repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/ExtensibilityTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.fressian.Reader;
import org.fressian.Writer;
import org.fressian.handlers.ReadHandler;
import org.fressian.handlers.WriteHandler;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class ExtensibilityTest {
private static final String Edn = "#dh{:dumb [#MyDumbClass{:version 1, :str \"str\"}]}";
@BeforeEach
public void setup() {
DynamicObject.registerType(DumbClass.class, new DumbClassTranslator());
DynamicObject.registerTag(DumbClassHolder.class, "dh");
DynamicObject.registerType(DumbClass.class, "dumb", new DumbClassReader(), new DumbClassWriter());
}
@AfterEach
public void teardown() {
DynamicObject.deregisterType(DumbClass.class);
DynamicObject.deregisterTag(DumbClassHolder.class);
}
@Test
public void roundTrip() {
DumbClassHolder holder = deserialize(Edn, DumbClassHolder.class);
String serialized = serialize(holder);
assertEquivalent(Edn, serialized);
assertEquals(new DumbClass(1, "str"), holder.dumb().get(0)); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/ExtensibilityTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.fressian.Reader;
import org.fressian.Writer;
import org.fressian.handlers.ReadHandler;
import org.fressian.handlers.WriteHandler;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class ExtensibilityTest {
private static final String Edn = "#dh{:dumb [#MyDumbClass{:version 1, :str \"str\"}]}";
@BeforeEach
public void setup() {
DynamicObject.registerType(DumbClass.class, new DumbClassTranslator());
DynamicObject.registerTag(DumbClassHolder.class, "dh");
DynamicObject.registerType(DumbClass.class, "dumb", new DumbClassReader(), new DumbClassWriter());
}
@AfterEach
public void teardown() {
DynamicObject.deregisterType(DumbClass.class);
DynamicObject.deregisterTag(DumbClassHolder.class);
}
@Test
public void roundTrip() {
DumbClassHolder holder = deserialize(Edn, DumbClassHolder.class);
String serialized = serialize(holder);
assertEquivalent(Edn, serialized);
assertEquals(new DumbClass(1, "str"), holder.dumb().get(0)); | assertEquals(holder, fromFressianByteArray(toFressianByteArray(holder))); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/ExtensibilityTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.fressian.Reader;
import org.fressian.Writer;
import org.fressian.handlers.ReadHandler;
import org.fressian.handlers.WriteHandler;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class ExtensibilityTest {
private static final String Edn = "#dh{:dumb [#MyDumbClass{:version 1, :str \"str\"}]}";
@BeforeEach
public void setup() {
DynamicObject.registerType(DumbClass.class, new DumbClassTranslator());
DynamicObject.registerTag(DumbClassHolder.class, "dh");
DynamicObject.registerType(DumbClass.class, "dumb", new DumbClassReader(), new DumbClassWriter());
}
@AfterEach
public void teardown() {
DynamicObject.deregisterType(DumbClass.class);
DynamicObject.deregisterTag(DumbClassHolder.class);
}
@Test
public void roundTrip() {
DumbClassHolder holder = deserialize(Edn, DumbClassHolder.class);
String serialized = serialize(holder);
assertEquivalent(Edn, serialized);
assertEquals(new DumbClass(1, "str"), holder.dumb().get(0)); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/ExtensibilityTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static java.lang.String.format;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.fressian.Reader;
import org.fressian.Writer;
import org.fressian.handlers.ReadHandler;
import org.fressian.handlers.WriteHandler;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class ExtensibilityTest {
private static final String Edn = "#dh{:dumb [#MyDumbClass{:version 1, :str \"str\"}]}";
@BeforeEach
public void setup() {
DynamicObject.registerType(DumbClass.class, new DumbClassTranslator());
DynamicObject.registerTag(DumbClassHolder.class, "dh");
DynamicObject.registerType(DumbClass.class, "dumb", new DumbClassReader(), new DumbClassWriter());
}
@AfterEach
public void teardown() {
DynamicObject.deregisterType(DumbClass.class);
DynamicObject.deregisterTag(DumbClassHolder.class);
}
@Test
public void roundTrip() {
DumbClassHolder holder = deserialize(Edn, DumbClassHolder.class);
String serialized = serialize(holder);
assertEquivalent(Edn, serialized);
assertEquals(new DumbClass(1, "str"), holder.dumb().get(0)); | assertEquals(holder, fromFressianByteArray(toFressianByteArray(holder))); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/CollectionsTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.IntStream.range;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class CollectionsTest {
private static final Random Random = new Random();
private static final Base64.Encoder Encoder = Base64.getEncoder();
@BeforeEach
public void setup() {
DynamicObject.registerTag(ListSchema.class, "ls");
DynamicObject.registerTag(MapSchema.class, "ms");
DynamicObject.registerTag(SetSchema.class, "ss");
}
@AfterEach
public void teardown() {
DynamicObject.deregisterTag(ListSchema.class);
DynamicObject.deregisterTag(MapSchema.class);
DynamicObject.deregisterTag(SetSchema.class);
}
@Test
public void listOfStrings() { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/CollectionsTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.IntStream.range;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class CollectionsTest {
private static final Random Random = new Random();
private static final Base64.Encoder Encoder = Base64.getEncoder();
@BeforeEach
public void setup() {
DynamicObject.registerTag(ListSchema.class, "ls");
DynamicObject.registerTag(MapSchema.class, "ms");
DynamicObject.registerTag(SetSchema.class, "ss");
}
@AfterEach
public void teardown() {
DynamicObject.deregisterTag(ListSchema.class);
DynamicObject.deregisterTag(MapSchema.class);
DynamicObject.deregisterTag(SetSchema.class);
}
@Test
public void listOfStrings() { | ListSchema listSchema = deserialize("{:strings [\"one\" \"two\" \"three\"]}", ListSchema.class); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/CollectionsTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.IntStream.range;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | assertEquals(3, collect.get(1).intValue());
assertEquals(5, collect.get(2).intValue());
binaryRoundTrip(listSchema);
}
@Test
public void setOfStrings() {
SetSchema setSchema = deserialize("{:strings #{\"one\" \"two\" \"three\"}}", SetSchema.class);
Set<String> stringSet = setSchema.strings();
assertEquals(3, stringSet.size());
assertTrue(stringSet.contains("one"));
assertTrue(stringSet.contains("two"));
assertTrue(stringSet.contains("three"));
binaryRoundTrip(setSchema);
}
@Test
public void embeddedMap() {
String edn = "{:dictionary {\"key\" \"value\"}}";
MapSchema mapSchema = deserialize(edn, MapSchema.class);
assertEquals("value", mapSchema.dictionary().get("key"));
assertEquals(1, mapSchema.dictionary().size());
binaryRoundTrip(mapSchema);
}
@Test
public void listOfIntegers() {
ListSchema deserialized = deserialize("{:ints [nil 2 nil 4 nil]}", ListSchema.class);
List<Integer> builtList = asList(null, 2, null, 4, null);
| // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/CollectionsTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toMap;
import static java.util.stream.IntStream.range;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
assertEquals(3, collect.get(1).intValue());
assertEquals(5, collect.get(2).intValue());
binaryRoundTrip(listSchema);
}
@Test
public void setOfStrings() {
SetSchema setSchema = deserialize("{:strings #{\"one\" \"two\" \"three\"}}", SetSchema.class);
Set<String> stringSet = setSchema.strings();
assertEquals(3, stringSet.size());
assertTrue(stringSet.contains("one"));
assertTrue(stringSet.contains("two"));
assertTrue(stringSet.contains("three"));
binaryRoundTrip(setSchema);
}
@Test
public void embeddedMap() {
String edn = "{:dictionary {\"key\" \"value\"}}";
MapSchema mapSchema = deserialize(edn, MapSchema.class);
assertEquals("value", mapSchema.dictionary().get("key"));
assertEquals(1, mapSchema.dictionary().size());
binaryRoundTrip(mapSchema);
}
@Test
public void listOfIntegers() {
ListSchema deserialized = deserialize("{:ints [nil 2 nil 4 nil]}", ListSchema.class);
List<Integer> builtList = asList(null, 2, null, 4, null);
| ListSchema built = newInstance(ListSchema.class).ints(builtList); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/BuilderTest.java | // Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import clojure.lang.PersistentHashMap; | package com.github.rschmitt.dynamicobject;
public class BuilderTest {
@Test
public void createEmptyInstance() {
Buildable obj = DynamicObject.newInstance(Buildable.class);
assertEquals(PersistentHashMap.EMPTY, obj.getMap());
assertEquals("{}", DynamicObject.serialize(obj));
}
@Test
public void invokeBuilderMethod() {
Buildable obj = DynamicObject.newInstance(Buildable.class).str("string");
assertEquals("{:str \"string\"}", DynamicObject.serialize(obj));
assertEquals("string", obj.str());
}
@Test
public void invokeBuilderWithPrimitive() {
Buildable obj = DynamicObject.newInstance(Buildable.class).i(4).s((short) 127).l(Long.MAX_VALUE).d(3.14).f((float) 3.14); | // Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/BuilderTest.java
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import clojure.lang.PersistentHashMap;
package com.github.rschmitt.dynamicobject;
public class BuilderTest {
@Test
public void createEmptyInstance() {
Buildable obj = DynamicObject.newInstance(Buildable.class);
assertEquals(PersistentHashMap.EMPTY, obj.getMap());
assertEquals("{}", DynamicObject.serialize(obj));
}
@Test
public void invokeBuilderMethod() {
Buildable obj = DynamicObject.newInstance(Buildable.class).str("string");
assertEquals("{:str \"string\"}", DynamicObject.serialize(obj));
assertEquals("string", obj.str());
}
@Test
public void invokeBuilderWithPrimitive() {
Buildable obj = DynamicObject.newInstance(Buildable.class).i(4).s((short) 127).l(Long.MAX_VALUE).d(3.14).f((float) 3.14); | assertEquivalent("{:f 3.14, :d 3.14, :l 9223372036854775807, :s 127, :i 4}", DynamicObject.serialize(obj)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/CustomKeyTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class CustomKeyTest {
@Test
public void customKeywordSupport() {
String edn = "{:a-sample-int 5}"; | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/CustomKeyTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class CustomKeyTest {
@Test
public void customKeywordSupport() {
String edn = "{:a-sample-int 5}"; | KeywordInterface object = deserialize(edn, KeywordInterface.class); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/CustomKeyTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class CustomKeyTest {
@Test
public void customKeywordSupport() {
String edn = "{:a-sample-int 5}";
KeywordInterface object = deserialize(edn, KeywordInterface.class);
assertEquals(5, object.aSampleInt()); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/CustomKeyTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class CustomKeyTest {
@Test
public void customKeywordSupport() {
String edn = "{:a-sample-int 5}";
KeywordInterface object = deserialize(edn, KeywordInterface.class);
assertEquals(5, object.aSampleInt()); | assertEquals(object, newInstance(KeywordInterface.class).aSampleInt(5)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/SchemaCollectionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class SchemaCollectionTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(X.class, "X");
DynamicObject.registerTag(Coll.class, "Coll");
}
@AfterEach
public void teardown() {
DynamicObject.deregisterTag(Coll.class);
DynamicObject.deregisterTag(X.class);
}
@Test
public void list() { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/SchemaCollectionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class SchemaCollectionTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(X.class, "X");
DynamicObject.registerTag(Coll.class, "Coll");
}
@AfterEach
public void teardown() {
DynamicObject.deregisterTag(Coll.class);
DynamicObject.deregisterTag(X.class);
}
@Test
public void list() { | Coll expected = deserialize("#Coll{:list [#X{:y 1}, #X{:y 2}, #X{:y 3}]}", Coll.class); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/SchemaCollectionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class SchemaCollectionTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(X.class, "X");
DynamicObject.registerTag(Coll.class, "Coll");
}
@AfterEach
public void teardown() {
DynamicObject.deregisterTag(Coll.class);
DynamicObject.deregisterTag(X.class);
}
@Test
public void list() {
Coll expected = deserialize("#Coll{:list [#X{:y 1}, #X{:y 2}, #X{:y 3}]}", Coll.class);
List<X> list = new ArrayList<>(); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/SchemaCollectionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class SchemaCollectionTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(X.class, "X");
DynamicObject.registerTag(Coll.class, "Coll");
}
@AfterEach
public void teardown() {
DynamicObject.deregisterTag(Coll.class);
DynamicObject.deregisterTag(X.class);
}
@Test
public void list() {
Coll expected = deserialize("#Coll{:list [#X{:y 1}, #X{:y 2}, #X{:y 3}]}", Coll.class);
List<X> list = new ArrayList<>(); | list.add(newInstance(X.class).y(1)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/SchemaCollectionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; |
Coll actual = newInstance(Coll.class).set(set);
roundTripTest(expected, Coll.class);
roundTripTest(actual, Coll.class);
assertEquals(expected, actual);
assertEquals(set, expected.set());
assertEquals(set, actual.set());
assertEquals(actual.set(), set);
assertEquals(expected.set(), set);
}
@Test
public void map() {
Coll expected = deserialize("#Coll{:map {#X{:y 1}, #X{:y 2}}}", Coll.class);
Map<X, X> map = new HashMap<>();
map.put(newInstance(X.class).y(1), newInstance(X.class).y(2));
Coll actual = newInstance(Coll.class).map(map);
roundTripTest(expected, Coll.class);
roundTripTest(actual, Coll.class);
assertEquals(expected, actual);
assertEquals(map, expected.map());
assertEquals(map, actual.map());
assertEquals(actual.map(), map);
assertEquals(expected.map(), map);
}
private <D extends DynamicObject<D>> void roundTripTest(D obj, Class<D> type) { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/SchemaCollectionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Coll actual = newInstance(Coll.class).set(set);
roundTripTest(expected, Coll.class);
roundTripTest(actual, Coll.class);
assertEquals(expected, actual);
assertEquals(set, expected.set());
assertEquals(set, actual.set());
assertEquals(actual.set(), set);
assertEquals(expected.set(), set);
}
@Test
public void map() {
Coll expected = deserialize("#Coll{:map {#X{:y 1}, #X{:y 2}}}", Coll.class);
Map<X, X> map = new HashMap<>();
map.put(newInstance(X.class).y(1), newInstance(X.class).y(2));
Coll actual = newInstance(Coll.class).map(map);
roundTripTest(expected, Coll.class);
roundTripTest(actual, Coll.class);
assertEquals(expected, actual);
assertEquals(map, expected.map());
assertEquals(map, actual.map());
assertEquals(actual.map(), map);
assertEquals(expected.map(), map);
}
private <D extends DynamicObject<D>> void roundTripTest(D obj, Class<D> type) { | String edn = serialize(obj); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/NestingTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class NestingTest {
@Test
public void nestedInts() {
List<Integer> innerList = new ArrayList<>();
innerList.add(1);
innerList.add(2);
innerList.add(3);
List<List<Integer>> outerList = new ArrayList<>();
outerList.add(innerList);
Nested nested = DynamicObject.newInstance(Nested.class).nestedIntegers(outerList);
assertEquals(outerList, nested.nestedIntegers()); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/NestingTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class NestingTest {
@Test
public void nestedInts() {
List<Integer> innerList = new ArrayList<>();
innerList.add(1);
innerList.add(2);
innerList.add(3);
List<List<Integer>> outerList = new ArrayList<>();
outerList.add(innerList);
Nested nested = DynamicObject.newInstance(Nested.class).nestedIntegers(outerList);
assertEquals(outerList, nested.nestedIntegers()); | assertEquals("{:nestedIntegers [[1 2 3]]}", serialize(nested)); |
rschmitt/dynamic-object | src/main/java/com/github/rschmitt/dynamicobject/Unknown.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// @SuppressWarnings("rawtypes")
// public class ClojureStuff {
// public static final Map EmptyMap = (Map) read("{}");
// public static final Object EmptySet = read("#{}");
// public static final Object EmptyVector = read("[]");
// public static final Object Readers = read(":readers");
// public static final Object Default = read(":default");
//
// public static final IFn Assoc = var("clojure.core/assoc");
// public static final IFn AssocBang = var("clojure.core/assoc!");
// public static final IFn Bigint = var("clojure.core/bigint");
// public static final IFn Biginteger = var("clojure.core/biginteger");
// public static final IFn ConjBang = var("clojure.core/conj!");
// public static final IFn Deref = var("clojure.core/deref");
// public static final IFn Dissoc = var("clojure.core/dissoc");
// public static final IFn Eval = var("clojure.core/eval");
// public static final IFn Get = var("clojure.core/get");
// public static final IFn Memoize = var("clojure.core/memoize");
// public static final IFn MergeWith = var("clojure.core/merge-with");
// public static final IFn Meta = var("clojure.core/meta");
// public static final IFn Nth = var("clojure.core/nth");
// public static final IFn Persistent = var("clojure.core/persistent!");
// public static final IFn PreferMethod = var("clojure.core/prefer-method");
// public static final IFn PrOn = var("clojure.core/pr-on");
// public static final IFn Read = var("clojure.edn/read");
// public static final IFn ReadString = var("clojure.edn/read-string");
// public static final IFn RemoveMethod = var("clojure.core/remove-method");
// public static final IFn Transient = var("clojure.core/transient");
// public static final IFn VaryMeta = var("clojure.core/vary-meta");
//
// public static final Object PrintMethod = Deref.invoke(var("clojure.core/print-method"));
// public static final IFn CachedRead = (IFn) Memoize.invoke(var("clojure.edn/read-string"));
// public static final IFn Pprint;
// public static final IFn SimpleDispatch;
// public static final IFn Diff;
//
// public static final Map clojureReadHandlers;
// public static final Map clojureWriteHandlers;
//
// static {
// IFn require = var("clojure.core/require");
// require.invoke(read("clojure.pprint"));
// require.invoke(read("clojure.data"));
// require.invoke(read("clojure.data.fressian"));
//
// Pprint = var("clojure.pprint/pprint");
// Diff = var("clojure.data/diff");
//
// SimpleDispatch = (IFn) Deref.invoke(var("clojure.pprint/simple-dispatch"));
//
// clojureReadHandlers = (Map) Deref.invoke(var("clojure.data.fressian/clojure-read-handlers"));
// clojureWriteHandlers = (Map) Deref.invoke(var("clojure.data.fressian/clojure-write-handlers"));
// }
//
// public static Object cachedRead(String edn) {
// return CachedRead.invoke(edn);
// }
// }
| import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import com.github.rschmitt.dynamicobject.internal.ClojureStuff; | package com.github.rschmitt.dynamicobject;
/**
* A generic container for tagged Edn elements. This class preserves everything the Edn reader sees when an unknown
* reader tag is encountered.
*/
public class Unknown {
private final String tag;
private final Object element;
/**
* For internal use only. Serialize a tagged element of an unknown type.
*/
@SuppressWarnings("unused")
public static Object serialize(Unknown unknown, Writer w) throws IOException {
w.append('#');
w.append(unknown.getTag());
if (!(unknown.getElement() instanceof Map))
w.append(' '); | // Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// @SuppressWarnings("rawtypes")
// public class ClojureStuff {
// public static final Map EmptyMap = (Map) read("{}");
// public static final Object EmptySet = read("#{}");
// public static final Object EmptyVector = read("[]");
// public static final Object Readers = read(":readers");
// public static final Object Default = read(":default");
//
// public static final IFn Assoc = var("clojure.core/assoc");
// public static final IFn AssocBang = var("clojure.core/assoc!");
// public static final IFn Bigint = var("clojure.core/bigint");
// public static final IFn Biginteger = var("clojure.core/biginteger");
// public static final IFn ConjBang = var("clojure.core/conj!");
// public static final IFn Deref = var("clojure.core/deref");
// public static final IFn Dissoc = var("clojure.core/dissoc");
// public static final IFn Eval = var("clojure.core/eval");
// public static final IFn Get = var("clojure.core/get");
// public static final IFn Memoize = var("clojure.core/memoize");
// public static final IFn MergeWith = var("clojure.core/merge-with");
// public static final IFn Meta = var("clojure.core/meta");
// public static final IFn Nth = var("clojure.core/nth");
// public static final IFn Persistent = var("clojure.core/persistent!");
// public static final IFn PreferMethod = var("clojure.core/prefer-method");
// public static final IFn PrOn = var("clojure.core/pr-on");
// public static final IFn Read = var("clojure.edn/read");
// public static final IFn ReadString = var("clojure.edn/read-string");
// public static final IFn RemoveMethod = var("clojure.core/remove-method");
// public static final IFn Transient = var("clojure.core/transient");
// public static final IFn VaryMeta = var("clojure.core/vary-meta");
//
// public static final Object PrintMethod = Deref.invoke(var("clojure.core/print-method"));
// public static final IFn CachedRead = (IFn) Memoize.invoke(var("clojure.edn/read-string"));
// public static final IFn Pprint;
// public static final IFn SimpleDispatch;
// public static final IFn Diff;
//
// public static final Map clojureReadHandlers;
// public static final Map clojureWriteHandlers;
//
// static {
// IFn require = var("clojure.core/require");
// require.invoke(read("clojure.pprint"));
// require.invoke(read("clojure.data"));
// require.invoke(read("clojure.data.fressian"));
//
// Pprint = var("clojure.pprint/pprint");
// Diff = var("clojure.data/diff");
//
// SimpleDispatch = (IFn) Deref.invoke(var("clojure.pprint/simple-dispatch"));
//
// clojureReadHandlers = (Map) Deref.invoke(var("clojure.data.fressian/clojure-read-handlers"));
// clojureWriteHandlers = (Map) Deref.invoke(var("clojure.data.fressian/clojure-write-handlers"));
// }
//
// public static Object cachedRead(String edn) {
// return CachedRead.invoke(edn);
// }
// }
// Path: src/main/java/com/github/rschmitt/dynamicobject/Unknown.java
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import com.github.rschmitt.dynamicobject.internal.ClojureStuff;
package com.github.rschmitt.dynamicobject;
/**
* A generic container for tagged Edn elements. This class preserves everything the Edn reader sees when an unknown
* reader tag is encountered.
*/
public class Unknown {
private final String tag;
private final Object element;
/**
* For internal use only. Serialize a tagged element of an unknown type.
*/
@SuppressWarnings("unused")
public static Object serialize(Unknown unknown, Writer w) throws IOException {
w.append('#');
w.append(unknown.getTag());
if (!(unknown.getElement() instanceof Map))
w.append(' '); | ClojureStuff.PrOn.invoke(unknown.getElement(), w); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/InstantTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Instant;
import java.util.Date;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class InstantTest {
@Test
public void dateBuilder() {
Date expected = Date.from(Instant.parse("1985-04-12T23:20:50.52Z"));
| // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/InstantTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Instant;
import java.util.Date;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class InstantTest {
@Test
public void dateBuilder() {
Date expected = Date.from(Instant.parse("1985-04-12T23:20:50.52Z"));
| TimeWrapper timeWrapper = newInstance(TimeWrapper.class).date(expected); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/InstantTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Instant;
import java.util.Date;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class InstantTest {
@Test
public void dateBuilder() {
Date expected = Date.from(Instant.parse("1985-04-12T23:20:50.52Z"));
TimeWrapper timeWrapper = newInstance(TimeWrapper.class).date(expected);
assertEquals(expected, timeWrapper.date()); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/InstantTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Instant;
import java.util.Date;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class InstantTest {
@Test
public void dateBuilder() {
Date expected = Date.from(Instant.parse("1985-04-12T23:20:50.52Z"));
TimeWrapper timeWrapper = newInstance(TimeWrapper.class).date(expected);
assertEquals(expected, timeWrapper.date()); | assertEquals("{:date #inst \"1985-04-12T23:20:50.520-00:00\"}", serialize(timeWrapper)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/InstantTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Instant;
import java.util.Date;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class InstantTest {
@Test
public void dateBuilder() {
Date expected = Date.from(Instant.parse("1985-04-12T23:20:50.52Z"));
TimeWrapper timeWrapper = newInstance(TimeWrapper.class).date(expected);
assertEquals(expected, timeWrapper.date());
assertEquals("{:date #inst \"1985-04-12T23:20:50.520-00:00\"}", serialize(timeWrapper));
}
@Test
public void instantBuilder() {
Instant expected = Instant.parse("1985-04-12T23:20:50.52Z");
TimeWrapper timeWrapper = newInstance(TimeWrapper.class).instant(expected);
assertEquals(expected, timeWrapper.instant());
assertEquals("{:instant #inst \"1985-04-12T23:20:50.520-00:00\"}", serialize(timeWrapper));
}
@Test
public void dateParser() {
String edn = "{:date #inst \"1985-04-12T23:20:50.520-00:00\"}";
Date expected = Date.from(Instant.parse("1985-04-12T23:20:50.52Z"));
| // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/InstantTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.Instant;
import java.util.Date;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class InstantTest {
@Test
public void dateBuilder() {
Date expected = Date.from(Instant.parse("1985-04-12T23:20:50.52Z"));
TimeWrapper timeWrapper = newInstance(TimeWrapper.class).date(expected);
assertEquals(expected, timeWrapper.date());
assertEquals("{:date #inst \"1985-04-12T23:20:50.520-00:00\"}", serialize(timeWrapper));
}
@Test
public void instantBuilder() {
Instant expected = Instant.parse("1985-04-12T23:20:50.52Z");
TimeWrapper timeWrapper = newInstance(TimeWrapper.class).instant(expected);
assertEquals(expected, timeWrapper.instant());
assertEquals("{:instant #inst \"1985-04-12T23:20:50.520-00:00\"}", serialize(timeWrapper));
}
@Test
public void dateParser() {
String edn = "{:date #inst \"1985-04-12T23:20:50.520-00:00\"}";
Date expected = Date.from(Instant.parse("1985-04-12T23:20:50.52Z"));
| TimeWrapper timeWrapper = deserialize(edn, TimeWrapper.class); |
rschmitt/dynamic-object | src/main/java/com/github/rschmitt/dynamicobject/internal/Numerics.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Bigint = var("clojure.core/bigint");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Biginteger = var("clojure.core/biginteger");
| import java.math.BigInteger;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Bigint;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Biginteger; | package com.github.rschmitt.dynamicobject.internal;
/*
* This class deals with the numeric types that need to be converted to and from long/double/clojure.lang.BigInt.
*/
public class Numerics {
private static final Set<Class<?>> numericTypes;
private static final Map<Class<?>, Class<?>> numericConversions; | // Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Bigint = var("clojure.core/bigint");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Biginteger = var("clojure.core/biginteger");
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/Numerics.java
import java.math.BigInteger;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Bigint;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Biginteger;
package com.github.rschmitt.dynamicobject.internal;
/*
* This class deals with the numeric types that need to be converted to and from long/double/clojure.lang.BigInt.
*/
public class Numerics {
private static final Set<Class<?>> numericTypes;
private static final Map<Class<?>, Class<?>> numericConversions; | private static final Class<?> BigInt = Bigint.invoke(0).getClass(); |
rschmitt/dynamic-object | src/main/java/com/github/rschmitt/dynamicobject/internal/Numerics.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Bigint = var("clojure.core/bigint");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Biginteger = var("clojure.core/biginteger");
| import java.math.BigInteger;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Bigint;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Biginteger; | types.add(int.class);
types.add(Integer.class);
types.add(float.class);
types.add(Float.class);
types.add(short.class);
types.add(Short.class);
types.add(byte.class);
types.add(Byte.class);
types.add(BigInteger.class);
numericTypes = Collections.unmodifiableSet(types);
Map<Class<?>, Class<?>> conversions = new HashMap<>();
conversions.put(Byte.class, Long.class);
conversions.put(Short.class, Long.class);
conversions.put(Integer.class, Long.class);
conversions.put(Float.class, Double.class);
conversions.put(BigInteger.class, BigInt);
numericConversions = conversions;
}
static boolean isNumeric(Class<?> type) {
return numericTypes.contains(type);
}
static Object maybeDownconvert(Class<?> type, Object val) {
if (val == null) return null;
if (type.equals(int.class) || type.equals(Integer.class)) return ((Long) val).intValue();
if (type.equals(float.class) || type.equals(Float.class)) return ((Double) val).floatValue();
if (type.equals(short.class) || type.equals(Short.class)) return ((Long) val).shortValue();
if (type.equals(byte.class) || type.equals(Byte.class)) return ((Long) val).byteValue(); | // Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Bigint = var("clojure.core/bigint");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Biginteger = var("clojure.core/biginteger");
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/Numerics.java
import java.math.BigInteger;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Bigint;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Biginteger;
types.add(int.class);
types.add(Integer.class);
types.add(float.class);
types.add(Float.class);
types.add(short.class);
types.add(Short.class);
types.add(byte.class);
types.add(Byte.class);
types.add(BigInteger.class);
numericTypes = Collections.unmodifiableSet(types);
Map<Class<?>, Class<?>> conversions = new HashMap<>();
conversions.put(Byte.class, Long.class);
conversions.put(Short.class, Long.class);
conversions.put(Integer.class, Long.class);
conversions.put(Float.class, Double.class);
conversions.put(BigInteger.class, BigInt);
numericConversions = conversions;
}
static boolean isNumeric(Class<?> type) {
return numericTypes.contains(type);
}
static Object maybeDownconvert(Class<?> type, Object val) {
if (val == null) return null;
if (type.equals(int.class) || type.equals(Integer.class)) return ((Long) val).intValue();
if (type.equals(float.class) || type.equals(Float.class)) return ((Double) val).floatValue();
if (type.equals(short.class) || type.equals(Short.class)) return ((Long) val).shortValue();
if (type.equals(byte.class) || type.equals(Byte.class)) return ((Long) val).byteValue(); | if (type.equals(BigInt)) return Biginteger.invoke(val); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Assoc = var("clojure.core/assoc");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final Object Default = read(":default");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final Map EmptyMap = (Map) read("{}");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn ReadString = var("clojure.edn/read-string");
| import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Assoc;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Default;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.EmptyMap;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.ReadString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import clojure.lang.AFn; | package com.github.rschmitt.dynamicobject;
public class TestUtils {
private static final Object readerOpts = Assoc.invoke(EmptyMap, Default, getUnknownReader());
private static Object getUnknownReader() {
return new AFn() {
@Override
public Object invoke(Object arg1, Object arg2) {
return new Unknown(arg1.toString(), arg2);
}
};
}
public static Object genericRead(String str) { | // Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn Assoc = var("clojure.core/assoc");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final Object Default = read(":default");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final Map EmptyMap = (Map) read("{}");
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/internal/ClojureStuff.java
// public static final IFn ReadString = var("clojure.edn/read-string");
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Assoc;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.Default;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.EmptyMap;
import static com.github.rschmitt.dynamicobject.internal.ClojureStuff.ReadString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import clojure.lang.AFn;
package com.github.rschmitt.dynamicobject;
public class TestUtils {
private static final Object readerOpts = Assoc.invoke(EmptyMap, Default, getUnknownReader());
private static Object getUnknownReader() {
return new AFn() {
@Override
public Object invoke(Object arg1, Object arg2) {
return new Unknown(arg1.toString(), arg2);
}
};
}
public static Object genericRead(String str) { | return ReadString.invoke(readerOpts, str); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class RecursionTest {
@BeforeEach
public void setup() {
try {
DynamicObject.deregisterTag(LinkedList.class);
} catch (NullPointerException ignore) { }
}
@Test
public void recursion() { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class RecursionTest {
@BeforeEach
public void setup() {
try {
DynamicObject.deregisterTag(LinkedList.class);
} catch (NullPointerException ignore) { }
}
@Test
public void recursion() { | LinkedList tail = newInstance(LinkedList.class).value(3); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class RecursionTest {
@BeforeEach
public void setup() {
try {
DynamicObject.deregisterTag(LinkedList.class);
} catch (NullPointerException ignore) { }
}
@Test
public void recursion() {
LinkedList tail = newInstance(LinkedList.class).value(3);
LinkedList middle = newInstance(LinkedList.class).value(2).next(tail);
LinkedList head = newInstance(LinkedList.class).value(1).next(middle);
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquals(1, head.value());
assertEquals(2, head.next().value());
assertEquals(3, head.next().next().value());
assertNull(head.next().next().next());
| // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class RecursionTest {
@BeforeEach
public void setup() {
try {
DynamicObject.deregisterTag(LinkedList.class);
} catch (NullPointerException ignore) { }
}
@Test
public void recursion() {
LinkedList tail = newInstance(LinkedList.class).value(3);
LinkedList middle = newInstance(LinkedList.class).value(2).next(tail);
LinkedList head = newInstance(LinkedList.class).value(1).next(middle);
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquals(1, head.value());
assertEquals(2, head.next().value());
assertEquals(3, head.next().next().value());
assertNull(head.next().next().next());
| assertEquivalent("{:next {:next {:value 3}, :value 2}, :value 1}", serialize(head)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class RecursionTest {
@BeforeEach
public void setup() {
try {
DynamicObject.deregisterTag(LinkedList.class);
} catch (NullPointerException ignore) { }
}
@Test
public void recursion() {
LinkedList tail = newInstance(LinkedList.class).value(3);
LinkedList middle = newInstance(LinkedList.class).value(2).next(tail);
LinkedList head = newInstance(LinkedList.class).value(1).next(middle);
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquals(1, head.value());
assertEquals(2, head.next().value());
assertEquals(3, head.next().next().value());
assertNull(head.next().next().next());
| // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class RecursionTest {
@BeforeEach
public void setup() {
try {
DynamicObject.deregisterTag(LinkedList.class);
} catch (NullPointerException ignore) { }
}
@Test
public void recursion() {
LinkedList tail = newInstance(LinkedList.class).value(3);
LinkedList middle = newInstance(LinkedList.class).value(2).next(tail);
LinkedList head = newInstance(LinkedList.class).value(1).next(middle);
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquals(1, head.value());
assertEquals(2, head.next().value());
assertEquals(3, head.next().next().value());
assertNull(head.next().next().next());
| assertEquivalent("{:next {:next {:value 3}, :value 2}, :value 1}", serialize(head)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; |
roundTrip(tail, true);
roundTrip(middle, true);
roundTrip(head, true);
assertEquivalent("#LinkedList{:value 3}", serialize(tail));
assertEquivalent("#LinkedList{:next #LinkedList{:value 3}, :value 2}", serialize(middle));
assertEquivalent("#LinkedList{:next #LinkedList{:next #LinkedList{:value 3}, :value 2}, :value 1}", serialize(head));
}
@Test
public void deregisteringTheTagRemovesItFromSerializedOutput() {
DynamicObject.registerTag(LinkedList.class, "LinkedList");
LinkedList tail = newInstance(LinkedList.class).value(3);
LinkedList middle = newInstance(LinkedList.class).value(2).next(tail);
LinkedList head = newInstance(LinkedList.class).value(1).next(middle);
DynamicObject.deregisterTag(LinkedList.class);
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquivalent("{:next {:next {:value 3}, :value 2}, :value 1}", serialize(head));
assertEquivalent("{:next {:value 3}, :value 2}", serialize(middle));
assertEquivalent("{:value 3}", serialize(tail));
}
@Test
public void registeringTheTagDoesNotAffectEqualityOfDeserializedInstances() { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
roundTrip(tail, true);
roundTrip(middle, true);
roundTrip(head, true);
assertEquivalent("#LinkedList{:value 3}", serialize(tail));
assertEquivalent("#LinkedList{:next #LinkedList{:value 3}, :value 2}", serialize(middle));
assertEquivalent("#LinkedList{:next #LinkedList{:next #LinkedList{:value 3}, :value 2}, :value 1}", serialize(head));
}
@Test
public void deregisteringTheTagRemovesItFromSerializedOutput() {
DynamicObject.registerTag(LinkedList.class, "LinkedList");
LinkedList tail = newInstance(LinkedList.class).value(3);
LinkedList middle = newInstance(LinkedList.class).value(2).next(tail);
LinkedList head = newInstance(LinkedList.class).value(1).next(middle);
DynamicObject.deregisterTag(LinkedList.class);
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquivalent("{:next {:next {:value 3}, :value 2}, :value 1}", serialize(head));
assertEquivalent("{:next {:value 3}, :value 2}", serialize(middle));
assertEquivalent("{:value 3}", serialize(tail));
}
@Test
public void registeringTheTagDoesNotAffectEqualityOfDeserializedInstances() { | LinkedList obj1 = DynamicObject.deserialize("{:value 1, :next {:value 2, :next {:value 3}}}", LinkedList.class); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; |
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquivalent("{:next {:next {:value 3}, :value 2}, :value 1}", serialize(head));
assertEquivalent("{:next {:value 3}, :value 2}", serialize(middle));
assertEquivalent("{:value 3}", serialize(tail));
}
@Test
public void registeringTheTagDoesNotAffectEqualityOfDeserializedInstances() {
LinkedList obj1 = DynamicObject.deserialize("{:value 1, :next {:value 2, :next {:value 3}}}", LinkedList.class);
DynamicObject.registerTag(LinkedList.class, "LinkedList");
LinkedList obj2 = DynamicObject.deserialize("#LinkedList{:value 1, :next #LinkedList{:value 2, :next #LinkedList{:value 3}}}", LinkedList.class);
DynamicObject.deregisterTag(LinkedList.class);
LinkedList next = obj1.next().next();
LinkedList next2 = obj1.next().next();
assertEquals(next, next2);
assertTrue(next.equals(next2));
assertTrue(obj1.equals(obj2));
assertEquals(obj1.next(), obj2.next());
assertEquals(obj1, obj2);
assertEquals(DynamicObject.serialize(obj1), DynamicObject.serialize(obj2));
}
private void roundTrip(LinkedList linkedList, boolean binary) {
assertEquals(linkedList, deserialize(serialize(linkedList), LinkedList.class));
if (binary) | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquivalent("{:next {:next {:value 3}, :value 2}, :value 1}", serialize(head));
assertEquivalent("{:next {:value 3}, :value 2}", serialize(middle));
assertEquivalent("{:value 3}", serialize(tail));
}
@Test
public void registeringTheTagDoesNotAffectEqualityOfDeserializedInstances() {
LinkedList obj1 = DynamicObject.deserialize("{:value 1, :next {:value 2, :next {:value 3}}}", LinkedList.class);
DynamicObject.registerTag(LinkedList.class, "LinkedList");
LinkedList obj2 = DynamicObject.deserialize("#LinkedList{:value 1, :next #LinkedList{:value 2, :next #LinkedList{:value 3}}}", LinkedList.class);
DynamicObject.deregisterTag(LinkedList.class);
LinkedList next = obj1.next().next();
LinkedList next2 = obj1.next().next();
assertEquals(next, next2);
assertTrue(next.equals(next2));
assertTrue(obj1.equals(obj2));
assertEquals(obj1.next(), obj2.next());
assertEquals(obj1, obj2);
assertEquals(DynamicObject.serialize(obj1), DynamicObject.serialize(obj2));
}
private void roundTrip(LinkedList linkedList, boolean binary) {
assertEquals(linkedList, deserialize(serialize(linkedList), LinkedList.class));
if (binary) | assertEquals(linkedList, fromFressianByteArray(toFressianByteArray(linkedList))); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; |
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquivalent("{:next {:next {:value 3}, :value 2}, :value 1}", serialize(head));
assertEquivalent("{:next {:value 3}, :value 2}", serialize(middle));
assertEquivalent("{:value 3}", serialize(tail));
}
@Test
public void registeringTheTagDoesNotAffectEqualityOfDeserializedInstances() {
LinkedList obj1 = DynamicObject.deserialize("{:value 1, :next {:value 2, :next {:value 3}}}", LinkedList.class);
DynamicObject.registerTag(LinkedList.class, "LinkedList");
LinkedList obj2 = DynamicObject.deserialize("#LinkedList{:value 1, :next #LinkedList{:value 2, :next #LinkedList{:value 3}}}", LinkedList.class);
DynamicObject.deregisterTag(LinkedList.class);
LinkedList next = obj1.next().next();
LinkedList next2 = obj1.next().next();
assertEquals(next, next2);
assertTrue(next.equals(next2));
assertTrue(obj1.equals(obj2));
assertEquals(obj1.next(), obj2.next());
assertEquals(obj1, obj2);
assertEquals(DynamicObject.serialize(obj1), DynamicObject.serialize(obj2));
}
private void roundTrip(LinkedList linkedList, boolean binary) {
assertEquals(linkedList, deserialize(serialize(linkedList), LinkedList.class));
if (binary) | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
//
// Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/RecursionTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
roundTrip(tail, false);
roundTrip(middle, false);
roundTrip(head, false);
assertEquivalent("{:next {:next {:value 3}, :value 2}, :value 1}", serialize(head));
assertEquivalent("{:next {:value 3}, :value 2}", serialize(middle));
assertEquivalent("{:value 3}", serialize(tail));
}
@Test
public void registeringTheTagDoesNotAffectEqualityOfDeserializedInstances() {
LinkedList obj1 = DynamicObject.deserialize("{:value 1, :next {:value 2, :next {:value 3}}}", LinkedList.class);
DynamicObject.registerTag(LinkedList.class, "LinkedList");
LinkedList obj2 = DynamicObject.deserialize("#LinkedList{:value 1, :next #LinkedList{:value 2, :next #LinkedList{:value 3}}}", LinkedList.class);
DynamicObject.deregisterTag(LinkedList.class);
LinkedList next = obj1.next().next();
LinkedList next2 = obj1.next().next();
assertEquals(next, next2);
assertTrue(next.equals(next2));
assertTrue(obj1.equals(obj2));
assertEquals(obj1.next(), obj2.next());
assertEquals(obj1, obj2);
assertEquals(DynamicObject.serialize(obj1), DynamicObject.serialize(obj2));
}
private void roundTrip(LinkedList linkedList, boolean binary) {
assertEquals(linkedList, deserialize(serialize(linkedList), LinkedList.class));
if (binary) | assertEquals(linkedList, fromFressianByteArray(toFressianByteArray(linkedList))); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/MethodHandleTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.UUID;
import java.util.function.BiFunction;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class MethodHandleTest {
private static final UUID ReceiptHandle = UUID.randomUUID();
@Test
public void buildPolymorphically() {
String edn = "{:command \"start the reactor\"}";
QueueMessage queueMessage = deserializeAndAttachMetadata(edn, QueueMessage::receiptHandle, QueueMessage.class);
assertEquals(ReceiptHandle, queueMessage.receiptHandle());
assertEquals("start the reactor", queueMessage.command());
}
private <T> T deserializeAndAttachMetadata(String edn, BiFunction<T, UUID, T> receiptHandleMetadataBuilder, Class<T> type) { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/MethodHandleTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.UUID;
import java.util.function.BiFunction;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class MethodHandleTest {
private static final UUID ReceiptHandle = UUID.randomUUID();
@Test
public void buildPolymorphically() {
String edn = "{:command \"start the reactor\"}";
QueueMessage queueMessage = deserializeAndAttachMetadata(edn, QueueMessage::receiptHandle, QueueMessage.class);
assertEquals(ReceiptHandle, queueMessage.receiptHandle());
assertEquals("start the reactor", queueMessage.command());
}
private <T> T deserializeAndAttachMetadata(String edn, BiFunction<T, UUID, T> receiptHandleMetadataBuilder, Class<T> type) { | T instance = deserialize(edn, type); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/ColliderTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
| import static com.github.rschmitt.collider.Collider.clojureList;
import static com.github.rschmitt.collider.Collider.clojureMap;
import static com.github.rschmitt.collider.Collider.clojureSet;
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.github.rschmitt.collider.ClojureList;
import com.github.rschmitt.collider.ClojureMap;
import com.github.rschmitt.collider.ClojureSet; | package com.github.rschmitt.dynamicobject;
public class ColliderTest {
static final Batch emptyBatch = newInstance(Batch.class);
static final Instant inst = Instant.parse("1985-04-12T23:20:50.52Z");
@BeforeAll
public static void setup() {
DynamicObject.registerTag(Batch.class, "batch");
}
@Test
public void clojureMapDeserialization() throws Exception { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/ColliderTest.java
import static com.github.rschmitt.collider.Collider.clojureList;
import static com.github.rschmitt.collider.Collider.clojureMap;
import static com.github.rschmitt.collider.Collider.clojureSet;
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.github.rschmitt.collider.ClojureList;
import com.github.rschmitt.collider.ClojureMap;
import com.github.rschmitt.collider.ClojureSet;
package com.github.rschmitt.dynamicobject;
public class ColliderTest {
static final Batch emptyBatch = newInstance(Batch.class);
static final Instant inst = Instant.parse("1985-04-12T23:20:50.52Z");
@BeforeAll
public static void setup() {
DynamicObject.registerTag(Batch.class, "batch");
}
@Test
public void clojureMapDeserialization() throws Exception { | Batch batch = deserialize("{:map {\"key\" 3}}", Batch.class); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/ColliderTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
| import static com.github.rschmitt.collider.Collider.clojureList;
import static com.github.rschmitt.collider.Collider.clojureMap;
import static com.github.rschmitt.collider.Collider.clojureSet;
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.github.rschmitt.collider.ClojureList;
import com.github.rschmitt.collider.ClojureMap;
import com.github.rschmitt.collider.ClojureSet; | public void mapBuilders() throws Exception {
ClojureMap<String, Integer> map = clojureMap("key", 3);
Batch batch = emptyBatch.map2(map);
assertEquals(map, batch.map());
fressianRoundTrip(batch);
}
@Test
public void setBuilders() throws Exception {
ClojureSet<Instant> set = clojureSet(inst);
Batch batch = emptyBatch.set2(set);
assertEquals(set, batch.set());
fressianRoundTrip(batch);
}
@Test
public void listBuilders() throws Exception {
ClojureList<Optional<String>> list = clojureList(of("a"), empty(), of("c"));
Batch batch = emptyBatch.list2(list);
assertEquals(list, batch.list());
fressianRoundTrip(batch);
}
private void fressianRoundTrip(Batch batch) { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/ColliderTest.java
import static com.github.rschmitt.collider.Collider.clojureList;
import static com.github.rschmitt.collider.Collider.clojureMap;
import static com.github.rschmitt.collider.Collider.clojureSet;
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.github.rschmitt.collider.ClojureList;
import com.github.rschmitt.collider.ClojureMap;
import com.github.rschmitt.collider.ClojureSet;
public void mapBuilders() throws Exception {
ClojureMap<String, Integer> map = clojureMap("key", 3);
Batch batch = emptyBatch.map2(map);
assertEquals(map, batch.map());
fressianRoundTrip(batch);
}
@Test
public void setBuilders() throws Exception {
ClojureSet<Instant> set = clojureSet(inst);
Batch batch = emptyBatch.set2(set);
assertEquals(set, batch.set());
fressianRoundTrip(batch);
}
@Test
public void listBuilders() throws Exception {
ClojureList<Optional<String>> list = clojureList(of("a"), empty(), of("c"));
Batch batch = emptyBatch.list2(list);
assertEquals(list, batch.list());
fressianRoundTrip(batch);
}
private void fressianRoundTrip(Batch batch) { | Batch actual = fromFressianByteArray(toFressianByteArray(batch)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/ColliderTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
| import static com.github.rschmitt.collider.Collider.clojureList;
import static com.github.rschmitt.collider.Collider.clojureMap;
import static com.github.rschmitt.collider.Collider.clojureSet;
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.github.rschmitt.collider.ClojureList;
import com.github.rschmitt.collider.ClojureMap;
import com.github.rschmitt.collider.ClojureSet; | public void mapBuilders() throws Exception {
ClojureMap<String, Integer> map = clojureMap("key", 3);
Batch batch = emptyBatch.map2(map);
assertEquals(map, batch.map());
fressianRoundTrip(batch);
}
@Test
public void setBuilders() throws Exception {
ClojureSet<Instant> set = clojureSet(inst);
Batch batch = emptyBatch.set2(set);
assertEquals(set, batch.set());
fressianRoundTrip(batch);
}
@Test
public void listBuilders() throws Exception {
ClojureList<Optional<String>> list = clojureList(of("a"), empty(), of("c"));
Batch batch = emptyBatch.list2(list);
assertEquals(list, batch.list());
fressianRoundTrip(batch);
}
private void fressianRoundTrip(Batch batch) { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/ColliderTest.java
import static com.github.rschmitt.collider.Collider.clojureList;
import static com.github.rschmitt.collider.Collider.clojureMap;
import static com.github.rschmitt.collider.Collider.clojureSet;
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.github.rschmitt.collider.ClojureList;
import com.github.rschmitt.collider.ClojureMap;
import com.github.rschmitt.collider.ClojureSet;
public void mapBuilders() throws Exception {
ClojureMap<String, Integer> map = clojureMap("key", 3);
Batch batch = emptyBatch.map2(map);
assertEquals(map, batch.map());
fressianRoundTrip(batch);
}
@Test
public void setBuilders() throws Exception {
ClojureSet<Instant> set = clojureSet(inst);
Batch batch = emptyBatch.set2(set);
assertEquals(set, batch.set());
fressianRoundTrip(batch);
}
@Test
public void listBuilders() throws Exception {
ClojureList<Optional<String>> list = clojureList(of("a"), empty(), of("c"));
Batch batch = emptyBatch.list2(list);
assertEquals(list, batch.list());
fressianRoundTrip(batch);
}
private void fressianRoundTrip(Batch batch) { | Batch actual = fromFressianByteArray(toFressianByteArray(batch)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
| // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
| ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
| // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
| assertEquals(edn, serialize(arbitraryPrecision)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision)); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision)); | assertEquals(newInstance(ArbitraryPrecision.class).bigDecimal(new BigDecimal("3.14159")), arbitraryPrecision); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision));
assertEquals(newInstance(ArbitraryPrecision.class).bigDecimal(new BigDecimal("3.14159")), arbitraryPrecision);
binaryRoundTrip(arbitraryPrecision);
}
@Test
public void BigInteger() {
String edn = "#ap{:bigInteger 9234812039419082756912384500123N}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision));
assertEquals(newInstance(ArbitraryPrecision.class).bigInteger(new BigInteger("9234812039419082756912384500123")), arbitraryPrecision);
binaryRoundTrip(arbitraryPrecision);
}
private void binaryRoundTrip(Object expected) { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision));
assertEquals(newInstance(ArbitraryPrecision.class).bigDecimal(new BigDecimal("3.14159")), arbitraryPrecision);
binaryRoundTrip(arbitraryPrecision);
}
@Test
public void BigInteger() {
String edn = "#ap{:bigInteger 9234812039419082756912384500123N}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision));
assertEquals(newInstance(ArbitraryPrecision.class).bigInteger(new BigInteger("9234812039419082756912384500123")), arbitraryPrecision);
binaryRoundTrip(arbitraryPrecision);
}
private void binaryRoundTrip(Object expected) { | Object actual = fromFressianByteArray(toFressianByteArray(expected)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision));
assertEquals(newInstance(ArbitraryPrecision.class).bigDecimal(new BigDecimal("3.14159")), arbitraryPrecision);
binaryRoundTrip(arbitraryPrecision);
}
@Test
public void BigInteger() {
String edn = "#ap{:bigInteger 9234812039419082756912384500123N}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision));
assertEquals(newInstance(ArbitraryPrecision.class).bigInteger(new BigInteger("9234812039419082756912384500123")), arbitraryPrecision);
binaryRoundTrip(arbitraryPrecision);
}
private void binaryRoundTrip(Object expected) { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T fromFressianByteArray(byte[] bytes) {
// return FressianSerialization.fromFressianByteArray(bytes);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static byte[] toFressianByteArray(Object o) {
// return FressianSerialization.toFressianByteArray(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/NumberTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.fromFressianByteArray;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.toFressianByteArray;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.math.BigDecimal;
import java.math.BigInteger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class NumberTest {
@BeforeEach
public void setup() {
DynamicObject.registerTag(ArbitraryPrecision.class, "ap");
}
@Test
public void BigDecimal() {
String edn = "#ap{:bigDecimal 3.14159M}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision));
assertEquals(newInstance(ArbitraryPrecision.class).bigDecimal(new BigDecimal("3.14159")), arbitraryPrecision);
binaryRoundTrip(arbitraryPrecision);
}
@Test
public void BigInteger() {
String edn = "#ap{:bigInteger 9234812039419082756912384500123N}";
ArbitraryPrecision arbitraryPrecision = deserialize(edn, ArbitraryPrecision.class);
assertEquals(edn, serialize(arbitraryPrecision));
assertEquals(newInstance(ArbitraryPrecision.class).bigInteger(new BigInteger("9234812039419082756912384500123")), arbitraryPrecision);
binaryRoundTrip(arbitraryPrecision);
}
private void binaryRoundTrip(Object expected) { | Object actual = fromFressianByteArray(toFressianByteArray(expected)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/OptionalTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class OptionalTest {
@Test
public void valuePresent() { | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/OptionalTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class OptionalTest {
@Test
public void valuePresent() { | OptWrapper instance = deserialize("{:str \"value\"}", OptWrapper.class).validate(); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/OptionalTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test; | package com.github.rschmitt.dynamicobject;
public class OptionalTest {
@Test
public void valuePresent() {
OptWrapper instance = deserialize("{:str \"value\"}", OptWrapper.class).validate(); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/OptionalTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
package com.github.rschmitt.dynamicobject;
public class OptionalTest {
@Test
public void valuePresent() {
OptWrapper instance = deserialize("{:str \"value\"}", OptWrapper.class).validate(); | OptWrapper expected = newInstance(OptWrapper.class).str(Optional.of("value")).validate(); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/OptionalTest.java | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
| import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test; | assertEquals(some.rawStr(), Optional.of("some string"));
assertEquals(nothing.rawStr(), Optional.empty());
}
@Test
public void intPresent() {
OptWrapper instance = deserialize("{:i 24601}", OptWrapper.class).validate();
OptWrapper expected = newInstance(OptWrapper.class).i(Optional.of(24601)).validate();
assertEquals(Integer.valueOf(24601), instance.i().get());
assertEquals(expected, instance);
}
@Test
public void listPresent() {
OptWrapper instance = deserialize("{:ints [1 2 3]}", OptWrapper.class).validate();
OptWrapper expected = newInstance(OptWrapper.class).ints(Optional.of(asList(1, 2, 3))).validate();
assertEquals(asList(1, 2, 3), instance.ints().get());
assertEquals(expected, instance);
}
@Test
public void instantPresent() {
String edn = "{:inst #inst \"1985-04-12T23:20:50.520-00:00\"}";
Instant expected = Instant.parse("1985-04-12T23:20:50.52Z");
OptWrapper instance = deserialize(edn, OptWrapper.class).validate();
assertEquals(expected, instance.inst().get()); | // Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <T> T deserialize(String edn, Class<T> type) {
// return EdnSerialization.deserialize(edn, type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static <D extends DynamicObject<D>> D newInstance(Class<D> type) {
// return Instances.newInstance(type);
// }
//
// Path: src/main/java/com/github/rschmitt/dynamicobject/DynamicObject.java
// static String serialize(Object o) {
// return EdnSerialization.serialize(o);
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/OptionalTest.java
import static com.github.rschmitt.dynamicobject.DynamicObject.deserialize;
import static com.github.rschmitt.dynamicobject.DynamicObject.newInstance;
import static com.github.rschmitt.dynamicobject.DynamicObject.serialize;
import static java.util.Arrays.asList;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.Test;
assertEquals(some.rawStr(), Optional.of("some string"));
assertEquals(nothing.rawStr(), Optional.empty());
}
@Test
public void intPresent() {
OptWrapper instance = deserialize("{:i 24601}", OptWrapper.class).validate();
OptWrapper expected = newInstance(OptWrapper.class).i(Optional.of(24601)).validate();
assertEquals(Integer.valueOf(24601), instance.i().get());
assertEquals(expected, instance);
}
@Test
public void listPresent() {
OptWrapper instance = deserialize("{:ints [1 2 3]}", OptWrapper.class).validate();
OptWrapper expected = newInstance(OptWrapper.class).ints(Optional.of(asList(1, 2, 3))).validate();
assertEquals(asList(1, 2, 3), instance.ints().get());
assertEquals(expected, instance);
}
@Test
public void instantPresent() {
String edn = "{:inst #inst \"1985-04-12T23:20:50.520-00:00\"}";
Instant expected = Instant.parse("1985-04-12T23:20:50.52Z");
OptWrapper instance = deserialize(edn, OptWrapper.class).validate();
assertEquals(expected, instance.inst().get()); | assertEquals(edn, serialize(instance)); |
rschmitt/dynamic-object | src/test/java/com/github/rschmitt/dynamicobject/MergeTest.java | // Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
| import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | assertEquals("#M{:a nil}", DynamicObject.serialize(c));
}
@Test
public void twoFullObjects() {
Mergeable a = DynamicObject.deserialize("#M{:a \"first\"}", Mergeable.class);
Mergeable b = DynamicObject.deserialize("#M{:a \"second\"}", Mergeable.class);
Mergeable c = a.merge(b);
assertEquals("#M{:a \"second\"}", DynamicObject.serialize(c));
}
@Test
public void nullsDoNotReplaceNonNulls() {
Mergeable a = DynamicObject.deserialize("#M{:a \"first\"}", Mergeable.class);
Mergeable b = DynamicObject.deserialize("#M{:a nil}", Mergeable.class);
Mergeable c = a.merge(b);
assertEquals("#M{:a \"first\"}", DynamicObject.serialize(c));
}
@Test
public void mergeOutputSerializesCorrectly() {
Mergeable a = DynamicObject.deserialize("#M{:a \"outer\"}", Mergeable.class);
Mergeable b = DynamicObject.deserialize("#M{:m #M{:a \"inner\"}}", Mergeable.class);
Mergeable c = a.merge(b);
| // Path: src/test/java/com/github/rschmitt/dynamicobject/TestUtils.java
// public static void assertEquivalent(String expected, String actual) {
// assertEquals(genericRead(expected), genericRead(actual));
// }
// Path: src/test/java/com/github/rschmitt/dynamicobject/MergeTest.java
import static com.github.rschmitt.dynamicobject.TestUtils.assertEquivalent;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
assertEquals("#M{:a nil}", DynamicObject.serialize(c));
}
@Test
public void twoFullObjects() {
Mergeable a = DynamicObject.deserialize("#M{:a \"first\"}", Mergeable.class);
Mergeable b = DynamicObject.deserialize("#M{:a \"second\"}", Mergeable.class);
Mergeable c = a.merge(b);
assertEquals("#M{:a \"second\"}", DynamicObject.serialize(c));
}
@Test
public void nullsDoNotReplaceNonNulls() {
Mergeable a = DynamicObject.deserialize("#M{:a \"first\"}", Mergeable.class);
Mergeable b = DynamicObject.deserialize("#M{:a nil}", Mergeable.class);
Mergeable c = a.merge(b);
assertEquals("#M{:a \"first\"}", DynamicObject.serialize(c));
}
@Test
public void mergeOutputSerializesCorrectly() {
Mergeable a = DynamicObject.deserialize("#M{:a \"outer\"}", Mergeable.class);
Mergeable b = DynamicObject.deserialize("#M{:m #M{:a \"inner\"}}", Mergeable.class);
Mergeable c = a.merge(b);
| assertEquivalent("#M{:m #M{:a \"inner\"}, :a \"outer\"}", DynamicObject.serialize(c)); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat; | /*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@RunWith(Theories.class)
public class BashSecretPatternFactoryTest {
public static final @DataPoint String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
public static final @DataPoint String ANOTHER_SAMPLE_PASSWORD = "a'b\"c\\d(e)#";
public static final @DataPoint String ONE_MORE = "'\"'(foo)'\"'";
@DataPoints
public static List<String> generatePasswords() {
Random random = new Random(100);
List<String> passwords = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
// choose a (printable) character in the closed range [' ', '~']
// 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character
char next = (char) (' ' + random.nextInt('\u007f' - ' '));
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@ClassRule public static JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() { | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactoryTest.java
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@RunWith(Theories.class)
public class BashSecretPatternFactoryTest {
public static final @DataPoint String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
public static final @DataPoint String ANOTHER_SAMPLE_PASSWORD = "a'b\"c\\d(e)#";
public static final @DataPoint String ONE_MORE = "'\"'(foo)'\"'";
@DataPoints
public static List<String> generatePasswords() {
Random random = new Random(100);
List<String> passwords = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
// choose a (printable) character in the closed range [' ', '~']
// 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character
char next = (char) (' ' + random.nextInt('\u007f' - ' '));
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@ClassRule public static JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() { | assumeThat("bash", is(executable())); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat; | List<String> passwords = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
// choose a (printable) character in the closed range [' ', '~']
// 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character
char next = (char) (' ' + random.nextInt('\u007f' - ' '));
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@ClassRule public static JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() {
assumeThat("bash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException { | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactoryTest.java
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
List<String> passwords = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
// choose a (printable) character in the closed range [' ', '~']
// 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character
char next = (char) (' ' + random.nextInt('\u007f' - ' '));
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@ClassRule public static JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() {
assumeThat("bash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException { | j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("bash")); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat; |
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() {
assumeThat("bash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException {
j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("bash"));
project = j.createProject(WorkflowJob.class);
credentialsId = UUID.randomUUID().toString();
project.setDefinition(new CpsFlowDefinition(
"node {\n" +
" withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" +
" sh ': \"$CREDENTIALS\"'\n" + // : will expand its parameters and do nothing with them
" sh ': \"< $CREDENTIALS >\"'\n" + // surround credentials with identifiable text for partial quoting
" }\n" +
"}", true));
}
@Theory
public void credentialsAreMaskedInLogs(String credentials) throws Exception {
assumeThat(credentials, not(startsWith("****")));
| // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactoryTest.java
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() {
assumeThat("bash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException {
j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("bash"));
project = j.createProject(WorkflowJob.class);
credentialsId = UUID.randomUUID().toString();
project.setDefinition(new CpsFlowDefinition(
"node {\n" +
" withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" +
" sh ': \"$CREDENTIALS\"'\n" + // : will expand its parameters and do nothing with them
" sh ': \"< $CREDENTIALS >\"'\n" + // surround credentials with identifiable text for partial quoting
" }\n" +
"}", true));
}
@Theory
public void credentialsAreMaskedInLogs(String credentials) throws Exception {
assumeThat(credentials, not(startsWith("****")));
| CredentialsTestUtil.setStringCredentials(j.jenkins, credentialsId, credentials); |
jenkinsci/credentials-binding-plugin | src/main/java/org/jenkinsci/plugins/credentialsbinding/impl/UnbindableDir.java | // Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/BindingDescriptor.java
// public abstract class BindingDescriptor<C extends StandardCredentials> extends Descriptor<MultiBinding<C>> {
//
// protected abstract Class<C> type();
//
// /**
// * Determines whether this {@link MultiBinding} needs a workspace to evaluate.
// */
// public boolean requiresWorkspace() {
// return true;
// }
//
// public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item owner) {
// if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
// return new ListBoxModel();
// }
// // when configuring the job, you only want those credentials that are available to ACL.SYSTEM selectable
// // as we cannot select from a user's credentials unless they are the only user submitting the build
// // (which we cannot assume) thus ACL.SYSTEM is correct here.
// return new Model().withAll(CredentialsProvider.lookupCredentials(type(), owner, ACL.SYSTEM, Collections.emptyList()));
// }
//
// private final class Model extends AbstractIdCredentialsListBoxModel<Model,C> {
//
// @NonNull
// @Override
// protected String describe(@NonNull C c) {
// return CredentialsNameProvider.name(c);
// }
//
// }
//
// }
//
// Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/MultiBinding.java
// public interface Unbinder extends Serializable {
// /**
// * Performs any needed cleanup.
// * @param build The build. Cannot be null
// * @param workspace The workspace - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
// * @param launcher The launcher - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
// * @param listener The task listener. Cannot be null.
// */
// void unbind(@NonNull Run<?,?> build,
// @Nullable FilePath workspace,
// @Nullable Launcher launcher,
// @NonNull TaskListener listener) throws IOException, InterruptedException;
// }
| import java.io.IOException;
import java.util.UUID;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.jenkinsci.plugins.credentialsbinding.MultiBinding.Unbinder;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.slaves.WorkspaceList; | package org.jenkinsci.plugins.credentialsbinding.impl;
/**
* Convenience class for creating a secure temporary directory dedicated to writing credentials file(s), and getting a
* corresponding {@link Unbinder} instance.
*/
public class UnbindableDir {
private final FilePath dirPath; | // Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/BindingDescriptor.java
// public abstract class BindingDescriptor<C extends StandardCredentials> extends Descriptor<MultiBinding<C>> {
//
// protected abstract Class<C> type();
//
// /**
// * Determines whether this {@link MultiBinding} needs a workspace to evaluate.
// */
// public boolean requiresWorkspace() {
// return true;
// }
//
// public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item owner) {
// if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
// return new ListBoxModel();
// }
// // when configuring the job, you only want those credentials that are available to ACL.SYSTEM selectable
// // as we cannot select from a user's credentials unless they are the only user submitting the build
// // (which we cannot assume) thus ACL.SYSTEM is correct here.
// return new Model().withAll(CredentialsProvider.lookupCredentials(type(), owner, ACL.SYSTEM, Collections.emptyList()));
// }
//
// private final class Model extends AbstractIdCredentialsListBoxModel<Model,C> {
//
// @NonNull
// @Override
// protected String describe(@NonNull C c) {
// return CredentialsNameProvider.name(c);
// }
//
// }
//
// }
//
// Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/MultiBinding.java
// public interface Unbinder extends Serializable {
// /**
// * Performs any needed cleanup.
// * @param build The build. Cannot be null
// * @param workspace The workspace - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
// * @param launcher The launcher - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
// * @param listener The task listener. Cannot be null.
// */
// void unbind(@NonNull Run<?,?> build,
// @Nullable FilePath workspace,
// @Nullable Launcher launcher,
// @NonNull TaskListener listener) throws IOException, InterruptedException;
// }
// Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/impl/UnbindableDir.java
import java.io.IOException;
import java.util.UUID;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.jenkinsci.plugins.credentialsbinding.MultiBinding.Unbinder;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.slaves.WorkspaceList;
package org.jenkinsci.plugins.credentialsbinding.impl;
/**
* Convenience class for creating a secure temporary directory dedicated to writing credentials file(s), and getting a
* corresponding {@link Unbinder} instance.
*/
public class UnbindableDir {
private final FilePath dirPath; | private final Unbinder unbinder; |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/AlmquistShellSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat; | public static final @DataPoint String ANOTHER_SAMPLE_PASSWORD = "a'b\"c\\d(e)#";
public static final @DataPoint String ONE_MORE = "'\"'(foo)'\"'";
public static final @DataPoint String FULL_ASCII = "!\"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]^_ `abcdefghijklmno pqrstuvwxyz{|}~";
@DataPoints
public static List<String> generatePasswords() {
Random random = new Random(100);
List<String> passwords = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
// choose a (printable) character in the closed range [' ', '~']
// 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character
char next = (char) (' ' + random.nextInt('\u007f' - ' '));
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@ClassRule public static JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeAsh() {
// ash = Almquist shell, default one used in Alpine | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/AlmquistShellSecretPatternFactoryTest.java
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
public static final @DataPoint String ANOTHER_SAMPLE_PASSWORD = "a'b\"c\\d(e)#";
public static final @DataPoint String ONE_MORE = "'\"'(foo)'\"'";
public static final @DataPoint String FULL_ASCII = "!\"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]^_ `abcdefghijklmno pqrstuvwxyz{|}~";
@DataPoints
public static List<String> generatePasswords() {
Random random = new Random(100);
List<String> passwords = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
// choose a (printable) character in the closed range [' ', '~']
// 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character
char next = (char) (' ' + random.nextInt('\u007f' - ' '));
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@ClassRule public static JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeAsh() {
// ash = Almquist shell, default one used in Alpine | assumeThat("ash", is(executable())); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/AlmquistShellSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat; | for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
// choose a (printable) character in the closed range [' ', '~']
// 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character
char next = (char) (' ' + random.nextInt('\u007f' - ' '));
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@ClassRule public static JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeAsh() {
// ash = Almquist shell, default one used in Alpine
assumeThat("ash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException { | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/AlmquistShellSecretPatternFactoryTest.java
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
// choose a (printable) character in the closed range [' ', '~']
// 0x7f is DEL, 0x7e is ~, and space is the first printable ASCII character
char next = (char) (' ' + random.nextInt('\u007f' - ' '));
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@ClassRule public static JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeAsh() {
// ash = Almquist shell, default one used in Alpine
assumeThat("ash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException { | j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("ash")); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/AlmquistShellSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat; | public static void assumeAsh() {
// ash = Almquist shell, default one used in Alpine
assumeThat("ash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException {
j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("ash"));
project = j.createProject(WorkflowJob.class);
credentialsId = UUID.randomUUID().toString();
project.setDefinition(new CpsFlowDefinition(
"node {\n" +
" withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" +
" sh '''\n" +
" echo begin0 $CREDENTIALS end0\n" +
// begin2 => 2 for double quotes
" echo \"begin2 $CREDENTIALS end2\"\n" +
" '''\n" +
" }\n" +
"}", true));
}
@Theory
public void credentialsAreMaskedInLogs(String credentials) throws Exception {
assumeThat(credentials, not(startsWith("****")));
| // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/AlmquistShellSecretPatternFactoryTest.java
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
public static void assumeAsh() {
// ash = Almquist shell, default one used in Alpine
assumeThat("ash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException {
j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("ash"));
project = j.createProject(WorkflowJob.class);
credentialsId = UUID.randomUUID().toString();
project.setDefinition(new CpsFlowDefinition(
"node {\n" +
" withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" +
" sh '''\n" +
" echo begin0 $CREDENTIALS end0\n" +
// begin2 => 2 for double quotes
" echo \"begin2 $CREDENTIALS end2\"\n" +
" '''\n" +
" }\n" +
"}", true));
}
@Theory
public void credentialsAreMaskedInLogs(String credentials) throws Exception {
assumeThat(credentials, not(startsWith("****")));
| CredentialsTestUtil.setStringCredentials(j.jenkins, credentialsId, credentials); |
jenkinsci/credentials-binding-plugin | src/main/java/org/jenkinsci/plugins/credentialsbinding/MultiBinding.java | // Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/impl/CredentialNotFoundException.java
// public class CredentialNotFoundException extends AbortException {
// public CredentialNotFoundException(String message) {
// super(message);
// }
// }
| import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.IdCredentials;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Run;
import hudson.model.TaskListener;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import jenkins.model.Jenkins;
import org.apache.commons.collections.CollectionUtils;
import org.jenkinsci.plugins.credentialsbinding.impl.CredentialNotFoundException;
import org.kohsuke.stapler.DataBoundConstructor; | /*
* The MIT License
*
* Copyright 2015 Jesse Glick.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding;
/**
* A way of binding a kind of credentials to an environment variable during a build.
* @param <C> a kind of credentials
*/
public abstract class MultiBinding<C extends StandardCredentials> extends AbstractDescribableImpl<MultiBinding<C>> implements ExtensionPoint {
private final String credentialsId;
/** For use with {@link DataBoundConstructor}. */
protected MultiBinding(String credentialsId) {
this.credentialsId = credentialsId;
}
/** Type token. */
protected abstract Class<C> type();
/** Identifier of the credentials to be bound. */
public final String getCredentialsId() {
return credentialsId;
}
/** Result of {@link #bind}. */
public static final class MultiEnvironment implements Serializable {
private static final long serialVersionUID = 1;
@Deprecated
private transient Map<String,String> values;
private Map<String,String> secretValues;
private Map<String,String> publicValues;
private final Unbinder unbinder;
public MultiEnvironment(Map<String,String> secretValues) {
this(secretValues, Collections.emptyMap());
}
public MultiEnvironment(Map<String,String> secretValues, Map<String,String> publicValues) {
this(secretValues, publicValues, new NullUnbinder());
}
public MultiEnvironment(Map<String,String> secretValues, Unbinder unbinder) {
this(secretValues, Collections.emptyMap(), unbinder);
}
public MultiEnvironment(Map<String,String> secretValues, Map<String,String> publicValues, Unbinder unbinder) {
this.values = null;
this.secretValues = new LinkedHashMap<>(secretValues);
this.publicValues = new LinkedHashMap<>(publicValues);
if (!CollectionUtils.intersection(secretValues.keySet(), publicValues.keySet()).isEmpty()) {
throw new IllegalArgumentException("Cannot use the same key in both secretValues and publicValues");
}
this.unbinder = unbinder;
}
// To avoid de-serialization issues with newly added field (secretValues, publicValues)
private Object readResolve() {
if (values != null) {
secretValues = values;
publicValues = Collections.emptyMap();
values = null;
}
return this;
}
@Deprecated
public Map<String,String> getValues() {
return Collections.unmodifiableMap(secretValues);
}
public Map<String,String> getSecretValues() {
return Collections.unmodifiableMap(secretValues);
}
public Map<String,String> getPublicValues() {
return Collections.unmodifiableMap(publicValues);
}
public Unbinder getUnbinder() {
return unbinder;
}
}
/** Callback run at the end of a build. */
public interface Unbinder extends Serializable {
/**
* Performs any needed cleanup.
* @param build The build. Cannot be null
* @param workspace The workspace - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
* @param launcher The launcher - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
* @param listener The task listener. Cannot be null.
*/
void unbind(@NonNull Run<?,?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener) throws IOException, InterruptedException;
}
/** No-op callback. */
protected static final class NullUnbinder implements Unbinder {
private static final long serialVersionUID = 1;
@Override public void unbind(@NonNull Run<?, ?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener) {}
}
/**
* Sets up bindings for a build.
* @param build The build. Cannot be null
* @param workspace The workspace - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
* @param launcher The launcher - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
* @param listener The task listener. Cannot be null.
* @return The configured {@link MultiEnvironment}
*/
public abstract MultiEnvironment bind(@NonNull Run<?,?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener) throws IOException, InterruptedException;
/**
* @deprecated override {@link #variables(Run)}
*/
public Set<String> variables() {
return Collections.emptySet();
}
/** Defines keys expected to be set in {@link MultiEnvironment#getSecretValues()}, particularly any that might be sensitive. */ | // Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/impl/CredentialNotFoundException.java
// public class CredentialNotFoundException extends AbortException {
// public CredentialNotFoundException(String message) {
// super(message);
// }
// }
// Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/MultiBinding.java
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.IdCredentials;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.ExtensionPoint;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.model.Run;
import hudson.model.TaskListener;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import jenkins.model.Jenkins;
import org.apache.commons.collections.CollectionUtils;
import org.jenkinsci.plugins.credentialsbinding.impl.CredentialNotFoundException;
import org.kohsuke.stapler.DataBoundConstructor;
/*
* The MIT License
*
* Copyright 2015 Jesse Glick.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding;
/**
* A way of binding a kind of credentials to an environment variable during a build.
* @param <C> a kind of credentials
*/
public abstract class MultiBinding<C extends StandardCredentials> extends AbstractDescribableImpl<MultiBinding<C>> implements ExtensionPoint {
private final String credentialsId;
/** For use with {@link DataBoundConstructor}. */
protected MultiBinding(String credentialsId) {
this.credentialsId = credentialsId;
}
/** Type token. */
protected abstract Class<C> type();
/** Identifier of the credentials to be bound. */
public final String getCredentialsId() {
return credentialsId;
}
/** Result of {@link #bind}. */
public static final class MultiEnvironment implements Serializable {
private static final long serialVersionUID = 1;
@Deprecated
private transient Map<String,String> values;
private Map<String,String> secretValues;
private Map<String,String> publicValues;
private final Unbinder unbinder;
public MultiEnvironment(Map<String,String> secretValues) {
this(secretValues, Collections.emptyMap());
}
public MultiEnvironment(Map<String,String> secretValues, Map<String,String> publicValues) {
this(secretValues, publicValues, new NullUnbinder());
}
public MultiEnvironment(Map<String,String> secretValues, Unbinder unbinder) {
this(secretValues, Collections.emptyMap(), unbinder);
}
public MultiEnvironment(Map<String,String> secretValues, Map<String,String> publicValues, Unbinder unbinder) {
this.values = null;
this.secretValues = new LinkedHashMap<>(secretValues);
this.publicValues = new LinkedHashMap<>(publicValues);
if (!CollectionUtils.intersection(secretValues.keySet(), publicValues.keySet()).isEmpty()) {
throw new IllegalArgumentException("Cannot use the same key in both secretValues and publicValues");
}
this.unbinder = unbinder;
}
// To avoid de-serialization issues with newly added field (secretValues, publicValues)
private Object readResolve() {
if (values != null) {
secretValues = values;
publicValues = Collections.emptyMap();
values = null;
}
return this;
}
@Deprecated
public Map<String,String> getValues() {
return Collections.unmodifiableMap(secretValues);
}
public Map<String,String> getSecretValues() {
return Collections.unmodifiableMap(secretValues);
}
public Map<String,String> getPublicValues() {
return Collections.unmodifiableMap(publicValues);
}
public Unbinder getUnbinder() {
return unbinder;
}
}
/** Callback run at the end of a build. */
public interface Unbinder extends Serializable {
/**
* Performs any needed cleanup.
* @param build The build. Cannot be null
* @param workspace The workspace - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
* @param launcher The launcher - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
* @param listener The task listener. Cannot be null.
*/
void unbind(@NonNull Run<?,?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener) throws IOException, InterruptedException;
}
/** No-op callback. */
protected static final class NullUnbinder implements Unbinder {
private static final long serialVersionUID = 1;
@Override public void unbind(@NonNull Run<?, ?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener) {}
}
/**
* Sets up bindings for a build.
* @param build The build. Cannot be null
* @param workspace The workspace - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
* @param launcher The launcher - can be null if {@link BindingDescriptor#requiresWorkspace()} is false.
* @param listener The task listener. Cannot be null.
* @return The configured {@link MultiEnvironment}
*/
public abstract MultiEnvironment bind(@NonNull Run<?,?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener) throws IOException, InterruptedException;
/**
* @deprecated override {@link #variables(Run)}
*/
public Set<String> variables() {
return Collections.emptySet();
}
/** Defines keys expected to be set in {@link MultiEnvironment#getSecretValues()}, particularly any that might be sensitive. */ | public /*abstract*/ Set<String> variables(@NonNull Run<?,?> build) throws CredentialNotFoundException { |
jenkinsci/credentials-binding-plugin | src/main/java/org/jenkinsci/plugins/credentialsbinding/impl/ZipFileBinding.java | // Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/BindingDescriptor.java
// public abstract class BindingDescriptor<C extends StandardCredentials> extends Descriptor<MultiBinding<C>> {
//
// protected abstract Class<C> type();
//
// /**
// * Determines whether this {@link MultiBinding} needs a workspace to evaluate.
// */
// public boolean requiresWorkspace() {
// return true;
// }
//
// public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item owner) {
// if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
// return new ListBoxModel();
// }
// // when configuring the job, you only want those credentials that are available to ACL.SYSTEM selectable
// // as we cannot select from a user's credentials unless they are the only user submitting the build
// // (which we cannot assume) thus ACL.SYSTEM is correct here.
// return new Model().withAll(CredentialsProvider.lookupCredentials(type(), owner, ACL.SYSTEM, Collections.emptyList()));
// }
//
// private final class Model extends AbstractIdCredentialsListBoxModel<Model,C> {
//
// @NonNull
// @Override
// protected String describe(@NonNull C c) {
// return CredentialsNameProvider.name(c);
// }
//
// }
//
// }
| import hudson.util.FormValidation;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import jenkins.model.Jenkins;
import org.apache.commons.io.IOUtils;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.jenkinsci.plugins.plaincredentials.FileCredentials;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Item; | /*
* The MIT License
*
* Copyright 2013 jglick.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.impl;
public class ZipFileBinding extends AbstractOnDiskBinding<FileCredentials> {
@DataBoundConstructor public ZipFileBinding(String variable, String credentialsId) {
super(variable, credentialsId);
}
@Override protected Class<FileCredentials> type() {
return FileCredentials.class;
}
@Override protected final FilePath write(FileCredentials credentials, FilePath dir) throws IOException, InterruptedException {
FilePath secret = dir.child(credentials.getFileName());
secret.unzipFrom(credentials.getContent());
secret.chmod(0700); // note: it's a directory
return secret;
}
@Symbol("zip") | // Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/BindingDescriptor.java
// public abstract class BindingDescriptor<C extends StandardCredentials> extends Descriptor<MultiBinding<C>> {
//
// protected abstract Class<C> type();
//
// /**
// * Determines whether this {@link MultiBinding} needs a workspace to evaluate.
// */
// public boolean requiresWorkspace() {
// return true;
// }
//
// public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item owner) {
// if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
// return new ListBoxModel();
// }
// // when configuring the job, you only want those credentials that are available to ACL.SYSTEM selectable
// // as we cannot select from a user's credentials unless they are the only user submitting the build
// // (which we cannot assume) thus ACL.SYSTEM is correct here.
// return new Model().withAll(CredentialsProvider.lookupCredentials(type(), owner, ACL.SYSTEM, Collections.emptyList()));
// }
//
// private final class Model extends AbstractIdCredentialsListBoxModel<Model,C> {
//
// @NonNull
// @Override
// protected String describe(@NonNull C c) {
// return CredentialsNameProvider.name(c);
// }
//
// }
//
// }
// Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/impl/ZipFileBinding.java
import hudson.util.FormValidation;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import jenkins.model.Jenkins;
import org.apache.commons.io.IOUtils;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.jenkinsci.plugins.plaincredentials.FileCredentials;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Item;
/*
* The MIT License
*
* Copyright 2013 jglick.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.impl;
public class ZipFileBinding extends AbstractOnDiskBinding<FileCredentials> {
@DataBoundConstructor public ZipFileBinding(String variable, String credentialsId) {
super(variable, credentialsId);
}
@Override protected Class<FileCredentials> type() {
return FileCredentials.class;
}
@Override protected final FilePath write(FileCredentials credentials, FilePath dir) throws IOException, InterruptedException {
FilePath secret = dir.child(credentials.getFileName());
secret.unzipFrom(credentials.getContent());
secret.chmod(0700); // note: it's a directory
return secret;
}
@Symbol("zip") | @Extension public static class DescriptorImpl extends BindingDescriptor<FileCredentials> { |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BatchSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
| import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assume.assumeTrue;
import hudson.Functions;
import hudson.model.Result;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun; | /*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
public class BatchSecretPatternFactoryTest {
private static final String SIMPLE = "abcABC123";
private static final String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
private static final String ESCAPE = "^<^>^(^)^^^&^|";
// ALL_ASCII - [ < > " ' ^ $ | % ]
private static final String NON_DANGEROUS = "!#$*+,-./ 0123456789:;=? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]_ `abcdefghijklmno pqrstuvwxyz{}~";
// <>"'^$|
private static final String NON_DANGEROUS_IN_DOUBLE = "abc<def>$ghi|jkl";
// quoted form: "^^|\a\\"
private static final String NEEDS_QUOTING = "^|\\a\\";
private static final String ALL_ASCII = "!\"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]^_ `abcdefghijklmno pqrstuvwxyz{|}~";
@Rule
public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialPlainText;
private String credentialId;
@Before
public void assumeWindowsForBatch() {
assumeTrue(Functions.isWindows());
}
private void registerCredentials(String password) throws IOException {
this.credentialPlainText = password; | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BatchSecretPatternFactoryTest.java
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assume.assumeTrue;
import hudson.Functions;
import hudson.model.Result;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
public class BatchSecretPatternFactoryTest {
private static final String SIMPLE = "abcABC123";
private static final String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
private static final String ESCAPE = "^<^>^(^)^^^&^|";
// ALL_ASCII - [ < > " ' ^ $ | % ]
private static final String NON_DANGEROUS = "!#$*+,-./ 0123456789:;=? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]_ `abcdefghijklmno pqrstuvwxyz{}~";
// <>"'^$|
private static final String NON_DANGEROUS_IN_DOUBLE = "abc<def>$ghi|jkl";
// quoted form: "^^|\a\\"
private static final String NEEDS_QUOTING = "^|\\a\\";
private static final String ALL_ASCII = "!\"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]^_ `abcdefghijklmno pqrstuvwxyz{|}~";
@Rule
public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialPlainText;
private String credentialId;
@Before
public void assumeWindowsForBatch() {
assumeTrue(Functions.isWindows());
}
private void registerCredentials(String password) throws IOException {
this.credentialPlainText = password; | this.credentialId = CredentialsTestUtil.registerStringCredentials(j.jenkins, password); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactory2Test.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun; | /*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@For(BashSecretPatternFactory.class)
public class BashSecretPatternFactory2Test {
public @Rule JenkinsRule j = new JenkinsRule();
@Before
public void setUp() { | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactory2Test.java
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@For(BashSecretPatternFactory.class)
public class BashSecretPatternFactory2Test {
public @Rule JenkinsRule j = new JenkinsRule();
@Before
public void setUp() { | assumeThat("bash", is(executable())); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactory2Test.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun; | /*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@For(BashSecretPatternFactory.class)
public class BashSecretPatternFactory2Test {
public @Rule JenkinsRule j = new JenkinsRule();
@Before
public void setUp() {
assumeThat("bash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable())); | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactory2Test.java
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@For(BashSecretPatternFactory.class)
public class BashSecretPatternFactory2Test {
public @Rule JenkinsRule j = new JenkinsRule();
@Before
public void setUp() {
assumeThat("bash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable())); | j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("bash")); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactory2Test.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun; | /*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@For(BashSecretPatternFactory.class)
public class BashSecretPatternFactory2Test {
public @Rule JenkinsRule j = new JenkinsRule();
@Before
public void setUp() {
assumeThat("bash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("bash"));
}
@Test
// DO NOT DO THIS IN PRODUCTION; IT IS QUOTED WRONG
public void testSecretsWithBackslashesStillMaskedWhenUsedWithoutProperQuoting() throws Exception {
WorkflowJob project = j.createProject(WorkflowJob.class);
String password = "foo\\bar\\"; | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public class Executables {
// private static final String LOCATOR = Functions.isWindows() ? "where.exe" : "which";
//
// public static @CheckForNull
// String getPathToExecutable(@NonNull String executable) {
// try {
// Process process = new ProcessBuilder(LOCATOR, executable).start();
// List<String> output = IOUtils.readLines(process.getInputStream(), Charset.defaultCharset());
// if (process.waitFor() != 0) {
// return null;
// }
// return output.isEmpty() ? null : output.get(0);
// } catch (IOException | InterruptedException e) {
// return null;
// }
// }
//
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BashSecretPatternFactory2Test.java
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.For;
import org.jvnet.hudson.test.JenkinsRule;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import hudson.tasks.Shell;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.credentialsbinding.test.Executables;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@For(BashSecretPatternFactory.class)
public class BashSecretPatternFactory2Test {
public @Rule JenkinsRule j = new JenkinsRule();
@Before
public void setUp() {
assumeThat("bash", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
j.jenkins.getDescriptorByType(Shell.DescriptorImpl.class).setShell(Executables.getPathToExecutable("bash"));
}
@Test
// DO NOT DO THIS IN PRODUCTION; IT IS QUOTED WRONG
public void testSecretsWithBackslashesStillMaskedWhenUsedWithoutProperQuoting() throws Exception {
WorkflowJob project = j.createProject(WorkflowJob.class);
String password = "foo\\bar\\"; | String credentialsId = CredentialsTestUtil.registerStringCredentials(j.jenkins, password); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/PowerShellMaskerProviderTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.Rule; | /*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
public class PowerShellMaskerProviderTest {
private static final String SIMPLE = "abcABC123";
private static final String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
private static final String ALL_ASCII = "!\"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]^_ `abcdefghijklmno pqrstuvwxyz{|}~";
@Rule
public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialPlainText;
private String credentialId;
@Before
public void assumeWindowsForBatch() {
// TODO: pwsh is also a valid executable name
// https://github.com/jenkinsci/durable-task-plugin/pull/88 | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/PowerShellMaskerProviderTest.java
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.Rule;
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
public class PowerShellMaskerProviderTest {
private static final String SIMPLE = "abcABC123";
private static final String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
private static final String ALL_ASCII = "!\"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]^_ `abcdefghijklmno pqrstuvwxyz{|}~";
@Rule
public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialPlainText;
private String credentialId;
@Before
public void assumeWindowsForBatch() {
// TODO: pwsh is also a valid executable name
// https://github.com/jenkinsci/durable-task-plugin/pull/88 | assumeThat("powershell", is(executable())); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/PowerShellMaskerProviderTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.Rule; | /*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
public class PowerShellMaskerProviderTest {
private static final String SIMPLE = "abcABC123";
private static final String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
private static final String ALL_ASCII = "!\"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]^_ `abcdefghijklmno pqrstuvwxyz{|}~";
@Rule
public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialPlainText;
private String credentialId;
@Before
public void assumeWindowsForBatch() {
// TODO: pwsh is also a valid executable name
// https://github.com/jenkinsci/durable-task-plugin/pull/88
assumeThat("powershell", is(executable()));
}
private void registerCredentials(String password) throws IOException {
this.credentialPlainText = password; | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/PowerShellMaskerProviderTest.java
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.Rule;
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
public class PowerShellMaskerProviderTest {
private static final String SIMPLE = "abcABC123";
private static final String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
private static final String ALL_ASCII = "!\"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\\]^_ `abcdefghijklmno pqrstuvwxyz{|}~";
@Rule
public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialPlainText;
private String credentialId;
@Before
public void assumeWindowsForBatch() {
// TODO: pwsh is also a valid executable name
// https://github.com/jenkinsci/durable-task-plugin/pull/88
assumeThat("powershell", is(executable()));
}
private void registerCredentials(String password) throws IOException {
this.credentialPlainText = password; | this.credentialId = CredentialsTestUtil.registerStringCredentials(j.jenkins, password); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BourneShellSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat; | /*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@RunWith(Theories.class)
public class BourneShellSecretPatternFactoryTest {
public static final @DataPoint String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
public static final @DataPoint String ANOTHER_SAMPLE_PASSWORD = "a'b\"c\\d(e)#";
@DataPoints
public static List<String> generatePasswords() {
Random random = new Random(100);
List<String> passwords = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
char next = (char) (random.nextInt('~' - ' ' + 1) + ' '); // space = 0x20, tilde = 0x7E
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@Rule public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() { | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BourneShellSecretPatternFactoryTest.java
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
/*
* The MIT License
*
* Copyright (c) 2019 CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* 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 org.jenkinsci.plugins.credentialsbinding.masking;
@RunWith(Theories.class)
public class BourneShellSecretPatternFactoryTest {
public static final @DataPoint String SAMPLE_PASSWORD = "}#T14'GAz&H!{$U_";
public static final @DataPoint String ANOTHER_SAMPLE_PASSWORD = "a'b\"c\\d(e)#";
@DataPoints
public static List<String> generatePasswords() {
Random random = new Random(100);
List<String> passwords = new ArrayList<>(10);
for (int i = 0; i < 10; i++) {
int length = random.nextInt(24) + 8;
StringBuilder sb = new StringBuilder(length);
for (int j = 0; j < length; j++) {
char next = (char) (random.nextInt('~' - ' ' + 1) + ' '); // space = 0x20, tilde = 0x7E
sb.append(next);
}
passwords.add(sb.toString());
}
return passwords;
}
@Rule public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() { | assumeThat("sh", is(executable())); |
jenkinsci/credentials-binding-plugin | src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BourneShellSecretPatternFactoryTest.java | // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
| import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat; | @Rule public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() {
assumeThat("sh", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException {
project = j.createProject(WorkflowJob.class);
credentialsId = UUID.randomUUID().toString();
project.setDefinition(new CpsFlowDefinition(
"node {\n" +
" withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" +
" sh ': \"$CREDENTIALS\"'\n" + // : will expand its parameters and do nothing with them
" sh ': \"< $CREDENTIALS >\"'\n" +
" }\n" +
"}", true));
}
@Theory
public void credentialsAreMaskedInLogs(String credentials) throws Exception {
assumeThat(credentials, not(startsWith("****")));
| // Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/CredentialsTestUtil.java
// public class CredentialsTestUtil {
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider}.
// * Returns the generated credential id for the registered credentials.
// */
// public static String registerStringCredentials(ModelObject context, String value) throws IOException {
// String credentialsId = UUID.randomUUID().toString();
// setStringCredentials(context, credentialsId, value);
// return credentialsId;
// }
//
// /**
// * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
// * specified credentials id.
// */
// public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
// StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
// CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
// }
// }
//
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/test/Executables.java
// public static Matcher<String> executable() {
// return new CustomTypeSafeMatcher<String>("executable") {
// @Override
// protected boolean matchesSafely(String item) {
// try {
// return new ProcessBuilder(LOCATOR, item).start().waitFor() == 0;
// } catch (InterruptedException | IOException e) {
// return false;
// }
// }
// };
// }
// Path: src/test/java/org/jenkinsci/plugins/credentialsbinding/masking/BourneShellSecretPatternFactoryTest.java
import org.jenkinsci.plugins.credentialsbinding.test.CredentialsTestUtil;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.experimental.theories.DataPoint;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.JenkinsRule;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.jenkinsci.plugins.credentialsbinding.test.Executables.executable;
import static org.junit.Assume.assumeThat;
@Rule public JenkinsRule j = new JenkinsRule();
private WorkflowJob project;
private String credentialsId;
@BeforeClass
public static void assumeBash() {
assumeThat("sh", is(executable()));
// due to https://github.com/jenkinsci/durable-task-plugin/blob/e75123eda986f20a390d92cc892c3d206e60aefb/src/main/java/org/jenkinsci/plugins/durabletask/BourneShellScript.java#L149
// on Windows
assumeThat("nohup", is(executable()));
}
@Before
public void setUp() throws IOException {
project = j.createProject(WorkflowJob.class);
credentialsId = UUID.randomUUID().toString();
project.setDefinition(new CpsFlowDefinition(
"node {\n" +
" withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'CREDENTIALS')]) {\n" +
" sh ': \"$CREDENTIALS\"'\n" + // : will expand its parameters and do nothing with them
" sh ': \"< $CREDENTIALS >\"'\n" +
" }\n" +
"}", true));
}
@Theory
public void credentialsAreMaskedInLogs(String credentials) throws Exception {
assumeThat(credentials, not(startsWith("****")));
| CredentialsTestUtil.setStringCredentials(j.jenkins, credentialsId, credentials); |
jenkinsci/credentials-binding-plugin | src/main/java/org/jenkinsci/plugins/credentialsbinding/impl/FileBinding.java | // Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/BindingDescriptor.java
// public abstract class BindingDescriptor<C extends StandardCredentials> extends Descriptor<MultiBinding<C>> {
//
// protected abstract Class<C> type();
//
// /**
// * Determines whether this {@link MultiBinding} needs a workspace to evaluate.
// */
// public boolean requiresWorkspace() {
// return true;
// }
//
// public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item owner) {
// if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
// return new ListBoxModel();
// }
// // when configuring the job, you only want those credentials that are available to ACL.SYSTEM selectable
// // as we cannot select from a user's credentials unless they are the only user submitting the build
// // (which we cannot assume) thus ACL.SYSTEM is correct here.
// return new Model().withAll(CredentialsProvider.lookupCredentials(type(), owner, ACL.SYSTEM, Collections.emptyList()));
// }
//
// private final class Model extends AbstractIdCredentialsListBoxModel<Model,C> {
//
// @NonNull
// @Override
// protected String describe(@NonNull C c) {
// return CredentialsNameProvider.name(c);
// }
//
// }
//
// }
| import hudson.model.TaskListener;
import java.io.IOException;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.jenkinsci.plugins.plaincredentials.FileCredentials;
import org.kohsuke.stapler.DataBoundConstructor;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run; | FilePath secret = dir.child(credentials.getFileName());
secret.copyFrom(credentials.getContent());
secret.chmod(0400);
return secret;
}
@SuppressWarnings("unused")
@Deprecated
private static class UnbinderImpl implements Unbinder {
private static final long serialVersionUID = 1;
private final String dirName;
private UnbinderImpl(String dirName) {
this.dirName = dirName;
}
protected Object readResolve() {
return new UnbindableDir.UnbinderImpl(dirName);
}
@Override
public void unbind(@NonNull Run<?, ?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener) {
// replaced by the UnbindableDir.UnbinderImpl implementation
}
}
@Symbol("file") | // Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/BindingDescriptor.java
// public abstract class BindingDescriptor<C extends StandardCredentials> extends Descriptor<MultiBinding<C>> {
//
// protected abstract Class<C> type();
//
// /**
// * Determines whether this {@link MultiBinding} needs a workspace to evaluate.
// */
// public boolean requiresWorkspace() {
// return true;
// }
//
// public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item owner) {
// if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
// return new ListBoxModel();
// }
// // when configuring the job, you only want those credentials that are available to ACL.SYSTEM selectable
// // as we cannot select from a user's credentials unless they are the only user submitting the build
// // (which we cannot assume) thus ACL.SYSTEM is correct here.
// return new Model().withAll(CredentialsProvider.lookupCredentials(type(), owner, ACL.SYSTEM, Collections.emptyList()));
// }
//
// private final class Model extends AbstractIdCredentialsListBoxModel<Model,C> {
//
// @NonNull
// @Override
// protected String describe(@NonNull C c) {
// return CredentialsNameProvider.name(c);
// }
//
// }
//
// }
// Path: src/main/java/org/jenkinsci/plugins/credentialsbinding/impl/FileBinding.java
import hudson.model.TaskListener;
import java.io.IOException;
import org.jenkinsci.Symbol;
import org.jenkinsci.plugins.credentialsbinding.BindingDescriptor;
import org.jenkinsci.plugins.plaincredentials.FileCredentials;
import org.kohsuke.stapler.DataBoundConstructor;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.Run;
FilePath secret = dir.child(credentials.getFileName());
secret.copyFrom(credentials.getContent());
secret.chmod(0400);
return secret;
}
@SuppressWarnings("unused")
@Deprecated
private static class UnbinderImpl implements Unbinder {
private static final long serialVersionUID = 1;
private final String dirName;
private UnbinderImpl(String dirName) {
this.dirName = dirName;
}
protected Object readResolve() {
return new UnbindableDir.UnbinderImpl(dirName);
}
@Override
public void unbind(@NonNull Run<?, ?> build,
@Nullable FilePath workspace,
@Nullable Launcher launcher,
@NonNull TaskListener listener) {
// replaced by the UnbindableDir.UnbinderImpl implementation
}
}
@Symbol("file") | @Extension public static class DescriptorImpl extends BindingDescriptor<FileCredentials> { |
nutritionfactsorg/daily-dozen-android | app/src/main/java/org/nutritionfacts/dailydozen/view/TimeScaleSelector.java | // Path: app/src/main/java/org/nutritionfacts/dailydozen/controller/Bus.java
// public class Bus {
// public static void register(Object object) {
// final EventBus bus = EventBus.getDefault();
// if (!bus.isRegistered(object)) {
// bus.register(object);
// }
// }
//
// public static void unregister(Object object) {
// final EventBus bus = EventBus.getDefault();
// if (bus.isRegistered(object)) {
// bus.unregister(object);
// }
// }
//
// private static void post(BaseEvent event) {
// EventBus.getDefault().post(event);
// }
//
// public static void foodServingsChangedEvent(Day day, Food food) {
// post(new FoodServingsChangedEvent(day.getDateString(), food.getName(), Common.isSupplement(food)));
// }
//
// public static void tweakServingsChangedEvent(Day day, Tweak tweak) {
// post(new TweakServingsChangedEvent(day.getDateString(), tweak.getName()));
// }
//
// public static void displayLatestDate() {
// post(new DisplayDateEvent(Day.getToday()));
// }
//
// public static void showExplodingStarAnimation() {
// post(new ShowExplodingStarAnimation());
// }
//
// public static void restoreCompleteEvent(final boolean success) {
// post(new RestoreCompleteEvent(success));
// }
//
// public static void backupCompleteEvent(final boolean success) {
// post(new BackupCompleteEvent(success));
// }
//
// public static void calculateStreaksComplete(final boolean success) {
// post(new CalculateStreaksTaskCompleteEvent(success));
// }
//
// public static void loadHistoryCompleteEvent(final LoadHistoryCompleteEvent event) {
// post(event);
// }
//
// public static void timeScaleSelected(final int selectedTimeScale) {
// post(new TimeScaleSelectedEvent(selectedTimeScale));
// }
//
// public static void timeRangeSelectedEvent() {
// post(new TimeRangeSelectedEvent());
// }
//
// public static void weightVisibilityChanged() {
// post(new WeightVisibilityChangedEvent());
// }
//
// public static void reminderRemovedEvent(int adapterPosition) {
// post(new ReminderRemovedEvent(adapterPosition));
// }
// }
| import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import org.nutritionfacts.dailydozen.R;
import org.nutritionfacts.dailydozen.controller.Bus;
import org.nutritionfacts.dailydozen.databinding.TimeScaleSelectorBinding;
import org.nutritionfacts.dailydozen.model.enums.TimeScale; | @TimeScale.Interface
public int getSelectedTimeScale() {
switch (binding.timeScaleSpinner.getSelectedItemPosition()) {
case TimeScale.MONTHS:
return TimeScale.MONTHS;
case TimeScale.YEARS:
return TimeScale.YEARS;
default:
case TimeScale.DAYS:
return TimeScale.DAYS;
}
}
private void init(final Context context) {
binding = TimeScaleSelectorBinding.inflate(LayoutInflater.from(context), this, true);
initTimeScaleSpinner();
}
private void initTimeScaleSpinner() {
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.servings_time_scale_choices,
android.R.layout.simple_expandable_list_item_1);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.timeScaleSpinner.setOnItemSelectedListener(this);
binding.timeScaleSpinner.setAdapter(adapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { | // Path: app/src/main/java/org/nutritionfacts/dailydozen/controller/Bus.java
// public class Bus {
// public static void register(Object object) {
// final EventBus bus = EventBus.getDefault();
// if (!bus.isRegistered(object)) {
// bus.register(object);
// }
// }
//
// public static void unregister(Object object) {
// final EventBus bus = EventBus.getDefault();
// if (bus.isRegistered(object)) {
// bus.unregister(object);
// }
// }
//
// private static void post(BaseEvent event) {
// EventBus.getDefault().post(event);
// }
//
// public static void foodServingsChangedEvent(Day day, Food food) {
// post(new FoodServingsChangedEvent(day.getDateString(), food.getName(), Common.isSupplement(food)));
// }
//
// public static void tweakServingsChangedEvent(Day day, Tweak tweak) {
// post(new TweakServingsChangedEvent(day.getDateString(), tweak.getName()));
// }
//
// public static void displayLatestDate() {
// post(new DisplayDateEvent(Day.getToday()));
// }
//
// public static void showExplodingStarAnimation() {
// post(new ShowExplodingStarAnimation());
// }
//
// public static void restoreCompleteEvent(final boolean success) {
// post(new RestoreCompleteEvent(success));
// }
//
// public static void backupCompleteEvent(final boolean success) {
// post(new BackupCompleteEvent(success));
// }
//
// public static void calculateStreaksComplete(final boolean success) {
// post(new CalculateStreaksTaskCompleteEvent(success));
// }
//
// public static void loadHistoryCompleteEvent(final LoadHistoryCompleteEvent event) {
// post(event);
// }
//
// public static void timeScaleSelected(final int selectedTimeScale) {
// post(new TimeScaleSelectedEvent(selectedTimeScale));
// }
//
// public static void timeRangeSelectedEvent() {
// post(new TimeRangeSelectedEvent());
// }
//
// public static void weightVisibilityChanged() {
// post(new WeightVisibilityChangedEvent());
// }
//
// public static void reminderRemovedEvent(int adapterPosition) {
// post(new ReminderRemovedEvent(adapterPosition));
// }
// }
// Path: app/src/main/java/org/nutritionfacts/dailydozen/view/TimeScaleSelector.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import org.nutritionfacts.dailydozen.R;
import org.nutritionfacts.dailydozen.controller.Bus;
import org.nutritionfacts.dailydozen.databinding.TimeScaleSelectorBinding;
import org.nutritionfacts.dailydozen.model.enums.TimeScale;
@TimeScale.Interface
public int getSelectedTimeScale() {
switch (binding.timeScaleSpinner.getSelectedItemPosition()) {
case TimeScale.MONTHS:
return TimeScale.MONTHS;
case TimeScale.YEARS:
return TimeScale.YEARS;
default:
case TimeScale.DAYS:
return TimeScale.DAYS;
}
}
private void init(final Context context) {
binding = TimeScaleSelectorBinding.inflate(LayoutInflater.from(context), this, true);
initTimeScaleSpinner();
}
private void initTimeScaleSpinner() {
final ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.servings_time_scale_choices,
android.R.layout.simple_expandable_list_item_1);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
binding.timeScaleSpinner.setOnItemSelectedListener(this);
binding.timeScaleSpinner.setAdapter(adapter);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { | Bus.timeScaleSelected(binding.timeScaleSpinner.getSelectedItemPosition()); |
nutritionfactsorg/daily-dozen-android | app/src/main/java/org/nutritionfacts/dailydozen/model/pref/UpdateReminderPref.java | // Path: app/src/main/java/org/nutritionfacts/dailydozen/util/DateUtil.java
// public class DateUtil {
// public static Calendar getCalendarForYearMonthAndDay(final int year,
// final int monthOneBased,
// final int day) {
// // We need to subtract one to convert the one-based month arg into a zero-based month
// final Calendar cal = getCalendarForYearAndMonth(year, monthOneBased - 1);
// cal.set(Calendar.DAY_OF_MONTH, day);
// return cal;
// }
//
// public static Calendar getCalendarForYearAndMonth(final int year, final int monthZeroBased) {
// final Calendar cal = getCalendarForToday();
// cal.set(Calendar.YEAR, year);
// cal.set(Calendar.MONTH, monthZeroBased);
// cal.set(Calendar.DAY_OF_MONTH, 1);
// return cal;
// }
//
// private static Calendar getCalendarForToday() {
// final Calendar cal = Calendar.getInstance(Locale.getDefault());
// cal.set(Calendar.HOUR_OF_DAY, 0);
// cal.set(Calendar.MINUTE, 0);
// cal.set(Calendar.SECOND, 0);
// cal.set(Calendar.MILLISECOND, 0);
// return cal;
// }
//
// public static int getCurrentYear() {
// return getYear(getCalendarForToday());
// }
//
// public static int getYear(Calendar cal) {
// return cal.get(Calendar.YEAR);
// }
//
// private static int getMonthZeroBased(Calendar cal) {
// return cal.get(Calendar.MONTH);
// }
//
// public static int getMonthOneBased(Calendar cal) {
// return getMonthZeroBased(cal) + 1;
// }
//
// public static void addOneMonth(Calendar cal) {
// cal.add(Calendar.MONTH, 1);
// }
//
// public static void subtractTwoMonths(Calendar cal) {
// cal.add(Calendar.MONTH, -2);
// }
//
// public static String toStringYYYYMM(Calendar cal) {
// return String.format("%s%s", getYear(cal), getMonthOneBased(cal));
// }
//
// public static String getShortNameOfMonth(final int monthNumberOneBased) {
// return new SimpleDateFormat("MMM", Locale.getDefault())
// .format(getCalendarForYearAndMonth(2016, monthNumberOneBased - 1).getTime());
// }
//
// public static DateTime convertDateToDateTime(final Date date) {
// return date != null ? DateTime.forInstant(date.getTime(), TimeZone.getDefault()) : null;
// }
//
// public static Date convertDayToDate(final Day day) {
// return day != null ? getCalendarForYearMonthAndDay(day.getYear(), day.getMonth(), day.getDayNumber()).getTime() : null;
// }
//
// public static boolean is24HourTimeFormat(final Context context) {
// return DateFormat.is24HourFormat(context);
// }
//
// public static String formatTime(final Context context, int hourOfDay, int minute) {
// if (is24HourTimeFormat(context)) {
// return String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
// } else {
// int hour = hourOfDay < 12 ? hourOfDay : hourOfDay % 12;
// if (hour == 0) {
// hour = 12;
// }
//
// return String.format(Locale.getDefault(), "%s:%02d %s", hour, minute, hourOfDay < 12 ? "AM" : "PM");
// }
// }
// }
| import android.content.Context;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.google.gson.annotations.SerializedName;
import org.nutritionfacts.dailydozen.util.DateUtil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import timber.log.Timber; | package org.nutritionfacts.dailydozen.model.pref;
public class UpdateReminderPref {
// The default Update Reminder notification displays at 8pm
@SerializedName("hourOfDay")
private int hourOfDay = 20; // Default to 8pm
@SerializedName("minute")
private int minute = 0;
@SerializedName("reminderTimes")
private List<String> reminderTimes = new ArrayList<>();
public void setHourOfDay(int hourOfDay) {
this.hourOfDay = hourOfDay;
}
public int getHourOfDay() {
return hourOfDay;
}
public void setMinute(int minute) {
this.minute = minute;
}
public int getMinute() {
return minute;
}
public void addReminderTime(Context context, int hourOfDay, int minute) {
// Add new reminder to set to eliminate duplicates
Set<String> reminderTimesSet = new HashSet<>(reminderTimes); | // Path: app/src/main/java/org/nutritionfacts/dailydozen/util/DateUtil.java
// public class DateUtil {
// public static Calendar getCalendarForYearMonthAndDay(final int year,
// final int monthOneBased,
// final int day) {
// // We need to subtract one to convert the one-based month arg into a zero-based month
// final Calendar cal = getCalendarForYearAndMonth(year, monthOneBased - 1);
// cal.set(Calendar.DAY_OF_MONTH, day);
// return cal;
// }
//
// public static Calendar getCalendarForYearAndMonth(final int year, final int monthZeroBased) {
// final Calendar cal = getCalendarForToday();
// cal.set(Calendar.YEAR, year);
// cal.set(Calendar.MONTH, monthZeroBased);
// cal.set(Calendar.DAY_OF_MONTH, 1);
// return cal;
// }
//
// private static Calendar getCalendarForToday() {
// final Calendar cal = Calendar.getInstance(Locale.getDefault());
// cal.set(Calendar.HOUR_OF_DAY, 0);
// cal.set(Calendar.MINUTE, 0);
// cal.set(Calendar.SECOND, 0);
// cal.set(Calendar.MILLISECOND, 0);
// return cal;
// }
//
// public static int getCurrentYear() {
// return getYear(getCalendarForToday());
// }
//
// public static int getYear(Calendar cal) {
// return cal.get(Calendar.YEAR);
// }
//
// private static int getMonthZeroBased(Calendar cal) {
// return cal.get(Calendar.MONTH);
// }
//
// public static int getMonthOneBased(Calendar cal) {
// return getMonthZeroBased(cal) + 1;
// }
//
// public static void addOneMonth(Calendar cal) {
// cal.add(Calendar.MONTH, 1);
// }
//
// public static void subtractTwoMonths(Calendar cal) {
// cal.add(Calendar.MONTH, -2);
// }
//
// public static String toStringYYYYMM(Calendar cal) {
// return String.format("%s%s", getYear(cal), getMonthOneBased(cal));
// }
//
// public static String getShortNameOfMonth(final int monthNumberOneBased) {
// return new SimpleDateFormat("MMM", Locale.getDefault())
// .format(getCalendarForYearAndMonth(2016, monthNumberOneBased - 1).getTime());
// }
//
// public static DateTime convertDateToDateTime(final Date date) {
// return date != null ? DateTime.forInstant(date.getTime(), TimeZone.getDefault()) : null;
// }
//
// public static Date convertDayToDate(final Day day) {
// return day != null ? getCalendarForYearMonthAndDay(day.getYear(), day.getMonth(), day.getDayNumber()).getTime() : null;
// }
//
// public static boolean is24HourTimeFormat(final Context context) {
// return DateFormat.is24HourFormat(context);
// }
//
// public static String formatTime(final Context context, int hourOfDay, int minute) {
// if (is24HourTimeFormat(context)) {
// return String.format(Locale.getDefault(), "%02d:%02d", hourOfDay, minute);
// } else {
// int hour = hourOfDay < 12 ? hourOfDay : hourOfDay % 12;
// if (hour == 0) {
// hour = 12;
// }
//
// return String.format(Locale.getDefault(), "%s:%02d %s", hour, minute, hourOfDay < 12 ? "AM" : "PM");
// }
// }
// }
// Path: app/src/main/java/org/nutritionfacts/dailydozen/model/pref/UpdateReminderPref.java
import android.content.Context;
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.google.gson.annotations.SerializedName;
import org.nutritionfacts.dailydozen.util.DateUtil;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import timber.log.Timber;
package org.nutritionfacts.dailydozen.model.pref;
public class UpdateReminderPref {
// The default Update Reminder notification displays at 8pm
@SerializedName("hourOfDay")
private int hourOfDay = 20; // Default to 8pm
@SerializedName("minute")
private int minute = 0;
@SerializedName("reminderTimes")
private List<String> reminderTimes = new ArrayList<>();
public void setHourOfDay(int hourOfDay) {
this.hourOfDay = hourOfDay;
}
public int getHourOfDay() {
return hourOfDay;
}
public void setMinute(int minute) {
this.minute = minute;
}
public int getMinute() {
return minute;
}
public void addReminderTime(Context context, int hourOfDay, int minute) {
// Add new reminder to set to eliminate duplicates
Set<String> reminderTimesSet = new HashSet<>(reminderTimes); | reminderTimesSet.add(DateUtil.formatTime(context, hourOfDay, minute)); |
nutritionfactsorg/daily-dozen-android | app/src/main/java/org/nutritionfacts/dailydozen/model/Day.java | // Path: app/src/main/java/org/nutritionfacts/dailydozen/exception/InvalidDateException.java
// public class InvalidDateException extends Exception {
// private final String invalidDateString;
//
// public InvalidDateException(String invalidDateString) {
// this.invalidDateString = invalidDateString;
// }
//
// @NonNull
// @Override
// public String toString() {
// return String.format("InvalidDateException{invalidDateString='%s'}", invalidDateString);
// }
// }
| import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import org.nutritionfacts.dailydozen.exception.InvalidDateException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import hirondelle.date4j.DateTime;
import timber.log.Timber; | // NOTE: This method used to be the following line. However, because of a bug in Caldroid, I had to
// change the implementation to return a DateTime with 0 in the time fields instead of null otherwise the
// food servings history chart would not show events.
// return DateTime.forDateOnly(year, month, day);
return new DateTime(year, month, day, 0, 0, 0, 0);
}
private void setDate(DateTime dateTime) {
this.date = Long.parseLong(getDateString(dateTime));
this.year = dateTime.getYear();
this.month = dateTime.getMonth();
this.day = dateTime.getDay();
}
public long getDate() {
return date;
}
@NonNull
@Override
public String toString() {
return getDateTime().format("WWW, MMM D", Locale.getDefault());
}
public String getDayOfWeek() {
return getDateTime().format("D (WWW)", Locale.getDefault());
}
| // Path: app/src/main/java/org/nutritionfacts/dailydozen/exception/InvalidDateException.java
// public class InvalidDateException extends Exception {
// private final String invalidDateString;
//
// public InvalidDateException(String invalidDateString) {
// this.invalidDateString = invalidDateString;
// }
//
// @NonNull
// @Override
// public String toString() {
// return String.format("InvalidDateException{invalidDateString='%s'}", invalidDateString);
// }
// }
// Path: app/src/main/java/org/nutritionfacts/dailydozen/model/Day.java
import android.text.TextUtils;
import androidx.annotation.NonNull;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
import com.activeandroid.query.Select;
import org.nutritionfacts.dailydozen.exception.InvalidDateException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import hirondelle.date4j.DateTime;
import timber.log.Timber;
// NOTE: This method used to be the following line. However, because of a bug in Caldroid, I had to
// change the implementation to return a DateTime with 0 in the time fields instead of null otherwise the
// food servings history chart would not show events.
// return DateTime.forDateOnly(year, month, day);
return new DateTime(year, month, day, 0, 0, 0, 0);
}
private void setDate(DateTime dateTime) {
this.date = Long.parseLong(getDateString(dateTime));
this.year = dateTime.getYear();
this.month = dateTime.getMonth();
this.day = dateTime.getDay();
}
public long getDate() {
return date;
}
@NonNull
@Override
public String toString() {
return getDateTime().format("WWW, MMM D", Locale.getDefault());
}
public String getDayOfWeek() {
return getDateTime().format("D (WWW)", Locale.getDefault());
}
| public static Day getByDate(String dateString) throws InvalidDateException { |
nutritionfactsorg/daily-dozen-android | app/src/main/java/org/nutritionfacts/dailydozen/adapter/DailyReminderAdapter.java | // Path: app/src/main/java/org/nutritionfacts/dailydozen/controller/Bus.java
// public class Bus {
// public static void register(Object object) {
// final EventBus bus = EventBus.getDefault();
// if (!bus.isRegistered(object)) {
// bus.register(object);
// }
// }
//
// public static void unregister(Object object) {
// final EventBus bus = EventBus.getDefault();
// if (bus.isRegistered(object)) {
// bus.unregister(object);
// }
// }
//
// private static void post(BaseEvent event) {
// EventBus.getDefault().post(event);
// }
//
// public static void foodServingsChangedEvent(Day day, Food food) {
// post(new FoodServingsChangedEvent(day.getDateString(), food.getName(), Common.isSupplement(food)));
// }
//
// public static void tweakServingsChangedEvent(Day day, Tweak tweak) {
// post(new TweakServingsChangedEvent(day.getDateString(), tweak.getName()));
// }
//
// public static void displayLatestDate() {
// post(new DisplayDateEvent(Day.getToday()));
// }
//
// public static void showExplodingStarAnimation() {
// post(new ShowExplodingStarAnimation());
// }
//
// public static void restoreCompleteEvent(final boolean success) {
// post(new RestoreCompleteEvent(success));
// }
//
// public static void backupCompleteEvent(final boolean success) {
// post(new BackupCompleteEvent(success));
// }
//
// public static void calculateStreaksComplete(final boolean success) {
// post(new CalculateStreaksTaskCompleteEvent(success));
// }
//
// public static void loadHistoryCompleteEvent(final LoadHistoryCompleteEvent event) {
// post(event);
// }
//
// public static void timeScaleSelected(final int selectedTimeScale) {
// post(new TimeScaleSelectedEvent(selectedTimeScale));
// }
//
// public static void timeRangeSelectedEvent() {
// post(new TimeRangeSelectedEvent());
// }
//
// public static void weightVisibilityChanged() {
// post(new WeightVisibilityChangedEvent());
// }
//
// public static void reminderRemovedEvent(int adapterPosition) {
// post(new ReminderRemovedEvent(adapterPosition));
// }
// }
| import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.nutritionfacts.dailydozen.controller.Bus;
import org.nutritionfacts.dailydozen.databinding.ReminderTimeBinding;
import java.util.List; | @Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(ReminderTimeBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
if (reminderTimes == null || reminderTimes.isEmpty()) {
return;
}
holder.reminderTime.setText(reminderTimes.get(position));
}
@Override
public int getItemCount() {
return reminderTimes != null ? reminderTimes.size() : 0;
}
public void setReminders(List<String> reminderTimes) {
this.reminderTimes = reminderTimes;
notifyDataSetChanged();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView reminderTime;
ViewHolder(ReminderTimeBinding binding) {
super(binding.getRoot());
reminderTime = binding.reminderTime; | // Path: app/src/main/java/org/nutritionfacts/dailydozen/controller/Bus.java
// public class Bus {
// public static void register(Object object) {
// final EventBus bus = EventBus.getDefault();
// if (!bus.isRegistered(object)) {
// bus.register(object);
// }
// }
//
// public static void unregister(Object object) {
// final EventBus bus = EventBus.getDefault();
// if (bus.isRegistered(object)) {
// bus.unregister(object);
// }
// }
//
// private static void post(BaseEvent event) {
// EventBus.getDefault().post(event);
// }
//
// public static void foodServingsChangedEvent(Day day, Food food) {
// post(new FoodServingsChangedEvent(day.getDateString(), food.getName(), Common.isSupplement(food)));
// }
//
// public static void tweakServingsChangedEvent(Day day, Tweak tweak) {
// post(new TweakServingsChangedEvent(day.getDateString(), tweak.getName()));
// }
//
// public static void displayLatestDate() {
// post(new DisplayDateEvent(Day.getToday()));
// }
//
// public static void showExplodingStarAnimation() {
// post(new ShowExplodingStarAnimation());
// }
//
// public static void restoreCompleteEvent(final boolean success) {
// post(new RestoreCompleteEvent(success));
// }
//
// public static void backupCompleteEvent(final boolean success) {
// post(new BackupCompleteEvent(success));
// }
//
// public static void calculateStreaksComplete(final boolean success) {
// post(new CalculateStreaksTaskCompleteEvent(success));
// }
//
// public static void loadHistoryCompleteEvent(final LoadHistoryCompleteEvent event) {
// post(event);
// }
//
// public static void timeScaleSelected(final int selectedTimeScale) {
// post(new TimeScaleSelectedEvent(selectedTimeScale));
// }
//
// public static void timeRangeSelectedEvent() {
// post(new TimeRangeSelectedEvent());
// }
//
// public static void weightVisibilityChanged() {
// post(new WeightVisibilityChangedEvent());
// }
//
// public static void reminderRemovedEvent(int adapterPosition) {
// post(new ReminderRemovedEvent(adapterPosition));
// }
// }
// Path: app/src/main/java/org/nutritionfacts/dailydozen/adapter/DailyReminderAdapter.java
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import org.nutritionfacts.dailydozen.controller.Bus;
import org.nutritionfacts.dailydozen.databinding.ReminderTimeBinding;
import java.util.List;
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new ViewHolder(ReminderTimeBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
if (reminderTimes == null || reminderTimes.isEmpty()) {
return;
}
holder.reminderTime.setText(reminderTimes.get(position));
}
@Override
public int getItemCount() {
return reminderTimes != null ? reminderTimes.size() : 0;
}
public void setReminders(List<String> reminderTimes) {
this.reminderTimes = reminderTimes;
notifyDataSetChanged();
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView reminderTime;
ViewHolder(ReminderTimeBinding binding) {
super(binding.getRoot());
reminderTime = binding.reminderTime; | binding.reminderDelete.setOnClickListener(v -> Bus.reminderRemovedEvent(getAdapterPosition())); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/BaseOutputDialog.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/TaskType.java
// public enum TaskType {
// /**
// * Indicates the task should only overwrite preferences if the file's
// * modification date is earlier than the changes.
// */
// LASTMOD,
//
// /**
// * Indicates the task should overwrite any preferences that are different
// * from the values listed the one written here.
// */
// RECONCILE
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
| import java.io.File;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.eclipse.mechanic.internal.TaskType;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin; | protected boolean isResizable() {
return true;
}
// TODO: zorzella says: I don't think this overload is doing anything at all.
// I refactored it to stop growing upon every invocation, but the whole bit
// about "new Point(p.x, p.y * 3 / 2);" which, on face value, seems like an
// attempt to make the dialog taller than its otherwise default, seems to
// simply be having no effect.
@Override
protected Point getInitialSize() {
// We check if the dialog has been resized by the user...
if (getDialogBoundsSettings() == null) {
// ... if not, we create a dialog twice the default size
Point p = super.getInitialSize();
return new Point(p.x, p.y * 3 / 2);
} else {
// ... if it has been resized, we use that size, otherwise
// every time we open the dialog it grows...
return super.getInitialSize();
}
// ... there probably is a much better way of doing this, btw.
}
@Override
protected IDialogSettings getDialogBoundsSettings() {
String dialogSettingsSection = getDialogSettingsSection();
if (dialogSettingsSection == null) {
return null;
} | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/TaskType.java
// public enum TaskType {
// /**
// * Indicates the task should only overwrite preferences if the file's
// * modification date is earlier than the changes.
// */
// LASTMOD,
//
// /**
// * Indicates the task should overwrite any preferences that are different
// * from the values listed the one written here.
// */
// RECONCILE
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/BaseOutputDialog.java
import java.io.File;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.eclipse.mechanic.internal.TaskType;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;
protected boolean isResizable() {
return true;
}
// TODO: zorzella says: I don't think this overload is doing anything at all.
// I refactored it to stop growing upon every invocation, but the whole bit
// about "new Point(p.x, p.y * 3 / 2);" which, on face value, seems like an
// attempt to make the dialog taller than its otherwise default, seems to
// simply be having no effect.
@Override
protected Point getInitialSize() {
// We check if the dialog has been resized by the user...
if (getDialogBoundsSettings() == null) {
// ... if not, we create a dialog twice the default size
Point p = super.getInitialSize();
return new Point(p.x, p.y * 3 / 2);
} else {
// ... if it has been resized, we use that size, otherwise
// every time we open the dialog it grows...
return super.getInitialSize();
}
// ... there probably is a much better way of doing this, btw.
}
@Override
protected IDialogSettings getDialogBoundsSettings() {
String dialogSettingsSection = getDialogSettingsSection();
if (dialogSettingsSection == null) {
return null;
} | IDialogSettings settings = MechanicPlugin.getDefault().getDialogSettings(); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/BaseOutputDialog.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/TaskType.java
// public enum TaskType {
// /**
// * Indicates the task should only overwrite preferences if the file's
// * modification date is earlier than the changes.
// */
// LASTMOD,
//
// /**
// * Indicates the task should overwrite any preferences that are different
// * from the values listed the one written here.
// */
// RECONCILE
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
| import java.io.File;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.eclipse.mechanic.internal.TaskType;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin; |
protected Text createTextBox(Composite parent) {
Text text = new Text(parent, SWT.SINGLE | SWT.BORDER);
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
text.addModifyListener(validateOnChange);
return text;
}
@Override
protected Control createDialogArea(Composite parent) {
final Composite container = (Composite) super.createDialogArea(parent);
GridLayout layout = new GridLayout(3, false);
container.setLayout(layout);
if (components.contains(Component.TITLE)) {
createLabel(container, "Title:");
titleText = createTextBox(container);
titleText.setEnabled(components.contains(Component.TITLE));
}
if (components.contains(Component.DESCRIPTION)) {
createLabel(container, "Description:");
descriptionText = createTextBox(container);
descriptionText.setEnabled(components.contains(Component.DESCRIPTION));
}
if (components.contains(Component.TASK_TYPE)) {
createLabel(container, "Task Type:");
taskTypeCombo = new Combo(container, SWT.DROP_DOWN | SWT.READ_ONLY);
// Ensuring the order hasn't changed, as we rely on that. | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/TaskType.java
// public enum TaskType {
// /**
// * Indicates the task should only overwrite preferences if the file's
// * modification date is earlier than the changes.
// */
// LASTMOD,
//
// /**
// * Indicates the task should overwrite any preferences that are different
// * from the values listed the one written here.
// */
// RECONCILE
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/BaseOutputDialog.java
import java.io.File;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Set;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.eclipse.mechanic.internal.TaskType;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;
protected Text createTextBox(Composite parent) {
Text text = new Text(parent, SWT.SINGLE | SWT.BORDER);
text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
text.addModifyListener(validateOnChange);
return text;
}
@Override
protected Control createDialogArea(Composite parent) {
final Composite container = (Composite) super.createDialogArea(parent);
GridLayout layout = new GridLayout(3, false);
container.setLayout(layout);
if (components.contains(Component.TITLE)) {
createLabel(container, "Title:");
titleText = createTextBox(container);
titleText.setEnabled(components.contains(Component.TITLE));
}
if (components.contains(Component.DESCRIPTION)) {
createLabel(container, "Description:");
descriptionText = createTextBox(container);
descriptionText.setEnabled(components.contains(Component.DESCRIPTION));
}
if (components.contains(Component.TASK_TYPE)) {
createLabel(container, "Task Type:");
taskTypeCombo = new Combo(container, SWT.DROP_DOWN | SWT.READ_ONLY);
// Ensuring the order hasn't changed, as we rely on that. | Preconditions.checkState(TaskType.values()[0] == TaskType.LASTMOD); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyboardBindingsScanner.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ListCollector.java
// public class ListCollector<T> implements ICollector<T> {
// private final List<T> list = Lists.newArrayList();
//
// public static <T> ListCollector<T> create() {
// return new ListCollector<T>();
// }
//
// public void collect(T element) {
// list.add(element);
// }
//
// public List<T> get() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ResourceTaskScanner.java
// public abstract class ResourceTaskScanner implements TaskScanner {
//
// private final Supplier<List<IResourceTaskProvider>> supplier;
//
// public ResourceTaskScanner() {
// this(ResourceTaskProvidersExtensionPoint.getInstance());
// }
//
// @VisibleForTesting
// ResourceTaskScanner(Supplier<List<IResourceTaskProvider>> supplier) {
// this.supplier = supplier;
// }
//
// public void scan(TaskCollector collector) {
// Preconditions.checkNotNull(collector, "'collector' cannot be null.");
//
// for (IResourceTaskProvider source : supplier.get()) {
// scan(source, collector);
// }
// }
//
// /**
// * Scan the source for tasks.
// *
// * @param source the source to scan. The source should already be considered valid.
// * @param collector the collector of tasks. Guaranteed to be not null.
// */
// protected abstract void scan(IResourceTaskProvider source, TaskCollector collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
| import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;
import com.google.eclipse.mechanic.ListCollector;
import com.google.eclipse.mechanic.ResourceTaskScanner;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.TaskCollector; | /*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Scanner for keyboard bindings.
*
* @author zorzella@google.com (Luiz-Otavio Zorzella)
*/
public class KeyboardBindingsScanner extends ResourceTaskScanner {
private static final Logger LOG = Logger.getLogger(
KeyboardBindingsScanner.class.getName());
@Override | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ListCollector.java
// public class ListCollector<T> implements ICollector<T> {
// private final List<T> list = Lists.newArrayList();
//
// public static <T> ListCollector<T> create() {
// return new ListCollector<T>();
// }
//
// public void collect(T element) {
// list.add(element);
// }
//
// public List<T> get() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ResourceTaskScanner.java
// public abstract class ResourceTaskScanner implements TaskScanner {
//
// private final Supplier<List<IResourceTaskProvider>> supplier;
//
// public ResourceTaskScanner() {
// this(ResourceTaskProvidersExtensionPoint.getInstance());
// }
//
// @VisibleForTesting
// ResourceTaskScanner(Supplier<List<IResourceTaskProvider>> supplier) {
// this.supplier = supplier;
// }
//
// public void scan(TaskCollector collector) {
// Preconditions.checkNotNull(collector, "'collector' cannot be null.");
//
// for (IResourceTaskProvider source : supplier.get()) {
// scan(source, collector);
// }
// }
//
// /**
// * Scan the source for tasks.
// *
// * @param source the source to scan. The source should already be considered valid.
// * @param collector the collector of tasks. Guaranteed to be not null.
// */
// protected abstract void scan(IResourceTaskProvider source, TaskCollector collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyboardBindingsScanner.java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;
import com.google.eclipse.mechanic.ListCollector;
import com.google.eclipse.mechanic.ResourceTaskScanner;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.TaskCollector;
/*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Scanner for keyboard bindings.
*
* @author zorzella@google.com (Luiz-Otavio Zorzella)
*/
public class KeyboardBindingsScanner extends ResourceTaskScanner {
private static final Logger LOG = Logger.getLogger(
KeyboardBindingsScanner.class.getName());
@Override | public void scan(IResourceTaskProvider source, TaskCollector collector) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyboardBindingsScanner.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ListCollector.java
// public class ListCollector<T> implements ICollector<T> {
// private final List<T> list = Lists.newArrayList();
//
// public static <T> ListCollector<T> create() {
// return new ListCollector<T>();
// }
//
// public void collect(T element) {
// list.add(element);
// }
//
// public List<T> get() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ResourceTaskScanner.java
// public abstract class ResourceTaskScanner implements TaskScanner {
//
// private final Supplier<List<IResourceTaskProvider>> supplier;
//
// public ResourceTaskScanner() {
// this(ResourceTaskProvidersExtensionPoint.getInstance());
// }
//
// @VisibleForTesting
// ResourceTaskScanner(Supplier<List<IResourceTaskProvider>> supplier) {
// this.supplier = supplier;
// }
//
// public void scan(TaskCollector collector) {
// Preconditions.checkNotNull(collector, "'collector' cannot be null.");
//
// for (IResourceTaskProvider source : supplier.get()) {
// scan(source, collector);
// }
// }
//
// /**
// * Scan the source for tasks.
// *
// * @param source the source to scan. The source should already be considered valid.
// * @param collector the collector of tasks. Guaranteed to be not null.
// */
// protected abstract void scan(IResourceTaskProvider source, TaskCollector collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
| import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;
import com.google.eclipse.mechanic.ListCollector;
import com.google.eclipse.mechanic.ResourceTaskScanner;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.TaskCollector; | /*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Scanner for keyboard bindings.
*
* @author zorzella@google.com (Luiz-Otavio Zorzella)
*/
public class KeyboardBindingsScanner extends ResourceTaskScanner {
private static final Logger LOG = Logger.getLogger(
KeyboardBindingsScanner.class.getName());
@Override | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ListCollector.java
// public class ListCollector<T> implements ICollector<T> {
// private final List<T> list = Lists.newArrayList();
//
// public static <T> ListCollector<T> create() {
// return new ListCollector<T>();
// }
//
// public void collect(T element) {
// list.add(element);
// }
//
// public List<T> get() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ResourceTaskScanner.java
// public abstract class ResourceTaskScanner implements TaskScanner {
//
// private final Supplier<List<IResourceTaskProvider>> supplier;
//
// public ResourceTaskScanner() {
// this(ResourceTaskProvidersExtensionPoint.getInstance());
// }
//
// @VisibleForTesting
// ResourceTaskScanner(Supplier<List<IResourceTaskProvider>> supplier) {
// this.supplier = supplier;
// }
//
// public void scan(TaskCollector collector) {
// Preconditions.checkNotNull(collector, "'collector' cannot be null.");
//
// for (IResourceTaskProvider source : supplier.get()) {
// scan(source, collector);
// }
// }
//
// /**
// * Scan the source for tasks.
// *
// * @param source the source to scan. The source should already be considered valid.
// * @param collector the collector of tasks. Guaranteed to be not null.
// */
// protected abstract void scan(IResourceTaskProvider source, TaskCollector collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyboardBindingsScanner.java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;
import com.google.eclipse.mechanic.ListCollector;
import com.google.eclipse.mechanic.ResourceTaskScanner;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.TaskCollector;
/*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Scanner for keyboard bindings.
*
* @author zorzella@google.com (Luiz-Otavio Zorzella)
*/
public class KeyboardBindingsScanner extends ResourceTaskScanner {
private static final Logger LOG = Logger.getLogger(
KeyboardBindingsScanner.class.getName());
@Override | public void scan(IResourceTaskProvider source, TaskCollector collector) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyboardBindingsScanner.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ListCollector.java
// public class ListCollector<T> implements ICollector<T> {
// private final List<T> list = Lists.newArrayList();
//
// public static <T> ListCollector<T> create() {
// return new ListCollector<T>();
// }
//
// public void collect(T element) {
// list.add(element);
// }
//
// public List<T> get() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ResourceTaskScanner.java
// public abstract class ResourceTaskScanner implements TaskScanner {
//
// private final Supplier<List<IResourceTaskProvider>> supplier;
//
// public ResourceTaskScanner() {
// this(ResourceTaskProvidersExtensionPoint.getInstance());
// }
//
// @VisibleForTesting
// ResourceTaskScanner(Supplier<List<IResourceTaskProvider>> supplier) {
// this.supplier = supplier;
// }
//
// public void scan(TaskCollector collector) {
// Preconditions.checkNotNull(collector, "'collector' cannot be null.");
//
// for (IResourceTaskProvider source : supplier.get()) {
// scan(source, collector);
// }
// }
//
// /**
// * Scan the source for tasks.
// *
// * @param source the source to scan. The source should already be considered valid.
// * @param collector the collector of tasks. Guaranteed to be not null.
// */
// protected abstract void scan(IResourceTaskProvider source, TaskCollector collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
| import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;
import com.google.eclipse.mechanic.ListCollector;
import com.google.eclipse.mechanic.ResourceTaskScanner;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.TaskCollector; | /*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Scanner for keyboard bindings.
*
* @author zorzella@google.com (Luiz-Otavio Zorzella)
*/
public class KeyboardBindingsScanner extends ResourceTaskScanner {
private static final Logger LOG = Logger.getLogger(
KeyboardBindingsScanner.class.getName());
@Override
public void scan(IResourceTaskProvider source, TaskCollector collector) {
/**
* Scan our source. Add a new Task for each KBD found.
*/ | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ListCollector.java
// public class ListCollector<T> implements ICollector<T> {
// private final List<T> list = Lists.newArrayList();
//
// public static <T> ListCollector<T> create() {
// return new ListCollector<T>();
// }
//
// public void collect(T element) {
// list.add(element);
// }
//
// public List<T> get() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ResourceTaskScanner.java
// public abstract class ResourceTaskScanner implements TaskScanner {
//
// private final Supplier<List<IResourceTaskProvider>> supplier;
//
// public ResourceTaskScanner() {
// this(ResourceTaskProvidersExtensionPoint.getInstance());
// }
//
// @VisibleForTesting
// ResourceTaskScanner(Supplier<List<IResourceTaskProvider>> supplier) {
// this.supplier = supplier;
// }
//
// public void scan(TaskCollector collector) {
// Preconditions.checkNotNull(collector, "'collector' cannot be null.");
//
// for (IResourceTaskProvider source : supplier.get()) {
// scan(source, collector);
// }
// }
//
// /**
// * Scan the source for tasks.
// *
// * @param source the source to scan. The source should already be considered valid.
// * @param collector the collector of tasks. Guaranteed to be not null.
// */
// protected abstract void scan(IResourceTaskProvider source, TaskCollector collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyboardBindingsScanner.java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;
import com.google.eclipse.mechanic.ListCollector;
import com.google.eclipse.mechanic.ResourceTaskScanner;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.TaskCollector;
/*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Scanner for keyboard bindings.
*
* @author zorzella@google.com (Luiz-Otavio Zorzella)
*/
public class KeyboardBindingsScanner extends ResourceTaskScanner {
private static final Logger LOG = Logger.getLogger(
KeyboardBindingsScanner.class.getName());
@Override
public void scan(IResourceTaskProvider source, TaskCollector collector) {
/**
* Scan our source. Add a new Task for each KBD found.
*/ | ListCollector<IResourceTaskReference> taskCollector = ListCollector.create(); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyboardBindingsScanner.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ListCollector.java
// public class ListCollector<T> implements ICollector<T> {
// private final List<T> list = Lists.newArrayList();
//
// public static <T> ListCollector<T> create() {
// return new ListCollector<T>();
// }
//
// public void collect(T element) {
// list.add(element);
// }
//
// public List<T> get() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ResourceTaskScanner.java
// public abstract class ResourceTaskScanner implements TaskScanner {
//
// private final Supplier<List<IResourceTaskProvider>> supplier;
//
// public ResourceTaskScanner() {
// this(ResourceTaskProvidersExtensionPoint.getInstance());
// }
//
// @VisibleForTesting
// ResourceTaskScanner(Supplier<List<IResourceTaskProvider>> supplier) {
// this.supplier = supplier;
// }
//
// public void scan(TaskCollector collector) {
// Preconditions.checkNotNull(collector, "'collector' cannot be null.");
//
// for (IResourceTaskProvider source : supplier.get()) {
// scan(source, collector);
// }
// }
//
// /**
// * Scan the source for tasks.
// *
// * @param source the source to scan. The source should already be considered valid.
// * @param collector the collector of tasks. Guaranteed to be not null.
// */
// protected abstract void scan(IResourceTaskProvider source, TaskCollector collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
| import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;
import com.google.eclipse.mechanic.ListCollector;
import com.google.eclipse.mechanic.ResourceTaskScanner;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.TaskCollector; | /*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Scanner for keyboard bindings.
*
* @author zorzella@google.com (Luiz-Otavio Zorzella)
*/
public class KeyboardBindingsScanner extends ResourceTaskScanner {
private static final Logger LOG = Logger.getLogger(
KeyboardBindingsScanner.class.getName());
@Override
public void scan(IResourceTaskProvider source, TaskCollector collector) {
/**
* Scan our source. Add a new Task for each KBD found.
*/ | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ListCollector.java
// public class ListCollector<T> implements ICollector<T> {
// private final List<T> list = Lists.newArrayList();
//
// public static <T> ListCollector<T> create() {
// return new ListCollector<T>();
// }
//
// public void collect(T element) {
// list.add(element);
// }
//
// public List<T> get() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ResourceTaskScanner.java
// public abstract class ResourceTaskScanner implements TaskScanner {
//
// private final Supplier<List<IResourceTaskProvider>> supplier;
//
// public ResourceTaskScanner() {
// this(ResourceTaskProvidersExtensionPoint.getInstance());
// }
//
// @VisibleForTesting
// ResourceTaskScanner(Supplier<List<IResourceTaskProvider>> supplier) {
// this.supplier = supplier;
// }
//
// public void scan(TaskCollector collector) {
// Preconditions.checkNotNull(collector, "'collector' cannot be null.");
//
// for (IResourceTaskProvider source : supplier.get()) {
// scan(source, collector);
// }
// }
//
// /**
// * Scan the source for tasks.
// *
// * @param source the source to scan. The source should already be considered valid.
// * @param collector the collector of tasks. Guaranteed to be not null.
// */
// protected abstract void scan(IResourceTaskProvider source, TaskCollector collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyboardBindingsScanner.java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.logging.Logger;
import com.google.eclipse.mechanic.ListCollector;
import com.google.eclipse.mechanic.ResourceTaskScanner;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.TaskCollector;
/*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Scanner for keyboard bindings.
*
* @author zorzella@google.com (Luiz-Otavio Zorzella)
*/
public class KeyboardBindingsScanner extends ResourceTaskScanner {
private static final Logger LOG = Logger.getLogger(
KeyboardBindingsScanner.class.getName());
@Override
public void scan(IResourceTaskProvider source, TaskCollector collector) {
/**
* Scan our source. Add a new Task for each KBD found.
*/ | ListCollector<IResourceTaskReference> taskCollector = ListCollector.create(); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindings.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicLog.java
// public class MechanicLog {
// private static MechanicLog DEFAULT;
//
// private final ILog log;
//
// /**
// * Get the default instance.
// */
// public synchronized static MechanicLog getDefault() {
// if (DEFAULT == null) {
// DEFAULT = new MechanicLog(MechanicPlugin.getDefault());
// }
// return DEFAULT;
// }
//
// MechanicLog(Plugin plugin) {
// this(plugin.getLog());
// }
//
// public MechanicLog(ILog log) {
// this.log = Preconditions.checkNotNull(log);
// }
//
// /**
// * Log a status.
// */
// public void log(IStatus status) {
// log.log(status);
// }
//
// /**
// * Log an error to the Eclipse log.
// *
// * @param t the throwable.
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logError(Throwable t, String fmt, Object... args) {
// String text = (args.length > 0) ? String.format(fmt, args) : fmt;
// log(new Status(IStatus.ERROR, MechanicPlugin.PLUGIN_ID, text, t));
// }
//
// /**
// * Log an error to the Eclipse log, using the exception's message as the log message text.
// *
// * @param t the throwable.
// */
// public void logError(Throwable t) {
// logError(t, t.getMessage());
// }
//
// /**
// * Log info to the Eclipse log.
// *
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logInfo(String fmt, Object... args) {
// log(IStatus.INFO, fmt, args);
// }
//
// /**
// * Log warning to the Eclipse log.
// *
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logWarning(String fmt, Object... args) {
// log(IStatus.WARNING, fmt, args);
// }
//
//
// /**
// * Log a message to the Eclipse log.
// *
// * @param severity message severity. Reference {@link IStatus#getSeverity()}.
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void log(int severity, String fmt, Object... args) {
// String text = (args.length > 0) ? String.format(fmt, args) : fmt;
// log(new Status(severity, MechanicPlugin.PLUGIN_ID, text));
// }
// }
| import com.google.common.base.Objects;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.plugin.core.MechanicLog;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.bindings.Binding;
import org.eclipse.jface.bindings.Scheme;
import org.eclipse.jface.bindings.keys.KeyBinding;
import org.eclipse.jface.bindings.keys.KeySequence;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map; | * Creates a new instance from a defined set of bindings.
*/
public KeyBindings(Binding[] bindings) {
this(MechanicLog.getDefault(), bindings);
}
KeyBindings(MechanicLog log, Binding[] bindings) {
this.log = log;
List<Binding> ub = new ArrayList<Binding>();
List<Binding> sb = new ArrayList<Binding>();
for (Binding binding : bindings) {
if (binding.getType() == Binding.USER) {
ub.add(binding);
} else if (binding.getType() == Binding.SYSTEM) {
sb.add(binding);
} else {
throw new UnsupportedOperationException("Unexpected binding type: " + binding.getType());
}
}
this.userBindings = ub;
this.systemBindings = Collections.unmodifiableList(sb);
this.userBindingsMap = buildQualifierToBindingMap(userBindings);
this.systemBindingsMap = buildQualifierToBindingMap(systemBindings);
}
static Multimap<KbaChangeSetQualifier,Binding> buildQualifierToBindingMap(List<Binding> bindings) {
Multimap<KbaChangeSetQualifier,Binding> result = ArrayListMultimap.create();
for (Binding binding : bindings) {
result.put( | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicLog.java
// public class MechanicLog {
// private static MechanicLog DEFAULT;
//
// private final ILog log;
//
// /**
// * Get the default instance.
// */
// public synchronized static MechanicLog getDefault() {
// if (DEFAULT == null) {
// DEFAULT = new MechanicLog(MechanicPlugin.getDefault());
// }
// return DEFAULT;
// }
//
// MechanicLog(Plugin plugin) {
// this(plugin.getLog());
// }
//
// public MechanicLog(ILog log) {
// this.log = Preconditions.checkNotNull(log);
// }
//
// /**
// * Log a status.
// */
// public void log(IStatus status) {
// log.log(status);
// }
//
// /**
// * Log an error to the Eclipse log.
// *
// * @param t the throwable.
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logError(Throwable t, String fmt, Object... args) {
// String text = (args.length > 0) ? String.format(fmt, args) : fmt;
// log(new Status(IStatus.ERROR, MechanicPlugin.PLUGIN_ID, text, t));
// }
//
// /**
// * Log an error to the Eclipse log, using the exception's message as the log message text.
// *
// * @param t the throwable.
// */
// public void logError(Throwable t) {
// logError(t, t.getMessage());
// }
//
// /**
// * Log info to the Eclipse log.
// *
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logInfo(String fmt, Object... args) {
// log(IStatus.INFO, fmt, args);
// }
//
// /**
// * Log warning to the Eclipse log.
// *
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logWarning(String fmt, Object... args) {
// log(IStatus.WARNING, fmt, args);
// }
//
//
// /**
// * Log a message to the Eclipse log.
// *
// * @param severity message severity. Reference {@link IStatus#getSeverity()}.
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void log(int severity, String fmt, Object... args) {
// String text = (args.length > 0) ? String.format(fmt, args) : fmt;
// log(new Status(severity, MechanicPlugin.PLUGIN_ID, text));
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindings.java
import com.google.common.base.Objects;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.plugin.core.MechanicLog;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.bindings.Binding;
import org.eclipse.jface.bindings.Scheme;
import org.eclipse.jface.bindings.keys.KeyBinding;
import org.eclipse.jface.bindings.keys.KeySequence;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
* Creates a new instance from a defined set of bindings.
*/
public KeyBindings(Binding[] bindings) {
this(MechanicLog.getDefault(), bindings);
}
KeyBindings(MechanicLog log, Binding[] bindings) {
this.log = log;
List<Binding> ub = new ArrayList<Binding>();
List<Binding> sb = new ArrayList<Binding>();
for (Binding binding : bindings) {
if (binding.getType() == Binding.USER) {
ub.add(binding);
} else if (binding.getType() == Binding.SYSTEM) {
sb.add(binding);
} else {
throw new UnsupportedOperationException("Unexpected binding type: " + binding.getType());
}
}
this.userBindings = ub;
this.systemBindings = Collections.unmodifiableList(sb);
this.userBindingsMap = buildQualifierToBindingMap(userBindings);
this.systemBindingsMap = buildQualifierToBindingMap(systemBindings);
}
static Multimap<KbaChangeSetQualifier,Binding> buildQualifierToBindingMap(List<Binding> bindings) {
Multimap<KbaChangeSetQualifier,Binding> result = ArrayListMultimap.create();
for (Binding binding : bindings) {
result.put( | qualifierForBinding(binding, Action.ADD), |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/SimpleExtensionPointManager.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
import com.google.common.collect.Lists;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin; | /*******************************************************************************
* Copyright (C) 2014, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* Utilities for working with simple extension points.
*
* <p>These extension points need to be limited to those that take a single
* {@code class} attribute, with an optional {@code forcePluginActivation} argument.
*/
public class SimpleExtensionPointManager<T> {
private static final Logger LOG = Logger.getLogger(ScannersExtensionPoint.class.getName());
private final List<SimpleProxy<T>> proxies;
private SimpleExtensionPointManager(
String extensionPointName,
Class<T> klass,
String elementName,
String classNameAttr,
String forcePluginActivationAttr) {
this.proxies = createProxies(
extensionPointName, klass, elementName, classNameAttr, forcePluginActivationAttr);
}
/**
* Create a new instance, which reads all plugin configurations, and prepares for loading
* instances.
*
* @param extensionPointName the name of the extension point.
* @param klass the base type of all the items in this proxy
* @param elementName the element name that represents the configuration
* @param classNameAttr the attribute name representing the class being built.
* @param forcePluginActivationAttr the attribute name representing whether the class should be
* instantiated even if the plugin hasn't been activated. When this is {@code null} it means the
* extension point doesn't support variable plugin activation, and classes will be instantiated
* even if that means starting
* @return A list of {@code SimpleProxy} items which can be passed to {@link #activateProxies(Collection)}
*/
public static <T> SimpleExtensionPointManager<T> newInstance(
String extensionPointName,
Class<T> klass,
String elementName,
String classNameAttr,
String forcePluginActivationAttr) {
return new SimpleExtensionPointManager<T>(
extensionPointName, klass, elementName, classNameAttr, forcePluginActivationAttr);
}
private List<SimpleProxy<T>> createProxies(
String extensionPointName,
Class<T> klass,
String elementName,
String classNameAttr,
String forcePluginActivationAttr) {
List<SimpleProxy<T>> proxies = Lists.newArrayList();
// Load the reference to the extension.
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint( | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/SimpleExtensionPointManager.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtension;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.Platform;
import com.google.common.collect.Lists;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;
/*******************************************************************************
* Copyright (C) 2014, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* Utilities for working with simple extension points.
*
* <p>These extension points need to be limited to those that take a single
* {@code class} attribute, with an optional {@code forcePluginActivation} argument.
*/
public class SimpleExtensionPointManager<T> {
private static final Logger LOG = Logger.getLogger(ScannersExtensionPoint.class.getName());
private final List<SimpleProxy<T>> proxies;
private SimpleExtensionPointManager(
String extensionPointName,
Class<T> klass,
String elementName,
String classNameAttr,
String forcePluginActivationAttr) {
this.proxies = createProxies(
extensionPointName, klass, elementName, classNameAttr, forcePluginActivationAttr);
}
/**
* Create a new instance, which reads all plugin configurations, and prepares for loading
* instances.
*
* @param extensionPointName the name of the extension point.
* @param klass the base type of all the items in this proxy
* @param elementName the element name that represents the configuration
* @param classNameAttr the attribute name representing the class being built.
* @param forcePluginActivationAttr the attribute name representing whether the class should be
* instantiated even if the plugin hasn't been activated. When this is {@code null} it means the
* extension point doesn't support variable plugin activation, and classes will be instantiated
* even if that means starting
* @return A list of {@code SimpleProxy} items which can be passed to {@link #activateProxies(Collection)}
*/
public static <T> SimpleExtensionPointManager<T> newInstance(
String extensionPointName,
Class<T> klass,
String elementName,
String classNameAttr,
String forcePluginActivationAttr) {
return new SimpleExtensionPointManager<T>(
extensionPointName, klass, elementName, classNameAttr, forcePluginActivationAttr);
}
private List<SimpleProxy<T>> createProxies(
String extensionPointName,
Class<T> klass,
String elementName,
String classNameAttr,
String forcePluginActivationAttr) {
List<SimpleProxy<T>> proxies = Lists.newArrayList();
// Load the reference to the extension.
IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint( | MechanicPlugin.PLUGIN_ID, extensionPointName); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsModel.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
| import java.util.List;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.gson.annotations.SerializedName; | /*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* A java representation of a .kbd task, abbreviated as KBA.
*
* <p>This, in disk, is represented as a JSON string.
*
* <p>This class operates with primitive types (Strings, ints, lists), not with
* Eclipse constructs.
*
* @author zorzella@google.com
*/
class KeyBindingsModel {
@SerializedName(KeyBindingsParser.METADATA_JSON_KEY)
private final KbaMetaData kbaMetadata;
@SerializedName(KeyBindingsParser.CHANGE_SETS_JSON_KEY)
private final ImmutableList<KbaChangeSet> kbaChangeSetList;
public KeyBindingsModel(List<KbaChangeSet> changeSetList, KbaMetaData metadata) {
this.kbaChangeSetList = filteredChangeSetList(changeSetList);
this.kbaMetadata = metadata;
}
private static ImmutableList<KbaChangeSet> filteredChangeSetList(
List<KbaChangeSet> changeSetList) {
Predicate<KbaChangeSet> filterOutRemoveActions = new Predicate<KbaChangeSet>() {
public boolean apply(KbaChangeSet source) {
// TODO: support remove
if (KeyboardBindingsTask.ENABLE_EXP_REM()) {
return true;
} | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsModel.java
import java.util.List;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.gson.annotations.SerializedName;
/*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* A java representation of a .kbd task, abbreviated as KBA.
*
* <p>This, in disk, is represented as a JSON string.
*
* <p>This class operates with primitive types (Strings, ints, lists), not with
* Eclipse constructs.
*
* @author zorzella@google.com
*/
class KeyBindingsModel {
@SerializedName(KeyBindingsParser.METADATA_JSON_KEY)
private final KbaMetaData kbaMetadata;
@SerializedName(KeyBindingsParser.CHANGE_SETS_JSON_KEY)
private final ImmutableList<KbaChangeSet> kbaChangeSetList;
public KeyBindingsModel(List<KbaChangeSet> changeSetList, KbaMetaData metadata) {
this.kbaChangeSetList = filteredChangeSetList(changeSetList);
this.kbaMetadata = metadata;
}
private static ImmutableList<KbaChangeSet> filteredChangeSetList(
List<KbaChangeSet> changeSetList) {
Predicate<KbaChangeSet> filterOutRemoveActions = new Predicate<KbaChangeSet>() {
public boolean apply(KbaChangeSet source) {
// TODO: support remove
if (KeyboardBindingsTask.ENABLE_EXP_REM()) {
return true;
} | return source.getAction() == Action.ADD; |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/DirectoryOrUrlEditor.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/ResourceTaskProviderParser.java
// public class ResourceTaskProviderParser {
//
// private static final Gson gson = new Gson();
//
// private final Function<String, String> variableParser;
//
// /**
// * Create a new instance.
// *
// * @param variableParser used to perform variable substitution. One such translator is
// * {@link VariableManagerStringParser#INSTANCE}. To get the raw values, pass
// * {@code Functions.<String>identity()}
// */
// public ResourceTaskProviderParser(Function<String, String> variableParser) {
// this.variableParser = Preconditions.checkNotNull(variableParser);
// }
//
// public final String[] parse(String text) {
// if (!text.startsWith("[")) {
// // I would use Splitter, but I won't use split.
// StringTokenizer st = new StringTokenizer(text, File.pathSeparator);
// List<String> list = Lists.newArrayList();
// while (st.hasMoreElements()) {
// String elem = (String) st.nextElement();
// // Historically paths named "null" somehow got added to default prefs
// if (elem == null) {
// continue;
// }
// String substituted = variableParser.apply(elem);
// list.add(substituted);
// }
// return list.toArray(new String[0]);
// } else {
// return gson.fromJson(text, String[].class);
// }
// }
//
// public final String unparse(String... items) {
// return gson.toJson(items);
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/VariableManagerStringParser.java
// public class VariableManagerStringParser implements Function<String, String> {
// public static final VariableManagerStringParser INSTANCE = new VariableManagerStringParser();
//
// private VariableManagerStringParser() { }
//
// public String apply(String input) {
// try {
// IStringVariableManager stringManager =
// VariablesPlugin.getDefault().getStringVariableManager();
// return stringManager.performStringSubstitution(input);
// } catch (CoreException e) {
// return "";
// }
// }
// }
| import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.ListEditor;
import org.eclipse.swt.widgets.Composite;
import com.google.eclipse.mechanic.internal.ResourceTaskProviderParser;
import com.google.eclipse.mechanic.internal.VariableManagerStringParser; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* An editor that lets the user select either a URL resource or
* directory path. Adding a path uses a filesystem-aware
* dialog box while the URL editor is a plain text box.
*/
public class DirectoryOrUrlEditor extends ListEditor {
private static final ResourceTaskProviderParser parser = | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/ResourceTaskProviderParser.java
// public class ResourceTaskProviderParser {
//
// private static final Gson gson = new Gson();
//
// private final Function<String, String> variableParser;
//
// /**
// * Create a new instance.
// *
// * @param variableParser used to perform variable substitution. One such translator is
// * {@link VariableManagerStringParser#INSTANCE}. To get the raw values, pass
// * {@code Functions.<String>identity()}
// */
// public ResourceTaskProviderParser(Function<String, String> variableParser) {
// this.variableParser = Preconditions.checkNotNull(variableParser);
// }
//
// public final String[] parse(String text) {
// if (!text.startsWith("[")) {
// // I would use Splitter, but I won't use split.
// StringTokenizer st = new StringTokenizer(text, File.pathSeparator);
// List<String> list = Lists.newArrayList();
// while (st.hasMoreElements()) {
// String elem = (String) st.nextElement();
// // Historically paths named "null" somehow got added to default prefs
// if (elem == null) {
// continue;
// }
// String substituted = variableParser.apply(elem);
// list.add(substituted);
// }
// return list.toArray(new String[0]);
// } else {
// return gson.fromJson(text, String[].class);
// }
// }
//
// public final String unparse(String... items) {
// return gson.toJson(items);
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/VariableManagerStringParser.java
// public class VariableManagerStringParser implements Function<String, String> {
// public static final VariableManagerStringParser INSTANCE = new VariableManagerStringParser();
//
// private VariableManagerStringParser() { }
//
// public String apply(String input) {
// try {
// IStringVariableManager stringManager =
// VariablesPlugin.getDefault().getStringVariableManager();
// return stringManager.performStringSubstitution(input);
// } catch (CoreException e) {
// return "";
// }
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/DirectoryOrUrlEditor.java
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.preference.ListEditor;
import org.eclipse.swt.widgets.Composite;
import com.google.eclipse.mechanic.internal.ResourceTaskProviderParser;
import com.google.eclipse.mechanic.internal.VariableManagerStringParser;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* An editor that lets the user select either a URL resource or
* directory path. Adding a path uses a filesystem-aware
* dialog box while the URL editor is a plain text box.
*/
public class DirectoryOrUrlEditor extends ListEditor {
private static final ResourceTaskProviderParser parser = | new ResourceTaskProviderParser(VariableManagerStringParser.INSTANCE); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/CompositeResourceTaskProvider.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
| import java.util.Collection;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference; | package com.google.eclipse.mechanic.internal;
/**
* Collects from multiple task providers in one go.
*/
public class CompositeResourceTaskProvider implements IResourceTaskProvider {
private final List<IResourceTaskProvider> providers;
public CompositeResourceTaskProvider(Collection<IResourceTaskProvider> providers) {
this.providers = ImmutableList.copyOf(providers);
}
public void collectTaskReferences(String extFilter, | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/CompositeResourceTaskProvider.java
import java.util.Collection;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
package com.google.eclipse.mechanic.internal;
/**
* Collects from multiple task providers in one go.
*/
public class CompositeResourceTaskProvider implements IResourceTaskProvider {
private final List<IResourceTaskProvider> providers;
public CompositeResourceTaskProvider(Collection<IResourceTaskProvider> providers) {
this.providers = ImmutableList.copyOf(providers);
}
public void collectTaskReferences(String extFilter, | ICollector<IResourceTaskReference> collector) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/CompositeResourceTaskProvider.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
| import java.util.Collection;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference; | package com.google.eclipse.mechanic.internal;
/**
* Collects from multiple task providers in one go.
*/
public class CompositeResourceTaskProvider implements IResourceTaskProvider {
private final List<IResourceTaskProvider> providers;
public CompositeResourceTaskProvider(Collection<IResourceTaskProvider> providers) {
this.providers = ImmutableList.copyOf(providers);
}
public void collectTaskReferences(String extFilter, | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/CompositeResourceTaskProvider.java
import java.util.Collection;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
package com.google.eclipse.mechanic.internal;
/**
* Collects from multiple task providers in one go.
*/
public class CompositeResourceTaskProvider implements IResourceTaskProvider {
private final List<IResourceTaskProvider> providers;
public CompositeResourceTaskProvider(Collection<IResourceTaskProvider> providers) {
this.providers = ImmutableList.copyOf(providers);
}
public void collectTaskReferences(String extFilter, | ICollector<IResourceTaskReference> collector) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/FileTaskProvider.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/SuffixFileFilter.java
// public final class SuffixFileFilter implements FileFilter {
//
// private final String suffix;
//
// public SuffixFileFilter(String suffix) {
// this.suffix = suffix;
// }
//
// public boolean accept(File file) {
// return file.getName().endsWith(suffix);
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/ResourceTaskProvider.java
// public abstract class ResourceTaskProvider implements IResourceTaskProvider {
//
// /**
// * Throws exception, ensures subclasses implement equals method.
// */
// @Override
// public boolean equals(Object obj) {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement equals");
// }
//
// /**
// * Throws exception, ensures subclasses implement hashCode method.
// */
// @Override
// public int hashCode() {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement hashCode");
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.SuffixFileFilter;
import com.google.eclipse.mechanic.plugin.core.ResourceTaskProvider; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
public final class FileTaskProvider extends ResourceTaskProvider {
private static final Logger LOG = Logger.getLogger(FileTaskProvider.class.getName());
private final File dir;
/**
* This is only public for ClassFileTaskScanner. See if we can make this private.
*/ | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/SuffixFileFilter.java
// public final class SuffixFileFilter implements FileFilter {
//
// private final String suffix;
//
// public SuffixFileFilter(String suffix) {
// this.suffix = suffix;
// }
//
// public boolean accept(File file) {
// return file.getName().endsWith(suffix);
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/ResourceTaskProvider.java
// public abstract class ResourceTaskProvider implements IResourceTaskProvider {
//
// /**
// * Throws exception, ensures subclasses implement equals method.
// */
// @Override
// public boolean equals(Object obj) {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement equals");
// }
//
// /**
// * Throws exception, ensures subclasses implement hashCode method.
// */
// @Override
// public int hashCode() {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement hashCode");
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/FileTaskProvider.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.SuffixFileFilter;
import com.google.eclipse.mechanic.plugin.core.ResourceTaskProvider;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
public final class FileTaskProvider extends ResourceTaskProvider {
private static final Logger LOG = Logger.getLogger(FileTaskProvider.class.getName());
private final File dir;
/**
* This is only public for ClassFileTaskScanner. See if we can make this private.
*/ | public final class TaskReference implements IResourceTaskReference { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/FileTaskProvider.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/SuffixFileFilter.java
// public final class SuffixFileFilter implements FileFilter {
//
// private final String suffix;
//
// public SuffixFileFilter(String suffix) {
// this.suffix = suffix;
// }
//
// public boolean accept(File file) {
// return file.getName().endsWith(suffix);
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/ResourceTaskProvider.java
// public abstract class ResourceTaskProvider implements IResourceTaskProvider {
//
// /**
// * Throws exception, ensures subclasses implement equals method.
// */
// @Override
// public boolean equals(Object obj) {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement equals");
// }
//
// /**
// * Throws exception, ensures subclasses implement hashCode method.
// */
// @Override
// public int hashCode() {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement hashCode");
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.SuffixFileFilter;
import com.google.eclipse.mechanic.plugin.core.ResourceTaskProvider; | }
@VisibleForTesting
static FileTaskProvider newInstance(File dir, Properties properties) throws IOException {
Preconditions.checkNotNull(dir);
FileTaskProvider instance = new FileTaskProvider(dir, properties);
instance.validateInitialization();
return instance;
}
/**
* REMOVE as we move things along.
*/
public File getFile() {
return dir;
}
private void validateInitialization() throws IOException {
if (!dir.exists()) {
throw new FileNotFoundException(
String.format("Directory '%s' does not exist.", dir));
}
if (!dir.canRead()) {
throw new IOException(
String.format("Directory '%s' is not readable.", dir));
}
}
public void collectTaskReferences( | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/SuffixFileFilter.java
// public final class SuffixFileFilter implements FileFilter {
//
// private final String suffix;
//
// public SuffixFileFilter(String suffix) {
// this.suffix = suffix;
// }
//
// public boolean accept(File file) {
// return file.getName().endsWith(suffix);
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/ResourceTaskProvider.java
// public abstract class ResourceTaskProvider implements IResourceTaskProvider {
//
// /**
// * Throws exception, ensures subclasses implement equals method.
// */
// @Override
// public boolean equals(Object obj) {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement equals");
// }
//
// /**
// * Throws exception, ensures subclasses implement hashCode method.
// */
// @Override
// public int hashCode() {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement hashCode");
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/FileTaskProvider.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.SuffixFileFilter;
import com.google.eclipse.mechanic.plugin.core.ResourceTaskProvider;
}
@VisibleForTesting
static FileTaskProvider newInstance(File dir, Properties properties) throws IOException {
Preconditions.checkNotNull(dir);
FileTaskProvider instance = new FileTaskProvider(dir, properties);
instance.validateInitialization();
return instance;
}
/**
* REMOVE as we move things along.
*/
public File getFile() {
return dir;
}
private void validateInitialization() throws IOException {
if (!dir.exists()) {
throw new FileNotFoundException(
String.format("Directory '%s' does not exist.", dir));
}
if (!dir.canRead()) {
throw new IOException(
String.format("Directory '%s' is not readable.", dir));
}
}
public void collectTaskReferences( | String localPath, String filter, ICollector<IResourceTaskReference> collector) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/FileTaskProvider.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/SuffixFileFilter.java
// public final class SuffixFileFilter implements FileFilter {
//
// private final String suffix;
//
// public SuffixFileFilter(String suffix) {
// this.suffix = suffix;
// }
//
// public boolean accept(File file) {
// return file.getName().endsWith(suffix);
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/ResourceTaskProvider.java
// public abstract class ResourceTaskProvider implements IResourceTaskProvider {
//
// /**
// * Throws exception, ensures subclasses implement equals method.
// */
// @Override
// public boolean equals(Object obj) {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement equals");
// }
//
// /**
// * Throws exception, ensures subclasses implement hashCode method.
// */
// @Override
// public int hashCode() {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement hashCode");
// }
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.SuffixFileFilter;
import com.google.eclipse.mechanic.plugin.core.ResourceTaskProvider; | return dir;
}
private void validateInitialization() throws IOException {
if (!dir.exists()) {
throw new FileNotFoundException(
String.format("Directory '%s' does not exist.", dir));
}
if (!dir.canRead()) {
throw new IOException(
String.format("Directory '%s' is not readable.", dir));
}
}
public void collectTaskReferences(
String localPath, String filter, ICollector<IResourceTaskReference> collector) {
// dir points to the root of the task directory, we
// add the PACKAGE PATH to point to the dir with classes.
File localDir = new File(dir.getAbsolutePath() + File.separator + localPath);
try {
FileTaskProvider.newInstance(localDir).collectTaskReferences(filter, collector);
} catch(FileNotFoundException e) {
// Ignore, this will happen most of the time.
} catch(IOException e) {
// Ugh, another mess that class files make. :)
LOG.log(Level.SEVERE, "Can't collect relative files.", e);
}
}
public void collectTaskReferences(String filterText, ICollector<IResourceTaskReference> collector) { | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/SuffixFileFilter.java
// public final class SuffixFileFilter implements FileFilter {
//
// private final String suffix;
//
// public SuffixFileFilter(String suffix) {
// this.suffix = suffix;
// }
//
// public boolean accept(File file) {
// return file.getName().endsWith(suffix);
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/ResourceTaskProvider.java
// public abstract class ResourceTaskProvider implements IResourceTaskProvider {
//
// /**
// * Throws exception, ensures subclasses implement equals method.
// */
// @Override
// public boolean equals(Object obj) {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement equals");
// }
//
// /**
// * Throws exception, ensures subclasses implement hashCode method.
// */
// @Override
// public int hashCode() {
// throw new RuntimeException(this.getClass().getName() + "doesn't implement hashCode");
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/FileTaskProvider.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskReference;
import com.google.eclipse.mechanic.SuffixFileFilter;
import com.google.eclipse.mechanic.plugin.core.ResourceTaskProvider;
return dir;
}
private void validateInitialization() throws IOException {
if (!dir.exists()) {
throw new FileNotFoundException(
String.format("Directory '%s' does not exist.", dir));
}
if (!dir.canRead()) {
throw new IOException(
String.format("Directory '%s' is not readable.", dir));
}
}
public void collectTaskReferences(
String localPath, String filter, ICollector<IResourceTaskReference> collector) {
// dir points to the root of the task directory, we
// add the PACKAGE PATH to point to the dir with classes.
File localDir = new File(dir.getAbsolutePath() + File.separator + localPath);
try {
FileTaskProvider.newInstance(localDir).collectTaskReferences(filter, collector);
} catch(FileNotFoundException e) {
// Ignore, this will happen most of the time.
} catch(IOException e) {
// Ugh, another mess that class files make. :)
LOG.log(Level.SEVERE, "Can't collect relative files.", e);
}
}
public void collectTaskReferences(String filterText, ICollector<IResourceTaskReference> collector) { | SuffixFileFilter filter = new SuffixFileFilter(filterText); |
alfsch/workspacemechanic | parent/examples/com.google.eclipse.mechanic.samples/src/com/google/eclipse/mechanic/samples/InMemoryTaskProvider.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
| import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteStreams;
import com.google.common.io.InputSupplier;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference; | /*******************************************************************************
* Copyright (C) 2014, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.samples;
/**
* Task provider that uses an in-memory map to provide task data.
*/
public class InMemoryTaskProvider implements IResourceTaskProvider {
private static final Map<String, String> RESOURCES = Maps.newLinkedHashMap();
private static final String SHOW_LINE_NUMBERS = Joiner.on("\n").join(
"# @title Show Line Numbers",
"# @description Show line numbers in text editors.",
"# @audit_type LASTMOD",
"",
"file_export_version=3.0",
"/instance/org.eclipse.ui.editors/lineNumberRuler=true");
static {
RESOURCES.put("foo.message", "HELLO");
RESOURCES.put("showlinenumbers.epf", SHOW_LINE_NUMBERS);
RESOURCES.put("breakpoint.showview", "org.eclipse.debug.ui.BreakpointView");
RESOURCES.put("junit.showview", "org.eclipse.jdt.junit.ResultView");
RESOURCES.put("packageexplorer.showview", "org.eclipse.jdt.ui.PackageExplorer");
}
public void collectTaskReferences(String extFilter, | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
// Path: parent/examples/com.google.eclipse.mechanic.samples/src/com/google/eclipse/mechanic/samples/InMemoryTaskProvider.java
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteStreams;
import com.google.common.io.InputSupplier;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
/*******************************************************************************
* Copyright (C) 2014, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.samples;
/**
* Task provider that uses an in-memory map to provide task data.
*/
public class InMemoryTaskProvider implements IResourceTaskProvider {
private static final Map<String, String> RESOURCES = Maps.newLinkedHashMap();
private static final String SHOW_LINE_NUMBERS = Joiner.on("\n").join(
"# @title Show Line Numbers",
"# @description Show line numbers in text editors.",
"# @audit_type LASTMOD",
"",
"file_export_version=3.0",
"/instance/org.eclipse.ui.editors/lineNumberRuler=true");
static {
RESOURCES.put("foo.message", "HELLO");
RESOURCES.put("showlinenumbers.epf", SHOW_LINE_NUMBERS);
RESOURCES.put("breakpoint.showview", "org.eclipse.debug.ui.BreakpointView");
RESOURCES.put("junit.showview", "org.eclipse.jdt.junit.ResultView");
RESOURCES.put("packageexplorer.showview", "org.eclipse.jdt.ui.PackageExplorer");
}
public void collectTaskReferences(String extFilter, | ICollector<IResourceTaskReference> collector) { |
alfsch/workspacemechanic | parent/examples/com.google.eclipse.mechanic.samples/src/com/google/eclipse/mechanic/samples/InMemoryTaskProvider.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
| import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteStreams;
import com.google.common.io.InputSupplier;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference; | /*******************************************************************************
* Copyright (C) 2014, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.samples;
/**
* Task provider that uses an in-memory map to provide task data.
*/
public class InMemoryTaskProvider implements IResourceTaskProvider {
private static final Map<String, String> RESOURCES = Maps.newLinkedHashMap();
private static final String SHOW_LINE_NUMBERS = Joiner.on("\n").join(
"# @title Show Line Numbers",
"# @description Show line numbers in text editors.",
"# @audit_type LASTMOD",
"",
"file_export_version=3.0",
"/instance/org.eclipse.ui.editors/lineNumberRuler=true");
static {
RESOURCES.put("foo.message", "HELLO");
RESOURCES.put("showlinenumbers.epf", SHOW_LINE_NUMBERS);
RESOURCES.put("breakpoint.showview", "org.eclipse.debug.ui.BreakpointView");
RESOURCES.put("junit.showview", "org.eclipse.jdt.junit.ResultView");
RESOURCES.put("packageexplorer.showview", "org.eclipse.jdt.ui.PackageExplorer");
}
public void collectTaskReferences(String extFilter, | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/ICollector.java
// public interface ICollector<T> {
// /**
// * Add a element to the collector.
// */
// void collect(T element);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskReference.java
// public interface IResourceTaskReference {
// /** Return the name of the task reference. This is typically a local name. */
// String getName();
//
// /** Return the task reference as an input stream. */
// InputStream newInputStream() throws IOException;
//
// /**
// * Return the time this resource was last modified, in milliseconds since the epoch.
// */
// long getLastModified() throws IOException;
//
// /**
// * Return the task reference path. Provide enough metadata to give it some distinction,
// * separate from other providers.
// */
// String getPath();
//
// /**
// * Return the File representation of this resource. Is {@code null} it's not a File.
// */
// File asFile();
//
// /**
// * Return the MD5 hash of this task
// */
// long computeMD5() throws IOException;
// }
// Path: parent/examples/com.google.eclipse.mechanic.samples/src/com/google/eclipse/mechanic/samples/InMemoryTaskProvider.java
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteStreams;
import com.google.common.io.InputSupplier;
import com.google.eclipse.mechanic.ICollector;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.IResourceTaskReference;
/*******************************************************************************
* Copyright (C) 2014, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.samples;
/**
* Task provider that uses an in-memory map to provide task data.
*/
public class InMemoryTaskProvider implements IResourceTaskProvider {
private static final Map<String, String> RESOURCES = Maps.newLinkedHashMap();
private static final String SHOW_LINE_NUMBERS = Joiner.on("\n").join(
"# @title Show Line Numbers",
"# @description Show line numbers in text editors.",
"# @audit_type LASTMOD",
"",
"file_export_version=3.0",
"/instance/org.eclipse.ui.editors/lineNumberRuler=true");
static {
RESOURCES.put("foo.message", "HELLO");
RESOURCES.put("showlinenumbers.epf", SHOW_LINE_NUMBERS);
RESOURCES.put("breakpoint.showview", "org.eclipse.debug.ui.BreakpointView");
RESOURCES.put("junit.showview", "org.eclipse.jdt.junit.ResultView");
RESOURCES.put("packageexplorer.showview", "org.eclipse.jdt.ui.PackageExplorer");
}
public void collectTaskReferences(String extFilter, | ICollector<IResourceTaskReference> collector) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/UserChoiceDecisionProvider.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairDecisionProvider.java
// public interface RepairDecisionProvider {
//
// /**
// * Represents a user's decision to proceed or abort.
// */
// public enum ResponseStatus {
// OK,
// CANCEL
// }
//
// /**
// * Represents the possible actions a user can select for an Task.
// */
// public enum Decision {
//
// YES,
// NO,
// NEVER;
//
// public static Decision valueOf(int ord) {
// return Decision.values()[ord];
// }
// }
//
// /**
// * Provides implementations an opportunity to collect information
// * from the user. Will be called before getDecisions() is called.
// *
// * Returns the response status for this repair action. If the status is
// * {@code ResponseStatus.OK}, then the service should proceed to evaluate
// * individual repair decisions, else, the service should abort the operation.
// */
// public ResponseStatus initialize(List<Task> failing);
//
// /**
// * Returns map of {@link Task} to the user's choice for that Task.
// */
// public Map<Task, Decision> getDecisions();
//
// }
| import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.RepairDecisionProvider;
import org.eclipse.ui.IWorkbenchWindow;
import java.util.Collections;
import java.util.List;
import java.util.Map; | /*******************************************************************************
* Copyright (C) 2009, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* Adapts MechanicDialog to the RepairDecisionProvider interface as needed by
* {@link com.google.eclipse.mechanic.RepairManager}.
*
* @author smckay@google.com (Steve McKay)
*/
class UserChoiceDecisionProvider implements RepairDecisionProvider {
private final IWorkbenchWindow window;
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairDecisionProvider.java
// public interface RepairDecisionProvider {
//
// /**
// * Represents a user's decision to proceed or abort.
// */
// public enum ResponseStatus {
// OK,
// CANCEL
// }
//
// /**
// * Represents the possible actions a user can select for an Task.
// */
// public enum Decision {
//
// YES,
// NO,
// NEVER;
//
// public static Decision valueOf(int ord) {
// return Decision.values()[ord];
// }
// }
//
// /**
// * Provides implementations an opportunity to collect information
// * from the user. Will be called before getDecisions() is called.
// *
// * Returns the response status for this repair action. If the status is
// * {@code ResponseStatus.OK}, then the service should proceed to evaluate
// * individual repair decisions, else, the service should abort the operation.
// */
// public ResponseStatus initialize(List<Task> failing);
//
// /**
// * Returns map of {@link Task} to the user's choice for that Task.
// */
// public Map<Task, Decision> getDecisions();
//
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/UserChoiceDecisionProvider.java
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.RepairDecisionProvider;
import org.eclipse.ui.IWorkbenchWindow;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/*******************************************************************************
* Copyright (C) 2009, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* Adapts MechanicDialog to the RepairDecisionProvider interface as needed by
* {@link com.google.eclipse.mechanic.RepairManager}.
*
* @author smckay@google.com (Steve McKay)
*/
class UserChoiceDecisionProvider implements RepairDecisionProvider {
private final IWorkbenchWindow window;
| private Map<Task, RepairDecisionProvider.Decision> decisions |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/recorder/PreferenceRecorder.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
| import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
import org.osgi.service.prefs.BackingStoreException;
import java.util.List;
import java.util.Set; | private List<PreferenceChange> changeLog = Lists.newArrayList();
/**
* Starts the process of recording changes to the eclipse preference tree.
* Recording may only occur once per recorder.
*
* @throws CoreException if there is a problem with the preference tree
* itself.
* @throws IllegalStateException if this object has already been used to
* record.
*/
public void startRecording() throws CoreException {
synchronized (lock) {
Preconditions.checkState(currState == State.IDLE, "Recorder object has already recorded preference changes.");
currState = State.RECORDING;
this.addListeners(Platform.getPreferencesService().getRootNode());
}
}
private void addListeners(IEclipsePreferences node) throws CoreException {
addListener(node);
try {
for (String childName : node.childrenNames()) {
IEclipsePreferences child = (IEclipsePreferences) node.node(childName);
this.addListeners(child);
}
} catch (BackingStoreException e) { | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/recorder/PreferenceRecorder.java
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.INodeChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.IPreferenceChangeListener;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.NodeChangeEvent;
import org.eclipse.core.runtime.preferences.IEclipsePreferences.PreferenceChangeEvent;
import org.osgi.service.prefs.BackingStoreException;
import java.util.List;
import java.util.Set;
private List<PreferenceChange> changeLog = Lists.newArrayList();
/**
* Starts the process of recording changes to the eclipse preference tree.
* Recording may only occur once per recorder.
*
* @throws CoreException if there is a problem with the preference tree
* itself.
* @throws IllegalStateException if this object has already been used to
* record.
*/
public void startRecording() throws CoreException {
synchronized (lock) {
Preconditions.checkState(currState == State.IDLE, "Recorder object has already recorded preference changes.");
currState = State.RECORDING;
this.addListeners(Platform.getPreferencesService().getRootNode());
}
}
private void addListeners(IEclipsePreferences node) throws CoreException {
addListener(node);
try {
for (String childName : node.childrenNames()) {
IEclipsePreferences child = (IEclipsePreferences) node.node(childName);
this.addListeners(child);
}
} catch (BackingStoreException e) { | throw new CoreException(new Status(IStatus.ERROR, MechanicPlugin.PLUGIN_ID, |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSetQualifier.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
| import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Qualifies a binding by scheme/platform/context/action
*
* <p>If platform is {@code null}, this applies to all platforms.
*/
// TODO: leverage this class in KbaChangeSet
final class KbaChangeSetQualifier {
final String scheme;
final String platform;
final String context;
final String action;
public KbaChangeSetQualifier(
final String scheme,
final String platform,
final String context,
final String actionLabel) {
this(scheme,
platform,
context, | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSetQualifier.java
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Qualifies a binding by scheme/platform/context/action
*
* <p>If platform is {@code null}, this applies to all platforms.
*/
// TODO: leverage this class in KbaChangeSet
final class KbaChangeSetQualifier {
final String scheme;
final String platform;
final String context;
final String action;
public KbaChangeSetQualifier(
final String scheme,
final String platform,
final String context,
final String actionLabel) {
this(scheme,
platform,
context, | Action.fromLabel(actionLabel)); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/ExtensionPointScanner.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/CompositeTaskInterface.java
// public interface CompositeTaskInterface extends Task, Evaluator, RepairAction {
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskScanner.java
// public interface TaskScanner {
//
// /**
// * Adds Tasks to the supplied collector.
// *
// * @param collector the collector of {@link Task}s.
// */
// void scan(TaskCollector collector);
//
// }
| import java.util.List;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.eclipse.mechanic.CompositeTaskInterface;
import com.google.eclipse.mechanic.TaskCollector;
import com.google.eclipse.mechanic.TaskScanner; | /*******************************************************************************
* Copyright (C) 2009, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* Provides support for loading tasks defined in extension points.
*/
public class ExtensionPointScanner implements TaskScanner {
private Supplier<List<CompositeTaskInterface>> taskSupplier;
public ExtensionPointScanner() {
this(TasksExtensionPoint.getInstance());
}
@VisibleForTesting
ExtensionPointScanner(Supplier<List<CompositeTaskInterface>> taskSupplier) {
this.taskSupplier = taskSupplier;
}
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/CompositeTaskInterface.java
// public interface CompositeTaskInterface extends Task, Evaluator, RepairAction {
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskScanner.java
// public interface TaskScanner {
//
// /**
// * Adds Tasks to the supplied collector.
// *
// * @param collector the collector of {@link Task}s.
// */
// void scan(TaskCollector collector);
//
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/ExtensionPointScanner.java
import java.util.List;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.eclipse.mechanic.CompositeTaskInterface;
import com.google.eclipse.mechanic.TaskCollector;
import com.google.eclipse.mechanic.TaskScanner;
/*******************************************************************************
* Copyright (C) 2009, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* Provides support for loading tasks defined in extension points.
*/
public class ExtensionPointScanner implements TaskScanner {
private Supplier<List<CompositeTaskInterface>> taskSupplier;
public ExtensionPointScanner() {
this(TasksExtensionPoint.getInstance());
}
@VisibleForTesting
ExtensionPointScanner(Supplier<List<CompositeTaskInterface>> taskSupplier) {
this.taskSupplier = taskSupplier;
}
| public void scan(TaskCollector collector) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/StateSensitiveCache.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IMechanicService.java
// public interface IMechanicService {
//
// /**
// * Causes the scannning service to start as soon as possible.
// */
// void start();
//
// /**
// * Causes the scanning service to stop scanning.
// */
// void stop();
//
// /**
// * Return true if the mechanic service is not running.
// */
// boolean isStopped();
//
// /**
// * Adds the supplied listener to status change events for the Mechanic (not the
// * Job). UI components can use this facility to get notifications announcing
// * changes in the mechanic service.
// *
// * <p>Callers of this method should note that Mechanic Service will
// * immediately send a notification to the supplied listener when this method
// * is called. Also, callers should remember to unsubscribe listeners when
// * they are disposed (or otherwise reach the end of their life).
// */
// void addTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Removes supplied listener from our set of listeners if it is contained
// * therein, else does nothing.
// *
// * @param statusChangeListener listener to receive status update notifications.
// */
// void removeTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Returns a {@link RepairManager} capable of fixing broken Tasks. The
// * returned {@link RepairManager} will use the supplied
// * {@link RepairDecisionProvider} to collect user input needed to determine
// * what actions to take for each failing Task.
// */
// RepairManager getRepairManager(RepairDecisionProvider rdp);
//
// /**
// * Returns an immutable set of all the currently known tasks, passing or not.
// */
// Collection<Task> getAllKnownTasks();
//
// /**
// * A temporary solution allowing the trim widget to display the number
// * of failing items to the user.
// */
// int getFailingItemCount();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IStatusChangeListener.java
// public interface IStatusChangeListener {
//
// void statusChanged(StatusChangedEvent event);
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/MechanicStatus.java
// public enum MechanicStatus {
//
// /* there are no failing tasks */
// PASSED,
//
// /* there are failing tasks */
// FAILED,
//
// /* mechanic service is updating its set of tasks */
// UPDATING,
//
// /* mechanic service is not running */
// STOPPED
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/StatusChangedEvent.java
// public class StatusChangedEvent {
//
// private final MechanicStatus status;
//
// public StatusChangedEvent(MechanicStatus status) {
// this.status = status;
// }
//
// public MechanicStatus getStatus() {
// return status;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import com.google.common.base.Preconditions;
import com.google.eclipse.mechanic.IMechanicService;
import com.google.eclipse.mechanic.IStatusChangeListener;
import com.google.eclipse.mechanic.MechanicStatus;
import com.google.eclipse.mechanic.StatusChangedEvent; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* A {@link IUriContentProvider} that clears its cache when the Mechanic starts a
* scanning session.
*/
public final class StateSensitiveCache implements IUriContentProvider {
private final IMechanicService service; | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IMechanicService.java
// public interface IMechanicService {
//
// /**
// * Causes the scannning service to start as soon as possible.
// */
// void start();
//
// /**
// * Causes the scanning service to stop scanning.
// */
// void stop();
//
// /**
// * Return true if the mechanic service is not running.
// */
// boolean isStopped();
//
// /**
// * Adds the supplied listener to status change events for the Mechanic (not the
// * Job). UI components can use this facility to get notifications announcing
// * changes in the mechanic service.
// *
// * <p>Callers of this method should note that Mechanic Service will
// * immediately send a notification to the supplied listener when this method
// * is called. Also, callers should remember to unsubscribe listeners when
// * they are disposed (or otherwise reach the end of their life).
// */
// void addTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Removes supplied listener from our set of listeners if it is contained
// * therein, else does nothing.
// *
// * @param statusChangeListener listener to receive status update notifications.
// */
// void removeTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Returns a {@link RepairManager} capable of fixing broken Tasks. The
// * returned {@link RepairManager} will use the supplied
// * {@link RepairDecisionProvider} to collect user input needed to determine
// * what actions to take for each failing Task.
// */
// RepairManager getRepairManager(RepairDecisionProvider rdp);
//
// /**
// * Returns an immutable set of all the currently known tasks, passing or not.
// */
// Collection<Task> getAllKnownTasks();
//
// /**
// * A temporary solution allowing the trim widget to display the number
// * of failing items to the user.
// */
// int getFailingItemCount();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IStatusChangeListener.java
// public interface IStatusChangeListener {
//
// void statusChanged(StatusChangedEvent event);
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/MechanicStatus.java
// public enum MechanicStatus {
//
// /* there are no failing tasks */
// PASSED,
//
// /* there are failing tasks */
// FAILED,
//
// /* mechanic service is updating its set of tasks */
// UPDATING,
//
// /* mechanic service is not running */
// STOPPED
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/StatusChangedEvent.java
// public class StatusChangedEvent {
//
// private final MechanicStatus status;
//
// public StatusChangedEvent(MechanicStatus status) {
// this.status = status;
// }
//
// public MechanicStatus getStatus() {
// return status;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/StateSensitiveCache.java
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import com.google.common.base.Preconditions;
import com.google.eclipse.mechanic.IMechanicService;
import com.google.eclipse.mechanic.IStatusChangeListener;
import com.google.eclipse.mechanic.MechanicStatus;
import com.google.eclipse.mechanic.StatusChangedEvent;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* A {@link IUriContentProvider} that clears its cache when the Mechanic starts a
* scanning session.
*/
public final class StateSensitiveCache implements IUriContentProvider {
private final IMechanicService service; | private final IStatusChangeListener statusChangeListener; |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/StateSensitiveCache.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IMechanicService.java
// public interface IMechanicService {
//
// /**
// * Causes the scannning service to start as soon as possible.
// */
// void start();
//
// /**
// * Causes the scanning service to stop scanning.
// */
// void stop();
//
// /**
// * Return true if the mechanic service is not running.
// */
// boolean isStopped();
//
// /**
// * Adds the supplied listener to status change events for the Mechanic (not the
// * Job). UI components can use this facility to get notifications announcing
// * changes in the mechanic service.
// *
// * <p>Callers of this method should note that Mechanic Service will
// * immediately send a notification to the supplied listener when this method
// * is called. Also, callers should remember to unsubscribe listeners when
// * they are disposed (or otherwise reach the end of their life).
// */
// void addTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Removes supplied listener from our set of listeners if it is contained
// * therein, else does nothing.
// *
// * @param statusChangeListener listener to receive status update notifications.
// */
// void removeTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Returns a {@link RepairManager} capable of fixing broken Tasks. The
// * returned {@link RepairManager} will use the supplied
// * {@link RepairDecisionProvider} to collect user input needed to determine
// * what actions to take for each failing Task.
// */
// RepairManager getRepairManager(RepairDecisionProvider rdp);
//
// /**
// * Returns an immutable set of all the currently known tasks, passing or not.
// */
// Collection<Task> getAllKnownTasks();
//
// /**
// * A temporary solution allowing the trim widget to display the number
// * of failing items to the user.
// */
// int getFailingItemCount();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IStatusChangeListener.java
// public interface IStatusChangeListener {
//
// void statusChanged(StatusChangedEvent event);
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/MechanicStatus.java
// public enum MechanicStatus {
//
// /* there are no failing tasks */
// PASSED,
//
// /* there are failing tasks */
// FAILED,
//
// /* mechanic service is updating its set of tasks */
// UPDATING,
//
// /* mechanic service is not running */
// STOPPED
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/StatusChangedEvent.java
// public class StatusChangedEvent {
//
// private final MechanicStatus status;
//
// public StatusChangedEvent(MechanicStatus status) {
// this.status = status;
// }
//
// public MechanicStatus getStatus() {
// return status;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import com.google.common.base.Preconditions;
import com.google.eclipse.mechanic.IMechanicService;
import com.google.eclipse.mechanic.IStatusChangeListener;
import com.google.eclipse.mechanic.MechanicStatus;
import com.google.eclipse.mechanic.StatusChangedEvent; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* A {@link IUriContentProvider} that clears its cache when the Mechanic starts a
* scanning session.
*/
public final class StateSensitiveCache implements IUriContentProvider {
private final IMechanicService service;
private final IStatusChangeListener statusChangeListener;
private final IUriContentProvider delegate;
public StateSensitiveCache(IMechanicService service, IUriContentProvider delegate) {
this.service = Preconditions.checkNotNull(service);
this.delegate = Preconditions.checkNotNull(delegate);
this.statusChangeListener = new IStatusChangeListener() { | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IMechanicService.java
// public interface IMechanicService {
//
// /**
// * Causes the scannning service to start as soon as possible.
// */
// void start();
//
// /**
// * Causes the scanning service to stop scanning.
// */
// void stop();
//
// /**
// * Return true if the mechanic service is not running.
// */
// boolean isStopped();
//
// /**
// * Adds the supplied listener to status change events for the Mechanic (not the
// * Job). UI components can use this facility to get notifications announcing
// * changes in the mechanic service.
// *
// * <p>Callers of this method should note that Mechanic Service will
// * immediately send a notification to the supplied listener when this method
// * is called. Also, callers should remember to unsubscribe listeners when
// * they are disposed (or otherwise reach the end of their life).
// */
// void addTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Removes supplied listener from our set of listeners if it is contained
// * therein, else does nothing.
// *
// * @param statusChangeListener listener to receive status update notifications.
// */
// void removeTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Returns a {@link RepairManager} capable of fixing broken Tasks. The
// * returned {@link RepairManager} will use the supplied
// * {@link RepairDecisionProvider} to collect user input needed to determine
// * what actions to take for each failing Task.
// */
// RepairManager getRepairManager(RepairDecisionProvider rdp);
//
// /**
// * Returns an immutable set of all the currently known tasks, passing or not.
// */
// Collection<Task> getAllKnownTasks();
//
// /**
// * A temporary solution allowing the trim widget to display the number
// * of failing items to the user.
// */
// int getFailingItemCount();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IStatusChangeListener.java
// public interface IStatusChangeListener {
//
// void statusChanged(StatusChangedEvent event);
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/MechanicStatus.java
// public enum MechanicStatus {
//
// /* there are no failing tasks */
// PASSED,
//
// /* there are failing tasks */
// FAILED,
//
// /* mechanic service is updating its set of tasks */
// UPDATING,
//
// /* mechanic service is not running */
// STOPPED
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/StatusChangedEvent.java
// public class StatusChangedEvent {
//
// private final MechanicStatus status;
//
// public StatusChangedEvent(MechanicStatus status) {
// this.status = status;
// }
//
// public MechanicStatus getStatus() {
// return status;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/StateSensitiveCache.java
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import com.google.common.base.Preconditions;
import com.google.eclipse.mechanic.IMechanicService;
import com.google.eclipse.mechanic.IStatusChangeListener;
import com.google.eclipse.mechanic.MechanicStatus;
import com.google.eclipse.mechanic.StatusChangedEvent;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* A {@link IUriContentProvider} that clears its cache when the Mechanic starts a
* scanning session.
*/
public final class StateSensitiveCache implements IUriContentProvider {
private final IMechanicService service;
private final IStatusChangeListener statusChangeListener;
private final IUriContentProvider delegate;
public StateSensitiveCache(IMechanicService service, IUriContentProvider delegate) {
this.service = Preconditions.checkNotNull(service);
this.delegate = Preconditions.checkNotNull(delegate);
this.statusChangeListener = new IStatusChangeListener() { | public void statusChanged(StatusChangedEvent event) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/StateSensitiveCache.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IMechanicService.java
// public interface IMechanicService {
//
// /**
// * Causes the scannning service to start as soon as possible.
// */
// void start();
//
// /**
// * Causes the scanning service to stop scanning.
// */
// void stop();
//
// /**
// * Return true if the mechanic service is not running.
// */
// boolean isStopped();
//
// /**
// * Adds the supplied listener to status change events for the Mechanic (not the
// * Job). UI components can use this facility to get notifications announcing
// * changes in the mechanic service.
// *
// * <p>Callers of this method should note that Mechanic Service will
// * immediately send a notification to the supplied listener when this method
// * is called. Also, callers should remember to unsubscribe listeners when
// * they are disposed (or otherwise reach the end of their life).
// */
// void addTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Removes supplied listener from our set of listeners if it is contained
// * therein, else does nothing.
// *
// * @param statusChangeListener listener to receive status update notifications.
// */
// void removeTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Returns a {@link RepairManager} capable of fixing broken Tasks. The
// * returned {@link RepairManager} will use the supplied
// * {@link RepairDecisionProvider} to collect user input needed to determine
// * what actions to take for each failing Task.
// */
// RepairManager getRepairManager(RepairDecisionProvider rdp);
//
// /**
// * Returns an immutable set of all the currently known tasks, passing or not.
// */
// Collection<Task> getAllKnownTasks();
//
// /**
// * A temporary solution allowing the trim widget to display the number
// * of failing items to the user.
// */
// int getFailingItemCount();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IStatusChangeListener.java
// public interface IStatusChangeListener {
//
// void statusChanged(StatusChangedEvent event);
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/MechanicStatus.java
// public enum MechanicStatus {
//
// /* there are no failing tasks */
// PASSED,
//
// /* there are failing tasks */
// FAILED,
//
// /* mechanic service is updating its set of tasks */
// UPDATING,
//
// /* mechanic service is not running */
// STOPPED
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/StatusChangedEvent.java
// public class StatusChangedEvent {
//
// private final MechanicStatus status;
//
// public StatusChangedEvent(MechanicStatus status) {
// this.status = status;
// }
//
// public MechanicStatus getStatus() {
// return status;
// }
// }
| import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import com.google.common.base.Preconditions;
import com.google.eclipse.mechanic.IMechanicService;
import com.google.eclipse.mechanic.IStatusChangeListener;
import com.google.eclipse.mechanic.MechanicStatus;
import com.google.eclipse.mechanic.StatusChangedEvent; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* A {@link IUriContentProvider} that clears its cache when the Mechanic starts a
* scanning session.
*/
public final class StateSensitiveCache implements IUriContentProvider {
private final IMechanicService service;
private final IStatusChangeListener statusChangeListener;
private final IUriContentProvider delegate;
public StateSensitiveCache(IMechanicService service, IUriContentProvider delegate) {
this.service = Preconditions.checkNotNull(service);
this.delegate = Preconditions.checkNotNull(delegate);
this.statusChangeListener = new IStatusChangeListener() {
public void statusChanged(StatusChangedEvent event) { | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IMechanicService.java
// public interface IMechanicService {
//
// /**
// * Causes the scannning service to start as soon as possible.
// */
// void start();
//
// /**
// * Causes the scanning service to stop scanning.
// */
// void stop();
//
// /**
// * Return true if the mechanic service is not running.
// */
// boolean isStopped();
//
// /**
// * Adds the supplied listener to status change events for the Mechanic (not the
// * Job). UI components can use this facility to get notifications announcing
// * changes in the mechanic service.
// *
// * <p>Callers of this method should note that Mechanic Service will
// * immediately send a notification to the supplied listener when this method
// * is called. Also, callers should remember to unsubscribe listeners when
// * they are disposed (or otherwise reach the end of their life).
// */
// void addTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Removes supplied listener from our set of listeners if it is contained
// * therein, else does nothing.
// *
// * @param statusChangeListener listener to receive status update notifications.
// */
// void removeTaskStatusChangeListener(IStatusChangeListener statusChangeListener);
//
// /**
// * Returns a {@link RepairManager} capable of fixing broken Tasks. The
// * returned {@link RepairManager} will use the supplied
// * {@link RepairDecisionProvider} to collect user input needed to determine
// * what actions to take for each failing Task.
// */
// RepairManager getRepairManager(RepairDecisionProvider rdp);
//
// /**
// * Returns an immutable set of all the currently known tasks, passing or not.
// */
// Collection<Task> getAllKnownTasks();
//
// /**
// * A temporary solution allowing the trim widget to display the number
// * of failing items to the user.
// */
// int getFailingItemCount();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IStatusChangeListener.java
// public interface IStatusChangeListener {
//
// void statusChanged(StatusChangedEvent event);
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/MechanicStatus.java
// public enum MechanicStatus {
//
// /* there are no failing tasks */
// PASSED,
//
// /* there are failing tasks */
// FAILED,
//
// /* mechanic service is updating its set of tasks */
// UPDATING,
//
// /* mechanic service is not running */
// STOPPED
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/StatusChangedEvent.java
// public class StatusChangedEvent {
//
// private final MechanicStatus status;
//
// public StatusChangedEvent(MechanicStatus status) {
// this.status = status;
// }
//
// public MechanicStatus getStatus() {
// return status;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/StateSensitiveCache.java
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import com.google.common.base.Preconditions;
import com.google.eclipse.mechanic.IMechanicService;
import com.google.eclipse.mechanic.IStatusChangeListener;
import com.google.eclipse.mechanic.MechanicStatus;
import com.google.eclipse.mechanic.StatusChangedEvent;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* A {@link IUriContentProvider} that clears its cache when the Mechanic starts a
* scanning session.
*/
public final class StateSensitiveCache implements IUriContentProvider {
private final IMechanicService service;
private final IStatusChangeListener statusChangeListener;
private final IUriContentProvider delegate;
public StateSensitiveCache(IMechanicService service, IUriContentProvider delegate) {
this.service = Preconditions.checkNotNull(service);
this.delegate = Preconditions.checkNotNull(delegate);
this.statusChangeListener = new IStatusChangeListener() {
public void statusChanged(StatusChangedEvent event) { | if (event.getStatus() == MechanicStatus.UPDATING) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/IMechanicPreferences.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
| import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.Task;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import java.util.List;
import java.util.Set; | /*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.core;
/**
* Interface for mechanic preferences.
*/
@SuppressWarnings("deprecation") // Uses the old-style API.
public interface IMechanicPreferences {
public static final String DIRS_PREF = "mechanicSourceDirectories";
public static final String BLOCKED_PREF = "blockedTaskIds";
public static final String SLEEPAGE_PREF = "sleepSeconds";
public static final String HELP_URL_PREF = "helpUrl";
public static final String SHOW_POPUP_PREF = "showPopup";
// /**
// * Preference string to enable web content caching.
// *
// * <p>Stores a boolean.
// */
// public static final String CACHE_URI_CONTENT_PREF = "cacheUriContent";
// /**
// * Preference string that defines the maximum lifetime of web cache entries, in hours.
// *
// * <p>Stores an integer.
// */
// public static final String CACHE_URI_AGE_HOURS_PREF = "cacheUriAgeHours";
/**
* Minimum duration between tasks, in seconds.
*/
public static final int MINIMUM_SLEEP_SECONDS = 10;
void addListener(IPropertyChangeListener listener);
void removeListener(IPropertyChangeListener listener);
/**
* Return a list of task sources where tasks may be found.
*
* @return list of task sources where tasks may be found.
*/ | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/IMechanicPreferences.java
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.Task;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import java.util.List;
import java.util.Set;
/*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.core;
/**
* Interface for mechanic preferences.
*/
@SuppressWarnings("deprecation") // Uses the old-style API.
public interface IMechanicPreferences {
public static final String DIRS_PREF = "mechanicSourceDirectories";
public static final String BLOCKED_PREF = "blockedTaskIds";
public static final String SLEEPAGE_PREF = "sleepSeconds";
public static final String HELP_URL_PREF = "helpUrl";
public static final String SHOW_POPUP_PREF = "showPopup";
// /**
// * Preference string to enable web content caching.
// *
// * <p>Stores a boolean.
// */
// public static final String CACHE_URI_CONTENT_PREF = "cacheUriContent";
// /**
// * Preference string that defines the maximum lifetime of web cache entries, in hours.
// *
// * <p>Stores an integer.
// */
// public static final String CACHE_URI_AGE_HOURS_PREF = "cacheUriAgeHours";
/**
* Minimum duration between tasks, in seconds.
*/
public static final int MINIMUM_SLEEP_SECONDS = 10;
void addListener(IPropertyChangeListener listener);
void removeListener(IPropertyChangeListener listener);
/**
* Return a list of task sources where tasks may be found.
*
* @return list of task sources where tasks may be found.
*/ | List<IResourceTaskProvider> getTaskProviders(); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/IMechanicPreferences.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
| import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.Task;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import java.util.List;
import java.util.Set; | /*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.core;
/**
* Interface for mechanic preferences.
*/
@SuppressWarnings("deprecation") // Uses the old-style API.
public interface IMechanicPreferences {
public static final String DIRS_PREF = "mechanicSourceDirectories";
public static final String BLOCKED_PREF = "blockedTaskIds";
public static final String SLEEPAGE_PREF = "sleepSeconds";
public static final String HELP_URL_PREF = "helpUrl";
public static final String SHOW_POPUP_PREF = "showPopup";
// /**
// * Preference string to enable web content caching.
// *
// * <p>Stores a boolean.
// */
// public static final String CACHE_URI_CONTENT_PREF = "cacheUriContent";
// /**
// * Preference string that defines the maximum lifetime of web cache entries, in hours.
// *
// * <p>Stores an integer.
// */
// public static final String CACHE_URI_AGE_HOURS_PREF = "cacheUriAgeHours";
/**
* Minimum duration between tasks, in seconds.
*/
public static final int MINIMUM_SLEEP_SECONDS = 10;
void addListener(IPropertyChangeListener listener);
void removeListener(IPropertyChangeListener listener);
/**
* Return a list of task sources where tasks may be found.
*
* @return list of task sources where tasks may be found.
*/
List<IResourceTaskProvider> getTaskProviders();
/**
* Returns the number of seconds the mechanic should sleep between passes.
*/
int getThreadSleepSeconds();
/**
* Ensures the supplied sleep duration falls in an acceptable range.
*/
int cleanSleepSeconds(int seconds);
/**
* Returns a mutable set of blocked Task ids.
*/
Set<String> getBlockedTaskIds();
/**
* Saves the supplied Task id set in the preferences system.
*/
void setBlockedTaskIds(Set<String> ids);
/**
* Adds the supplied Task's id to the set of blocked Tasks.
*/ | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/IMechanicPreferences.java
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.Task;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Preferences.IPropertyChangeListener;
import java.util.List;
import java.util.Set;
/*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.core;
/**
* Interface for mechanic preferences.
*/
@SuppressWarnings("deprecation") // Uses the old-style API.
public interface IMechanicPreferences {
public static final String DIRS_PREF = "mechanicSourceDirectories";
public static final String BLOCKED_PREF = "blockedTaskIds";
public static final String SLEEPAGE_PREF = "sleepSeconds";
public static final String HELP_URL_PREF = "helpUrl";
public static final String SHOW_POPUP_PREF = "showPopup";
// /**
// * Preference string to enable web content caching.
// *
// * <p>Stores a boolean.
// */
// public static final String CACHE_URI_CONTENT_PREF = "cacheUriContent";
// /**
// * Preference string that defines the maximum lifetime of web cache entries, in hours.
// *
// * <p>Stores an integer.
// */
// public static final String CACHE_URI_AGE_HOURS_PREF = "cacheUriAgeHours";
/**
* Minimum duration between tasks, in seconds.
*/
public static final int MINIMUM_SLEEP_SECONDS = 10;
void addListener(IPropertyChangeListener listener);
void removeListener(IPropertyChangeListener listener);
/**
* Return a list of task sources where tasks may be found.
*
* @return list of task sources where tasks may be found.
*/
List<IResourceTaskProvider> getTaskProviders();
/**
* Returns the number of seconds the mechanic should sleep between passes.
*/
int getThreadSleepSeconds();
/**
* Ensures the supplied sleep duration falls in an acceptable range.
*/
int cleanSleepSeconds(int seconds);
/**
* Returns a mutable set of blocked Task ids.
*/
Set<String> getBlockedTaskIds();
/**
* Saves the supplied Task id set in the preferences system.
*/
void setBlockedTaskIds(Set<String> ids);
/**
* Adds the supplied Task's id to the set of blocked Tasks.
*/ | void blockItem(Task item); |
alfsch/workspacemechanic | parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/core/MechanicPreferencesTest.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Evaluator.java
// public interface Evaluator {
//
// /**
// * @return true if the environment adheres to this test.
// */
// public boolean evaluate();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairAction.java
// public interface RepairAction extends Runnable {
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/MechanicPreferences.java
// @SuppressWarnings("deprecation") // Uses the old-style API.
// public class MechanicPreferences implements IMechanicPreferences {
//
// public void addListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.addListener(listener);
// }
//
// public void removeListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.removeListener(listener);
// }
//
// public List<IResourceTaskProvider> getTaskProviders() {
// return OldMechanicPreferences.getTaskProviders();
// }
//
// public int getThreadSleepSeconds() {
// return OldMechanicPreferences.getThreadSleepSeconds();
// }
//
// public int cleanSleepSeconds(int seconds) {
// return OldMechanicPreferences.cleanSleepSeconds(seconds);
// }
//
// public Set<String> getBlockedTaskIds() {
// return OldMechanicPreferences.getBlockedTaskIds();
// }
//
// public void setBlockedTaskIds(Set<String> ids) {
// OldMechanicPreferences.setBlockedTaskIds(ids);
// }
//
// public void blockItem(Task item) {
// OldMechanicPreferences.blockItem(item);
// }
//
// public String getHelpUrl() {
// return OldMechanicPreferences.getHelpUrl();
// }
//
// public boolean contains(String key) {
// return OldMechanicPreferences.contains(key);
// }
//
// public int getInt(String key) {
// return OldMechanicPreferences.getInt(key);
// }
//
// public long getLong(String key) {
// return OldMechanicPreferences.getLong(key);
// }
//
// public void setLong(String key, long value) {
// OldMechanicPreferences.setLong(key, value);
// }
//
// public String getString(String key) {
// return OldMechanicPreferences.getString(key);
// }
//
// public void setString(String key, String value) {
// OldMechanicPreferences.setString(key, value);
// }
//
// public boolean isShowPopup() {
// return OldMechanicPreferences.isShowPopup();
// }
//
// public void doNotShowPopup() {
// OldMechanicPreferences.doNotShowPopup();
// }
//
// public void showPopup() {
// OldMechanicPreferences.showPopup();
// }
//
// public IStatus validatePreferencesFile(IPath path) {
// return OldMechanicPreferences.validatePreferencesFile(path);
// }
// }
| import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.Evaluator;
import com.google.eclipse.mechanic.RepairAction;
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.MechanicPreferences;
import com.google.eclipse.mechanic.tests.internal.RunAsPluginTest; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.core;
/**
* Tests for {@link MechanicPreferences}
*/
@RunAsPluginTest
public class MechanicPreferencesTest extends TestCase {
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Evaluator.java
// public interface Evaluator {
//
// /**
// * @return true if the environment adheres to this test.
// */
// public boolean evaluate();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairAction.java
// public interface RepairAction extends Runnable {
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/MechanicPreferences.java
// @SuppressWarnings("deprecation") // Uses the old-style API.
// public class MechanicPreferences implements IMechanicPreferences {
//
// public void addListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.addListener(listener);
// }
//
// public void removeListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.removeListener(listener);
// }
//
// public List<IResourceTaskProvider> getTaskProviders() {
// return OldMechanicPreferences.getTaskProviders();
// }
//
// public int getThreadSleepSeconds() {
// return OldMechanicPreferences.getThreadSleepSeconds();
// }
//
// public int cleanSleepSeconds(int seconds) {
// return OldMechanicPreferences.cleanSleepSeconds(seconds);
// }
//
// public Set<String> getBlockedTaskIds() {
// return OldMechanicPreferences.getBlockedTaskIds();
// }
//
// public void setBlockedTaskIds(Set<String> ids) {
// OldMechanicPreferences.setBlockedTaskIds(ids);
// }
//
// public void blockItem(Task item) {
// OldMechanicPreferences.blockItem(item);
// }
//
// public String getHelpUrl() {
// return OldMechanicPreferences.getHelpUrl();
// }
//
// public boolean contains(String key) {
// return OldMechanicPreferences.contains(key);
// }
//
// public int getInt(String key) {
// return OldMechanicPreferences.getInt(key);
// }
//
// public long getLong(String key) {
// return OldMechanicPreferences.getLong(key);
// }
//
// public void setLong(String key, long value) {
// OldMechanicPreferences.setLong(key, value);
// }
//
// public String getString(String key) {
// return OldMechanicPreferences.getString(key);
// }
//
// public void setString(String key, String value) {
// OldMechanicPreferences.setString(key, value);
// }
//
// public boolean isShowPopup() {
// return OldMechanicPreferences.isShowPopup();
// }
//
// public void doNotShowPopup() {
// OldMechanicPreferences.doNotShowPopup();
// }
//
// public void showPopup() {
// OldMechanicPreferences.showPopup();
// }
//
// public IStatus validatePreferencesFile(IPath path) {
// return OldMechanicPreferences.validatePreferencesFile(path);
// }
// }
// Path: parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/core/MechanicPreferencesTest.java
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.Evaluator;
import com.google.eclipse.mechanic.RepairAction;
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.MechanicPreferences;
import com.google.eclipse.mechanic.tests.internal.RunAsPluginTest;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.core;
/**
* Tests for {@link MechanicPreferences}
*/
@RunAsPluginTest
public class MechanicPreferencesTest extends TestCase {
| private final IMechanicPreferences mechanicPreferences = new MechanicPreferences(); |
alfsch/workspacemechanic | parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/core/MechanicPreferencesTest.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Evaluator.java
// public interface Evaluator {
//
// /**
// * @return true if the environment adheres to this test.
// */
// public boolean evaluate();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairAction.java
// public interface RepairAction extends Runnable {
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/MechanicPreferences.java
// @SuppressWarnings("deprecation") // Uses the old-style API.
// public class MechanicPreferences implements IMechanicPreferences {
//
// public void addListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.addListener(listener);
// }
//
// public void removeListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.removeListener(listener);
// }
//
// public List<IResourceTaskProvider> getTaskProviders() {
// return OldMechanicPreferences.getTaskProviders();
// }
//
// public int getThreadSleepSeconds() {
// return OldMechanicPreferences.getThreadSleepSeconds();
// }
//
// public int cleanSleepSeconds(int seconds) {
// return OldMechanicPreferences.cleanSleepSeconds(seconds);
// }
//
// public Set<String> getBlockedTaskIds() {
// return OldMechanicPreferences.getBlockedTaskIds();
// }
//
// public void setBlockedTaskIds(Set<String> ids) {
// OldMechanicPreferences.setBlockedTaskIds(ids);
// }
//
// public void blockItem(Task item) {
// OldMechanicPreferences.blockItem(item);
// }
//
// public String getHelpUrl() {
// return OldMechanicPreferences.getHelpUrl();
// }
//
// public boolean contains(String key) {
// return OldMechanicPreferences.contains(key);
// }
//
// public int getInt(String key) {
// return OldMechanicPreferences.getInt(key);
// }
//
// public long getLong(String key) {
// return OldMechanicPreferences.getLong(key);
// }
//
// public void setLong(String key, long value) {
// OldMechanicPreferences.setLong(key, value);
// }
//
// public String getString(String key) {
// return OldMechanicPreferences.getString(key);
// }
//
// public void setString(String key, String value) {
// OldMechanicPreferences.setString(key, value);
// }
//
// public boolean isShowPopup() {
// return OldMechanicPreferences.isShowPopup();
// }
//
// public void doNotShowPopup() {
// OldMechanicPreferences.doNotShowPopup();
// }
//
// public void showPopup() {
// OldMechanicPreferences.showPopup();
// }
//
// public IStatus validatePreferencesFile(IPath path) {
// return OldMechanicPreferences.validatePreferencesFile(path);
// }
// }
| import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.Evaluator;
import com.google.eclipse.mechanic.RepairAction;
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.MechanicPreferences;
import com.google.eclipse.mechanic.tests.internal.RunAsPluginTest; | assertEquals(0, mechanicPreferences.getLong(pref));
mechanicPreferences.setLong(pref, 1);
assertEquals(1, mechanicPreferences.getLong(pref));
mechanicPreferences.setLong(pref, Long.MAX_VALUE);
assertEquals(Long.MAX_VALUE, mechanicPreferences.getLong(pref));
}
public void testGetTaskDirectories() {
setToDefault(IMechanicPreferences.DIRS_PREF);
String taskDirs = mechanicPreferences.getString(IMechanicPreferences.DIRS_PREF);
assertEquals("${user_homedir}/.eclipse/mechanic:${mechanic_configuration_path}/mechanic", taskDirs);
}
public void testContains() {
String pref = "XYZPDQ";
assertFalse(mechanicPreferences.contains(pref));
mechanicPreferences.setLong(pref, 1L);
assertTrue(mechanicPreferences.contains(pref));
setToDefault(pref);
assertFalse(mechanicPreferences.contains(pref));
}
//public static int getThreadSleepSeconds() {
//public static String doVariableSubstitution(String input) {
//public static IStatus validatePreferencesFile(IPath path) {
/**
* Create a mock task with the given id.
*/ | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Evaluator.java
// public interface Evaluator {
//
// /**
// * @return true if the environment adheres to this test.
// */
// public boolean evaluate();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairAction.java
// public interface RepairAction extends Runnable {
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/MechanicPreferences.java
// @SuppressWarnings("deprecation") // Uses the old-style API.
// public class MechanicPreferences implements IMechanicPreferences {
//
// public void addListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.addListener(listener);
// }
//
// public void removeListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.removeListener(listener);
// }
//
// public List<IResourceTaskProvider> getTaskProviders() {
// return OldMechanicPreferences.getTaskProviders();
// }
//
// public int getThreadSleepSeconds() {
// return OldMechanicPreferences.getThreadSleepSeconds();
// }
//
// public int cleanSleepSeconds(int seconds) {
// return OldMechanicPreferences.cleanSleepSeconds(seconds);
// }
//
// public Set<String> getBlockedTaskIds() {
// return OldMechanicPreferences.getBlockedTaskIds();
// }
//
// public void setBlockedTaskIds(Set<String> ids) {
// OldMechanicPreferences.setBlockedTaskIds(ids);
// }
//
// public void blockItem(Task item) {
// OldMechanicPreferences.blockItem(item);
// }
//
// public String getHelpUrl() {
// return OldMechanicPreferences.getHelpUrl();
// }
//
// public boolean contains(String key) {
// return OldMechanicPreferences.contains(key);
// }
//
// public int getInt(String key) {
// return OldMechanicPreferences.getInt(key);
// }
//
// public long getLong(String key) {
// return OldMechanicPreferences.getLong(key);
// }
//
// public void setLong(String key, long value) {
// OldMechanicPreferences.setLong(key, value);
// }
//
// public String getString(String key) {
// return OldMechanicPreferences.getString(key);
// }
//
// public void setString(String key, String value) {
// OldMechanicPreferences.setString(key, value);
// }
//
// public boolean isShowPopup() {
// return OldMechanicPreferences.isShowPopup();
// }
//
// public void doNotShowPopup() {
// OldMechanicPreferences.doNotShowPopup();
// }
//
// public void showPopup() {
// OldMechanicPreferences.showPopup();
// }
//
// public IStatus validatePreferencesFile(IPath path) {
// return OldMechanicPreferences.validatePreferencesFile(path);
// }
// }
// Path: parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/core/MechanicPreferencesTest.java
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.Evaluator;
import com.google.eclipse.mechanic.RepairAction;
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.MechanicPreferences;
import com.google.eclipse.mechanic.tests.internal.RunAsPluginTest;
assertEquals(0, mechanicPreferences.getLong(pref));
mechanicPreferences.setLong(pref, 1);
assertEquals(1, mechanicPreferences.getLong(pref));
mechanicPreferences.setLong(pref, Long.MAX_VALUE);
assertEquals(Long.MAX_VALUE, mechanicPreferences.getLong(pref));
}
public void testGetTaskDirectories() {
setToDefault(IMechanicPreferences.DIRS_PREF);
String taskDirs = mechanicPreferences.getString(IMechanicPreferences.DIRS_PREF);
assertEquals("${user_homedir}/.eclipse/mechanic:${mechanic_configuration_path}/mechanic", taskDirs);
}
public void testContains() {
String pref = "XYZPDQ";
assertFalse(mechanicPreferences.contains(pref));
mechanicPreferences.setLong(pref, 1L);
assertTrue(mechanicPreferences.contains(pref));
setToDefault(pref);
assertFalse(mechanicPreferences.contains(pref));
}
//public static int getThreadSleepSeconds() {
//public static String doVariableSubstitution(String input) {
//public static IStatus validatePreferencesFile(IPath path) {
/**
* Create a mock task with the given id.
*/ | private Task createTask(final String id) { |
alfsch/workspacemechanic | parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/core/MechanicPreferencesTest.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Evaluator.java
// public interface Evaluator {
//
// /**
// * @return true if the environment adheres to this test.
// */
// public boolean evaluate();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairAction.java
// public interface RepairAction extends Runnable {
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/MechanicPreferences.java
// @SuppressWarnings("deprecation") // Uses the old-style API.
// public class MechanicPreferences implements IMechanicPreferences {
//
// public void addListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.addListener(listener);
// }
//
// public void removeListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.removeListener(listener);
// }
//
// public List<IResourceTaskProvider> getTaskProviders() {
// return OldMechanicPreferences.getTaskProviders();
// }
//
// public int getThreadSleepSeconds() {
// return OldMechanicPreferences.getThreadSleepSeconds();
// }
//
// public int cleanSleepSeconds(int seconds) {
// return OldMechanicPreferences.cleanSleepSeconds(seconds);
// }
//
// public Set<String> getBlockedTaskIds() {
// return OldMechanicPreferences.getBlockedTaskIds();
// }
//
// public void setBlockedTaskIds(Set<String> ids) {
// OldMechanicPreferences.setBlockedTaskIds(ids);
// }
//
// public void blockItem(Task item) {
// OldMechanicPreferences.blockItem(item);
// }
//
// public String getHelpUrl() {
// return OldMechanicPreferences.getHelpUrl();
// }
//
// public boolean contains(String key) {
// return OldMechanicPreferences.contains(key);
// }
//
// public int getInt(String key) {
// return OldMechanicPreferences.getInt(key);
// }
//
// public long getLong(String key) {
// return OldMechanicPreferences.getLong(key);
// }
//
// public void setLong(String key, long value) {
// OldMechanicPreferences.setLong(key, value);
// }
//
// public String getString(String key) {
// return OldMechanicPreferences.getString(key);
// }
//
// public void setString(String key, String value) {
// OldMechanicPreferences.setString(key, value);
// }
//
// public boolean isShowPopup() {
// return OldMechanicPreferences.isShowPopup();
// }
//
// public void doNotShowPopup() {
// OldMechanicPreferences.doNotShowPopup();
// }
//
// public void showPopup() {
// OldMechanicPreferences.showPopup();
// }
//
// public IStatus validatePreferencesFile(IPath path) {
// return OldMechanicPreferences.validatePreferencesFile(path);
// }
// }
| import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.Evaluator;
import com.google.eclipse.mechanic.RepairAction;
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.MechanicPreferences;
import com.google.eclipse.mechanic.tests.internal.RunAsPluginTest; | public void testContains() {
String pref = "XYZPDQ";
assertFalse(mechanicPreferences.contains(pref));
mechanicPreferences.setLong(pref, 1L);
assertTrue(mechanicPreferences.contains(pref));
setToDefault(pref);
assertFalse(mechanicPreferences.contains(pref));
}
//public static int getThreadSleepSeconds() {
//public static String doVariableSubstitution(String input) {
//public static IStatus validatePreferencesFile(IPath path) {
/**
* Create a mock task with the given id.
*/
private Task createTask(final String id) {
return new Task() {
public String getId() {
return id;
}
public String getTitle() {
throw new AssertionError();
}
public String getDescription() {
throw new AssertionError();
}
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Evaluator.java
// public interface Evaluator {
//
// /**
// * @return true if the environment adheres to this test.
// */
// public boolean evaluate();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairAction.java
// public interface RepairAction extends Runnable {
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/MechanicPreferences.java
// @SuppressWarnings("deprecation") // Uses the old-style API.
// public class MechanicPreferences implements IMechanicPreferences {
//
// public void addListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.addListener(listener);
// }
//
// public void removeListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.removeListener(listener);
// }
//
// public List<IResourceTaskProvider> getTaskProviders() {
// return OldMechanicPreferences.getTaskProviders();
// }
//
// public int getThreadSleepSeconds() {
// return OldMechanicPreferences.getThreadSleepSeconds();
// }
//
// public int cleanSleepSeconds(int seconds) {
// return OldMechanicPreferences.cleanSleepSeconds(seconds);
// }
//
// public Set<String> getBlockedTaskIds() {
// return OldMechanicPreferences.getBlockedTaskIds();
// }
//
// public void setBlockedTaskIds(Set<String> ids) {
// OldMechanicPreferences.setBlockedTaskIds(ids);
// }
//
// public void blockItem(Task item) {
// OldMechanicPreferences.blockItem(item);
// }
//
// public String getHelpUrl() {
// return OldMechanicPreferences.getHelpUrl();
// }
//
// public boolean contains(String key) {
// return OldMechanicPreferences.contains(key);
// }
//
// public int getInt(String key) {
// return OldMechanicPreferences.getInt(key);
// }
//
// public long getLong(String key) {
// return OldMechanicPreferences.getLong(key);
// }
//
// public void setLong(String key, long value) {
// OldMechanicPreferences.setLong(key, value);
// }
//
// public String getString(String key) {
// return OldMechanicPreferences.getString(key);
// }
//
// public void setString(String key, String value) {
// OldMechanicPreferences.setString(key, value);
// }
//
// public boolean isShowPopup() {
// return OldMechanicPreferences.isShowPopup();
// }
//
// public void doNotShowPopup() {
// OldMechanicPreferences.doNotShowPopup();
// }
//
// public void showPopup() {
// OldMechanicPreferences.showPopup();
// }
//
// public IStatus validatePreferencesFile(IPath path) {
// return OldMechanicPreferences.validatePreferencesFile(path);
// }
// }
// Path: parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/core/MechanicPreferencesTest.java
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.Evaluator;
import com.google.eclipse.mechanic.RepairAction;
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.MechanicPreferences;
import com.google.eclipse.mechanic.tests.internal.RunAsPluginTest;
public void testContains() {
String pref = "XYZPDQ";
assertFalse(mechanicPreferences.contains(pref));
mechanicPreferences.setLong(pref, 1L);
assertTrue(mechanicPreferences.contains(pref));
setToDefault(pref);
assertFalse(mechanicPreferences.contains(pref));
}
//public static int getThreadSleepSeconds() {
//public static String doVariableSubstitution(String input) {
//public static IStatus validatePreferencesFile(IPath path) {
/**
* Create a mock task with the given id.
*/
private Task createTask(final String id) {
return new Task() {
public String getId() {
return id;
}
public String getTitle() {
throw new AssertionError();
}
public String getDescription() {
throw new AssertionError();
}
| public Evaluator getEvaluator() { |
alfsch/workspacemechanic | parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/core/MechanicPreferencesTest.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Evaluator.java
// public interface Evaluator {
//
// /**
// * @return true if the environment adheres to this test.
// */
// public boolean evaluate();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairAction.java
// public interface RepairAction extends Runnable {
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/MechanicPreferences.java
// @SuppressWarnings("deprecation") // Uses the old-style API.
// public class MechanicPreferences implements IMechanicPreferences {
//
// public void addListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.addListener(listener);
// }
//
// public void removeListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.removeListener(listener);
// }
//
// public List<IResourceTaskProvider> getTaskProviders() {
// return OldMechanicPreferences.getTaskProviders();
// }
//
// public int getThreadSleepSeconds() {
// return OldMechanicPreferences.getThreadSleepSeconds();
// }
//
// public int cleanSleepSeconds(int seconds) {
// return OldMechanicPreferences.cleanSleepSeconds(seconds);
// }
//
// public Set<String> getBlockedTaskIds() {
// return OldMechanicPreferences.getBlockedTaskIds();
// }
//
// public void setBlockedTaskIds(Set<String> ids) {
// OldMechanicPreferences.setBlockedTaskIds(ids);
// }
//
// public void blockItem(Task item) {
// OldMechanicPreferences.blockItem(item);
// }
//
// public String getHelpUrl() {
// return OldMechanicPreferences.getHelpUrl();
// }
//
// public boolean contains(String key) {
// return OldMechanicPreferences.contains(key);
// }
//
// public int getInt(String key) {
// return OldMechanicPreferences.getInt(key);
// }
//
// public long getLong(String key) {
// return OldMechanicPreferences.getLong(key);
// }
//
// public void setLong(String key, long value) {
// OldMechanicPreferences.setLong(key, value);
// }
//
// public String getString(String key) {
// return OldMechanicPreferences.getString(key);
// }
//
// public void setString(String key, String value) {
// OldMechanicPreferences.setString(key, value);
// }
//
// public boolean isShowPopup() {
// return OldMechanicPreferences.isShowPopup();
// }
//
// public void doNotShowPopup() {
// OldMechanicPreferences.doNotShowPopup();
// }
//
// public void showPopup() {
// OldMechanicPreferences.showPopup();
// }
//
// public IStatus validatePreferencesFile(IPath path) {
// return OldMechanicPreferences.validatePreferencesFile(path);
// }
// }
| import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.Evaluator;
import com.google.eclipse.mechanic.RepairAction;
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.MechanicPreferences;
import com.google.eclipse.mechanic.tests.internal.RunAsPluginTest; | assertTrue(mechanicPreferences.contains(pref));
setToDefault(pref);
assertFalse(mechanicPreferences.contains(pref));
}
//public static int getThreadSleepSeconds() {
//public static String doVariableSubstitution(String input) {
//public static IStatus validatePreferencesFile(IPath path) {
/**
* Create a mock task with the given id.
*/
private Task createTask(final String id) {
return new Task() {
public String getId() {
return id;
}
public String getTitle() {
throw new AssertionError();
}
public String getDescription() {
throw new AssertionError();
}
public Evaluator getEvaluator() {
throw new AssertionError();
}
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Evaluator.java
// public interface Evaluator {
//
// /**
// * @return true if the environment adheres to this test.
// */
// public boolean evaluate();
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairAction.java
// public interface RepairAction extends Runnable {
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/MechanicPreferences.java
// @SuppressWarnings("deprecation") // Uses the old-style API.
// public class MechanicPreferences implements IMechanicPreferences {
//
// public void addListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.addListener(listener);
// }
//
// public void removeListener(IPropertyChangeListener listener) {
// OldMechanicPreferences.removeListener(listener);
// }
//
// public List<IResourceTaskProvider> getTaskProviders() {
// return OldMechanicPreferences.getTaskProviders();
// }
//
// public int getThreadSleepSeconds() {
// return OldMechanicPreferences.getThreadSleepSeconds();
// }
//
// public int cleanSleepSeconds(int seconds) {
// return OldMechanicPreferences.cleanSleepSeconds(seconds);
// }
//
// public Set<String> getBlockedTaskIds() {
// return OldMechanicPreferences.getBlockedTaskIds();
// }
//
// public void setBlockedTaskIds(Set<String> ids) {
// OldMechanicPreferences.setBlockedTaskIds(ids);
// }
//
// public void blockItem(Task item) {
// OldMechanicPreferences.blockItem(item);
// }
//
// public String getHelpUrl() {
// return OldMechanicPreferences.getHelpUrl();
// }
//
// public boolean contains(String key) {
// return OldMechanicPreferences.contains(key);
// }
//
// public int getInt(String key) {
// return OldMechanicPreferences.getInt(key);
// }
//
// public long getLong(String key) {
// return OldMechanicPreferences.getLong(key);
// }
//
// public void setLong(String key, long value) {
// OldMechanicPreferences.setLong(key, value);
// }
//
// public String getString(String key) {
// return OldMechanicPreferences.getString(key);
// }
//
// public void setString(String key, String value) {
// OldMechanicPreferences.setString(key, value);
// }
//
// public boolean isShowPopup() {
// return OldMechanicPreferences.isShowPopup();
// }
//
// public void doNotShowPopup() {
// OldMechanicPreferences.doNotShowPopup();
// }
//
// public void showPopup() {
// OldMechanicPreferences.showPopup();
// }
//
// public IStatus validatePreferencesFile(IPath path) {
// return OldMechanicPreferences.validatePreferencesFile(path);
// }
// }
// Path: parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/core/MechanicPreferencesTest.java
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.Evaluator;
import com.google.eclipse.mechanic.RepairAction;
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.internal.MechanicPreferences;
import com.google.eclipse.mechanic.tests.internal.RunAsPluginTest;
assertTrue(mechanicPreferences.contains(pref));
setToDefault(pref);
assertFalse(mechanicPreferences.contains(pref));
}
//public static int getThreadSleepSeconds() {
//public static String doVariableSubstitution(String input) {
//public static IStatus validatePreferencesFile(IPath path) {
/**
* Create a mock task with the given id.
*/
private Task createTask(final String id) {
return new Task() {
public String getId() {
return id;
}
public String getTitle() {
throw new AssertionError();
}
public String getDescription() {
throw new AssertionError();
}
public Evaluator getEvaluator() {
throw new AssertionError();
}
| public RepairAction getRepairAction() { |
alfsch/workspacemechanic | parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/ui/TaskResourceValidatorTest.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/TaskResourceValidator.java
// class TaskResourceValidator implements IInputValidator {
// static final String PATH_DOES_NOT_EXIST = "The specified path does not exist.";
// static final String NOT_A_DIRECTORY = "Not a directory";
// static final String CANNOT_READ = "Cannot read";
// static final String UNACCEPTABLE_PROTOCOL = "This protocol is not supported.";
// static final String RELATIVE_PATH = "Local directories must be absolute paths.";
// static final String INVALID_URL = "Invalid URL";
//
// private final boolean allowUrls;
//
// public TaskResourceValidator(boolean allowUrls) {
// this.allowUrls = allowUrls;
// }
//
// public String isValid(String newText) {
// if (allowUrls) {
// return validateUri(newText);
// } else {
// return validateFile(newText);
// }
// }
//
// private String validateUri(String newText) {
// try {
// URI uri = new URI(newText);
// String scheme = uri.getScheme();
// if (!(scheme == null || "file".equals(scheme) || "http".equals(scheme) || "https"
// .equals(scheme))) {
// return UNACCEPTABLE_PROTOCOL;
// }
// if (scheme == null) {
// return validateFile(newText);
// }
// return null;
// } catch (URISyntaxException e) {
// return validateFile(newText);
// }
// }
//
// private String validateFile(String newText) {
// File file = new File(newText);
// if (!file.isAbsolute()) {
// return RELATIVE_PATH;
// }
// if (!file.exists()) {
// return PATH_DOES_NOT_EXIST;
// }
// if (!file.isDirectory()) {
// return NOT_A_DIRECTORY;
// }
// if (!file.canRead()) {
// return CANNOT_READ;
// }
// return null;
// }
//
// @Override
// public String toString() {
// return "TaskResourceValidator: " + allowUrls;
// }
// }
| import java.io.File;
import java.io.IOException;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.tests.internal.RunAsJUnitTest;
import static com.google.eclipse.mechanic.plugin.ui.TaskResourceValidator.*; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* Tests for {@link TaskResourceValidator}.
*/
@RunAsJUnitTest
public class TaskResourceValidatorTest extends TestCase { | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/TaskResourceValidator.java
// class TaskResourceValidator implements IInputValidator {
// static final String PATH_DOES_NOT_EXIST = "The specified path does not exist.";
// static final String NOT_A_DIRECTORY = "Not a directory";
// static final String CANNOT_READ = "Cannot read";
// static final String UNACCEPTABLE_PROTOCOL = "This protocol is not supported.";
// static final String RELATIVE_PATH = "Local directories must be absolute paths.";
// static final String INVALID_URL = "Invalid URL";
//
// private final boolean allowUrls;
//
// public TaskResourceValidator(boolean allowUrls) {
// this.allowUrls = allowUrls;
// }
//
// public String isValid(String newText) {
// if (allowUrls) {
// return validateUri(newText);
// } else {
// return validateFile(newText);
// }
// }
//
// private String validateUri(String newText) {
// try {
// URI uri = new URI(newText);
// String scheme = uri.getScheme();
// if (!(scheme == null || "file".equals(scheme) || "http".equals(scheme) || "https"
// .equals(scheme))) {
// return UNACCEPTABLE_PROTOCOL;
// }
// if (scheme == null) {
// return validateFile(newText);
// }
// return null;
// } catch (URISyntaxException e) {
// return validateFile(newText);
// }
// }
//
// private String validateFile(String newText) {
// File file = new File(newText);
// if (!file.isAbsolute()) {
// return RELATIVE_PATH;
// }
// if (!file.exists()) {
// return PATH_DOES_NOT_EXIST;
// }
// if (!file.isDirectory()) {
// return NOT_A_DIRECTORY;
// }
// if (!file.canRead()) {
// return CANNOT_READ;
// }
// return null;
// }
//
// @Override
// public String toString() {
// return "TaskResourceValidator: " + allowUrls;
// }
// }
// Path: parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/plugin/ui/TaskResourceValidatorTest.java
import java.io.File;
import java.io.IOException;
import junit.framework.TestCase;
import com.google.eclipse.mechanic.tests.internal.RunAsJUnitTest;
import static com.google.eclipse.mechanic.plugin.ui.TaskResourceValidator.*;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* Tests for {@link TaskResourceValidator}.
*/
@RunAsJUnitTest
public class TaskResourceValidatorTest extends TestCase { | private static final TaskResourceValidator ALL_VALIDATOR = new TaskResourceValidator(true); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/recorder/PreferenceRecordingService.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
| import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status; | /*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.recorder;
/**
* An implementation of the {@link IPreferenceRecordingService}.
*
* @author brianchin@google.com (BrianChin)
*/
public class PreferenceRecordingService implements IPreferenceRecordingService{
private PreferenceRecorder preferenceRecorder;
public synchronized void startRecording() throws CoreException {
if (isRecording()) {
throw new CoreException(new Status(
IStatus.ERROR, | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/recorder/PreferenceRecordingService.java
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
/*******************************************************************************
* Copyright (C) 2010, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.recorder;
/**
* An implementation of the {@link IPreferenceRecordingService}.
*
* @author brianchin@google.com (BrianChin)
*/
public class PreferenceRecordingService implements IPreferenceRecordingService{
private PreferenceRecorder preferenceRecorder;
public synchronized void startRecording() throws CoreException {
if (isRecording()) {
throw new CoreException(new Status(
IStatus.ERROR, | MechanicPlugin.PLUGIN_ID, |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/EclBinding.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
| import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.bindings.Binding;
import java.util.Map; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* This class has a 1-to-1 correspondence with Eclipse's {@link Binding}, except
* with primitives (Strings) instead of Eclipse data structure.
*
* <p>Like {@link Binding}, this supports a null command (whereas
* {@link KbaBinding} will not).
*
* <p>This only exists because these Eclipse data structures are not unit-testable.
*
* @author zorzella
*/
class EclBinding {
private final String cid;
private final Map<String, String> paramMap;
private final String schemeId;
private final String platform;
private final String contextId;
private final String keySequence; | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/EclBinding.java
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.bindings.Binding;
import java.util.Map;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* This class has a 1-to-1 correspondence with Eclipse's {@link Binding}, except
* with primitives (Strings) instead of Eclipse data structure.
*
* <p>Like {@link Binding}, this supports a null command (whereas
* {@link KbaBinding} will not).
*
* <p>This only exists because these Eclipse data structures are not unit-testable.
*
* @author zorzella
*/
class EclBinding {
private final String cid;
private final Map<String, String> paramMap;
private final String schemeId;
private final String platform;
private final String contextId;
private final String keySequence; | private final BindingType type; |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/EclBinding.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
| import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.bindings.Binding;
import java.util.Map; | if (!(obj instanceof EclBinding)) {
return false;
}
EclBinding that = (EclBinding)obj;
return Objects.equal(this.cid, that.cid)
&& Objects.equal(this.contextId, that.contextId)
&& Objects.equal(this.keySequence, that.keySequence)
&& Objects.equal(this.paramMap, that.paramMap)
&& Objects.equal(this.platform, that.platform)
&& Objects.equal(this.schemeId, that.schemeId)
&& Objects.equal(this.type, that.type);
}
@Override
public int hashCode() {
return Objects.hashCode(this.cid,
this.contextId,
this.keySequence,
this.paramMap,
this.platform,
this.schemeId,
this.type);
}
private static final Function<Binding, EclBinding> TRANSFORM = new Function<Binding, EclBinding>() {
public EclBinding apply(Binding b) {
return new EclBinding(b);
}
};
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/EclBinding.java
import com.google.common.base.Function;
import com.google.common.base.Objects;
import com.google.common.collect.Iterables;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.eclipse.core.commands.ParameterizedCommand;
import org.eclipse.jface.bindings.Binding;
import java.util.Map;
if (!(obj instanceof EclBinding)) {
return false;
}
EclBinding that = (EclBinding)obj;
return Objects.equal(this.cid, that.cid)
&& Objects.equal(this.contextId, that.contextId)
&& Objects.equal(this.keySequence, that.keySequence)
&& Objects.equal(this.paramMap, that.paramMap)
&& Objects.equal(this.platform, that.platform)
&& Objects.equal(this.schemeId, that.schemeId)
&& Objects.equal(this.type, that.type);
}
@Override
public int hashCode() {
return Objects.hashCode(this.cid,
this.contextId,
this.keySequence,
this.paramMap,
this.platform,
this.schemeId,
this.type);
}
private static final Function<Binding, EclBinding> TRANSFORM = new Function<Binding, EclBinding>() {
public EclBinding apply(Binding b) {
return new EclBinding(b);
}
};
| public KbaChangeSetQualifier with(Action action) { |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/MechanicDialog.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairDecisionProvider.java
// public enum Decision {
//
// YES,
// NO,
// NEVER;
//
// public static Decision valueOf(int ord) {
// return Decision.values()[ord];
// }
// }
| import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.RepairDecisionProvider.Decision;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* Dialog box that displays a list of available Tasks. Users use this
* dialog box to select Tasks to execute.
*
* @author smckay@google.com (Steve McKay)
*/
public class MechanicDialog extends TitleAreaDialog {
// action choice display names
private static final String YES = "Fix Now";
private static final String NO = "Fix Later";
private static final String NEVER = "Never Fix";
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairDecisionProvider.java
// public enum Decision {
//
// YES,
// NO,
// NEVER;
//
// public static Decision valueOf(int ord) {
// return Decision.values()[ord];
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/MechanicDialog.java
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.RepairDecisionProvider.Decision;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* Dialog box that displays a list of available Tasks. Users use this
* dialog box to select Tasks to execute.
*
* @author smckay@google.com (Steve McKay)
*/
public class MechanicDialog extends TitleAreaDialog {
// action choice display names
private static final String YES = "Fix Now";
private static final String NO = "Fix Later";
private static final String NEVER = "Never Fix";
| private final List<Task> items; |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/MechanicDialog.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairDecisionProvider.java
// public enum Decision {
//
// YES,
// NO,
// NEVER;
//
// public static Decision valueOf(int ord) {
// return Decision.values()[ord];
// }
// }
| import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.RepairDecisionProvider.Decision;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | /*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* Dialog box that displays a list of available Tasks. Users use this
* dialog box to select Tasks to execute.
*
* @author smckay@google.com (Steve McKay)
*/
public class MechanicDialog extends TitleAreaDialog {
// action choice display names
private static final String YES = "Fix Now";
private static final String NO = "Fix Later";
private static final String NEVER = "Never Fix";
private final List<Task> items; | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/Task.java
// public interface Task {
//
// /**
// * Return an id for this task. The id should be unique to any instance that
// * behaves differently than another instance. Typically the id would be the
// * fully qualified class name unless two task instances somehow manage to
// * behave differently. In this case they should each return a unique id.
// */
// public String getId();
//
// /**
// * Returns a string suitable for display to the user providing a title for
// * this Task. This is used in contexts where a short
// * description is needed. Capitalization should follow the same rules as
// * applied to book titles.
// */
// public String getTitle();
//
// /**
// * Returns a string suitable for display to the user describing what action
// * will be taken when the associated {@link RepairAction} is executed.
// * <p/>
// * The description should start with a 3rd person descriptive verb such as:
// * <p/>
// * "Customizes your java code templates with user information."
// * "Configures a local extension location."
// */
// public String getDescription();
//
// /**
// * Returns an Evaluator for this task. The Evaluator should return false
// * if the associated RepairAction needs to be executed.
// */
// public Evaluator getEvaluator();
//
// /**
// * Returns a {@link RepairAction} capable of bringing this {@link Task}
// * into compliance.
// */
// public RepairAction getRepairAction();
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/RepairDecisionProvider.java
// public enum Decision {
//
// YES,
// NO,
// NEVER;
//
// public static Decision valueOf(int ord) {
// return Decision.values()[ord];
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/ui/MechanicDialog.java
import com.google.eclipse.mechanic.Task;
import com.google.eclipse.mechanic.RepairDecisionProvider.Decision;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.plugin.ui;
/**
* Dialog box that displays a list of available Tasks. Users use this
* dialog box to select Tasks to execute.
*
* @author smckay@google.com (Steve McKay)
*/
public class MechanicDialog extends TitleAreaDialog {
// action choice display names
private static final String YES = "Fix Now";
private static final String NO = "Fix Later";
private static final String NEVER = "Never Fix";
private final List<Task> items; | private final Map<Task, Decision> userTaskChoices; |
alfsch/workspacemechanic | parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatterTest.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// static final class KbaBindingList {
// private final ImmutableList<KbaBinding> list;
//
// public KbaBindingList(KbaBinding... list) {
// this(Arrays.asList(list));
// }
//
// public KbaBindingList(Iterable<KbaBinding> list) {
// this.list = ImmutableList.copyOf(list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(list);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof KbaBindingList)) {
// return false;
// }
// KbaBindingList that = (KbaBindingList) obj;
// return this.list.equals(that.list);
// }
//
// @Override
// public String toString() {
// return this.list.toString();
// }
//
// public ImmutableList<KbaBinding> getList() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
| import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.KbaBindingList;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.junit.Test;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import junit.framework.Assert; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Tests for {@link KeyBindingsManualFormatter}
*/
public class KeyBindingsManualFormatterTest {
private static final KbaChangeSetQualifier QUALIFIER = new KbaChangeSetQualifier(
"org.eclipse.ui.defaultAcceleratorConfiguration",
null, // platform
"org.eclipse.ui.contexts.window", | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// static final class KbaBindingList {
// private final ImmutableList<KbaBinding> list;
//
// public KbaBindingList(KbaBinding... list) {
// this(Arrays.asList(list));
// }
//
// public KbaBindingList(Iterable<KbaBinding> list) {
// this.list = ImmutableList.copyOf(list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(list);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof KbaBindingList)) {
// return false;
// }
// KbaBindingList that = (KbaBindingList) obj;
// return this.list.equals(that.list);
// }
//
// @Override
// public String toString() {
// return this.list.toString();
// }
//
// public ImmutableList<KbaBinding> getList() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
// Path: parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatterTest.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.KbaBindingList;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.junit.Test;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Tests for {@link KeyBindingsManualFormatter}
*/
public class KeyBindingsManualFormatterTest {
private static final KbaChangeSetQualifier QUALIFIER = new KbaChangeSetQualifier(
"org.eclipse.ui.defaultAcceleratorConfiguration",
null, // platform
"org.eclipse.ui.contexts.window", | Action.ADD.toString()); |
alfsch/workspacemechanic | parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatterTest.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// static final class KbaBindingList {
// private final ImmutableList<KbaBinding> list;
//
// public KbaBindingList(KbaBinding... list) {
// this(Arrays.asList(list));
// }
//
// public KbaBindingList(Iterable<KbaBinding> list) {
// this.list = ImmutableList.copyOf(list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(list);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof KbaBindingList)) {
// return false;
// }
// KbaBindingList that = (KbaBindingList) obj;
// return this.list.equals(that.list);
// }
//
// @Override
// public String toString() {
// return this.list.toString();
// }
//
// public ImmutableList<KbaBinding> getList() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
| import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.KbaBindingList;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.junit.Test;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import junit.framework.Assert; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Tests for {@link KeyBindingsManualFormatter}
*/
public class KeyBindingsManualFormatterTest {
private static final KbaChangeSetQualifier QUALIFIER = new KbaChangeSetQualifier(
"org.eclipse.ui.defaultAcceleratorConfiguration",
null, // platform
"org.eclipse.ui.contexts.window",
Action.ADD.toString());
@Test
public void testARoundTripCommandWithParams() {
KbaBinding expectedKbaBinding = kbaBindingCommandWithParams(); | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// static final class KbaBindingList {
// private final ImmutableList<KbaBinding> list;
//
// public KbaBindingList(KbaBinding... list) {
// this(Arrays.asList(list));
// }
//
// public KbaBindingList(Iterable<KbaBinding> list) {
// this.list = ImmutableList.copyOf(list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(list);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof KbaBindingList)) {
// return false;
// }
// KbaBindingList that = (KbaBindingList) obj;
// return this.list.equals(that.list);
// }
//
// @Override
// public String toString() {
// return this.list.toString();
// }
//
// public ImmutableList<KbaBinding> getList() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
// Path: parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatterTest.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.KbaBindingList;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.junit.Test;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Tests for {@link KeyBindingsManualFormatter}
*/
public class KeyBindingsManualFormatterTest {
private static final KbaChangeSetQualifier QUALIFIER = new KbaChangeSetQualifier(
"org.eclipse.ui.defaultAcceleratorConfiguration",
null, // platform
"org.eclipse.ui.contexts.window",
Action.ADD.toString());
@Test
public void testARoundTripCommandWithParams() {
KbaBinding expectedKbaBinding = kbaBindingCommandWithParams(); | Map<KbaChangeSetQualifier, KbaChangeSet> map = kbaMap(new KbaBindingList( |
alfsch/workspacemechanic | parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatterTest.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// static final class KbaBindingList {
// private final ImmutableList<KbaBinding> list;
//
// public KbaBindingList(KbaBinding... list) {
// this(Arrays.asList(list));
// }
//
// public KbaBindingList(Iterable<KbaBinding> list) {
// this.list = ImmutableList.copyOf(list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(list);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof KbaBindingList)) {
// return false;
// }
// KbaBindingList that = (KbaBindingList) obj;
// return this.list.equals(that.list);
// }
//
// @Override
// public String toString() {
// return this.list.toString();
// }
//
// public ImmutableList<KbaBinding> getList() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
| import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.KbaBindingList;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.junit.Test;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import junit.framework.Assert; | /*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Tests for {@link KeyBindingsManualFormatter}
*/
public class KeyBindingsManualFormatterTest {
private static final KbaChangeSetQualifier QUALIFIER = new KbaChangeSetQualifier(
"org.eclipse.ui.defaultAcceleratorConfiguration",
null, // platform
"org.eclipse.ui.contexts.window",
Action.ADD.toString());
@Test
public void testARoundTripCommandWithParams() {
KbaBinding expectedKbaBinding = kbaBindingCommandWithParams();
Map<KbaChangeSetQualifier, KbaChangeSet> map = kbaMap(new KbaBindingList(
expectedKbaBinding));
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// enum Action {
// ADD("add"),
// REMOVE("remove"),
// ;
//
// /**
// * Label as it appears in the .kbd JSON file
// */
// private final String label;
//
// Action(String label) {
// this.label = label;
// }
//
// public static Action fromLabel(String someLabel) {
// for (Action a : values()) {
// if (a.label.equals(someLabel))
// return a;
// }
// throw new IllegalArgumentException(String.format(
// "'%s' is not a valid action",
// someLabel));
// }
//
// static Action forLabel(String label) {
// for (Action action : values()) {
// if (action.label.equals(label)) {
// return action;
// }
// }
// throw new IllegalArgumentException(label);
// }
//
// @Override
// public String toString() {
// return label;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KbaChangeSet.java
// static final class KbaBindingList {
// private final ImmutableList<KbaBinding> list;
//
// public KbaBindingList(KbaBinding... list) {
// this(Arrays.asList(list));
// }
//
// public KbaBindingList(Iterable<KbaBinding> list) {
// this.list = ImmutableList.copyOf(list);
// }
//
// @Override
// public int hashCode() {
// return Objects.hashCode(list);
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof KbaBindingList)) {
// return false;
// }
// KbaBindingList that = (KbaBindingList) obj;
// return this.list.equals(that.list);
// }
//
// @Override
// public String toString() {
// return this.list.toString();
// }
//
// public ImmutableList<KbaBinding> getList() {
// return list;
// }
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatter.java
// enum BindingType {
// USER,
// SYSTEM,
// ;
//
// static BindingType from(Binding binding) {
// return from(binding.getType());
// }
//
// static BindingType from(int eclipseBindingType) {
// if (eclipseBindingType == Binding.SYSTEM) {
// return SYSTEM;
// } else if (eclipseBindingType == Binding.USER) {
// return USER;
// } else {
// throw new UnsupportedOperationException("Binding type: " + eclipseBindingType);
// }
// }
//
// }
// Path: parent/tests/com.google.eclipse.mechanic.tests/src/com/google/eclipse/mechanic/core/keybinding/KeyBindingsManualFormatterTest.java
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.Action;
import com.google.eclipse.mechanic.core.keybinding.KbaChangeSet.KbaBindingList;
import com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.BindingType;
import org.junit.Test;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
/*******************************************************************************
* Copyright (C) 2011, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.core.keybinding;
/**
* Tests for {@link KeyBindingsManualFormatter}
*/
public class KeyBindingsManualFormatterTest {
private static final KbaChangeSetQualifier QUALIFIER = new KbaChangeSetQualifier(
"org.eclipse.ui.defaultAcceleratorConfiguration",
null, // platform
"org.eclipse.ui.contexts.window",
Action.ADD.toString());
@Test
public void testARoundTripCommandWithParams() {
KbaBinding expectedKbaBinding = kbaBindingCommandWithParams();
Map<KbaChangeSetQualifier, KbaChangeSet> map = kbaMap(new KbaBindingList(
expectedKbaBinding));
| String json = KeyBindingsManualFormatter.getBindingsPrintout(BindingType.USER, map, ""); |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/TasksExtensionPoint.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/CompositeTaskInterface.java
// public interface CompositeTaskInterface extends Task, Evaluator, RepairAction {
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
| import java.util.List;
import org.eclipse.core.runtime.Platform;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.eclipse.mechanic.CompositeTaskInterface;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin; | /*******************************************************************************
* Copyright (C) 2009, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* Code behind the {@code com.google.eclipse.mechanic.tasks} extension point.
*
* <p>This class interfaces with the {@link Platform}, reading all extensions of the
* {@code tasks} extension point, providing a mechanism for translating their
* implementations to instances of {@link CompositeTaskInterface}.
*/
public class TasksExtensionPoint {
private static final String EXTENSION_POINT_NAME = "tasks";
private static final String TAG_TASK = "task";
private static final String ATTR_CLASS = "class";
private static final String ATTR_FORCE_PLUGIN_ACTIVATION = "forcePluginActivation";
// Initialization On Demand Holder Idiom
// http://crazybob.org/2007/01/lazy-loading-singletons.html
private static class SingletonHolder { | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/CompositeTaskInterface.java
// public interface CompositeTaskInterface extends Task, Evaluator, RepairAction {
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/IResourceTaskProvider.java
// public interface IResourceTaskProvider {
// /**
// * Collect task references provided by this provider.
// *
// * <p>In theory this is similar to calling
// * {@code collectTaskReferences(".", extFilter, collector)}, but
// * that's in theory only.
// *
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String extFilter,
// ICollector<IResourceTaskReference> collector);
//
// /**
// * Collect task references provided by this provider, relative to the
// * provider's root.
// *
// * <p>This is only used for finding Class-based tasks, and is not even
// * implemented in the UriTaskProvider.
// *
// * @param localPath the relative path to the resources
// * @param extFilter the filename extension to filter.
// * @param collector the collector to receive all task references.
// *
// * TODO(konigsberg): Remove the filter parameter.
// */
// void collectTaskReferences(
// String localPath,
// String extFilter,
// ICollector<IResourceTaskReference> collector);
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicPlugin.java
// public class MechanicPlugin extends AbstractUIPlugin {
//
// // The plug-in ID
// public static final String PLUGIN_ID = "com.google.eclipse.mechanic";
//
// // The shared instance
// private static MechanicPlugin plugin;
//
// private IMechanicPreferences mechanicPreferences;
//
// private volatile IPreferenceRecordingService preferenceRecordingService =
// new PreferenceRecordingService();
//
// private PopupNotifier popupNotifier;
//
// public MechanicPlugin() {
// plugin = this;
// }
//
// @Override
// public void start(BundleContext context) throws Exception {
// super.start(context);
//
// mechanicPreferences = new MechanicPreferences();
//
// // popup notifier must start before the mechanic service in order to
// // catch the first statuses.
// popupNotifier = new PopupNotifier(MechanicService.getInstance(), getMechanicPreferences());
// popupNotifier.initialize();
//
// UriCaches.initialize();
//
// // immediately start the mechanic service
// MechanicService.getInstance().start();
// }
//
// @Override
// public void stop(BundleContext context) throws Exception {
// MechanicService.getInstance().stop();
// UriCaches.destroy();
// popupNotifier.dispose();
// TasksExtensionPoint.dispose();
// ScannersExtensionPoint.dispose();
// ResourceTaskProvidersExtensionPoint.dispose();
// plugin = null;
// super.stop(context);
// }
//
// /**
// * Keep this around as some of the generated code expects it.
// * @return shared instance of this plug-in class
// */
// public static MechanicPlugin getDefault() {
// return plugin;
// }
//
// /**
// * Returns an image descriptor for the image file at the given plug-in
// * relative path
// *
// * @param path the path
// * @return the image descriptor
// */
// public static ImageDescriptor getImageDescriptor(String path) {
// return imageDescriptorFromPlugin(PLUGIN_ID, path);
// }
//
// public IPreferenceRecordingService getPreferenceRecordingService() {
// if (preferenceRecordingService == null) {
// preferenceRecordingService = new PreferenceRecordingService();
// }
//
// return preferenceRecordingService;
// }
//
// public IMechanicPreferences getMechanicPreferences() {
// return mechanicPreferences;
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/TasksExtensionPoint.java
import java.util.List;
import org.eclipse.core.runtime.Platform;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.eclipse.mechanic.CompositeTaskInterface;
import com.google.eclipse.mechanic.IResourceTaskProvider;
import com.google.eclipse.mechanic.plugin.core.MechanicPlugin;
/*******************************************************************************
* Copyright (C) 2009, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* Code behind the {@code com.google.eclipse.mechanic.tasks} extension point.
*
* <p>This class interfaces with the {@link Platform}, reading all extensions of the
* {@code tasks} extension point, providing a mechanism for translating their
* implementations to instances of {@link CompositeTaskInterface}.
*/
public class TasksExtensionPoint {
private static final String EXTENSION_POINT_NAME = "tasks";
private static final String TAG_TASK = "task";
private static final String ATTR_CLASS = "class";
private static final String ATTR_FORCE_PLUGIN_ACTIVATION = "forcePluginActivation";
// Initialization On Demand Holder Idiom
// http://crazybob.org/2007/01/lazy-loading-singletons.html
private static class SingletonHolder { | static SimpleExtensionPointManager<CompositeTaskInterface> instance = |
alfsch/workspacemechanic | parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/RootTaskScanner.java | // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskScanner.java
// public interface TaskScanner {
//
// /**
// * Adds Tasks to the supplied collector.
// *
// * @param collector the collector of {@link Task}s.
// */
// void scan(TaskCollector collector);
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicLog.java
// public class MechanicLog {
// private static MechanicLog DEFAULT;
//
// private final ILog log;
//
// /**
// * Get the default instance.
// */
// public synchronized static MechanicLog getDefault() {
// if (DEFAULT == null) {
// DEFAULT = new MechanicLog(MechanicPlugin.getDefault());
// }
// return DEFAULT;
// }
//
// MechanicLog(Plugin plugin) {
// this(plugin.getLog());
// }
//
// public MechanicLog(ILog log) {
// this.log = Preconditions.checkNotNull(log);
// }
//
// /**
// * Log a status.
// */
// public void log(IStatus status) {
// log.log(status);
// }
//
// /**
// * Log an error to the Eclipse log.
// *
// * @param t the throwable.
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logError(Throwable t, String fmt, Object... args) {
// String text = (args.length > 0) ? String.format(fmt, args) : fmt;
// log(new Status(IStatus.ERROR, MechanicPlugin.PLUGIN_ID, text, t));
// }
//
// /**
// * Log an error to the Eclipse log, using the exception's message as the log message text.
// *
// * @param t the throwable.
// */
// public void logError(Throwable t) {
// logError(t, t.getMessage());
// }
//
// /**
// * Log info to the Eclipse log.
// *
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logInfo(String fmt, Object... args) {
// log(IStatus.INFO, fmt, args);
// }
//
// /**
// * Log warning to the Eclipse log.
// *
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logWarning(String fmt, Object... args) {
// log(IStatus.WARNING, fmt, args);
// }
//
//
// /**
// * Log a message to the Eclipse log.
// *
// * @param severity message severity. Reference {@link IStatus#getSeverity()}.
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void log(int severity, String fmt, Object... args) {
// String text = (args.length > 0) ? String.format(fmt, args) : fmt;
// log(new Status(severity, MechanicPlugin.PLUGIN_ID, text));
// }
// }
| import java.util.List;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.eclipse.mechanic.TaskCollector;
import com.google.eclipse.mechanic.TaskScanner;
import com.google.eclipse.mechanic.plugin.core.MechanicLog; | /*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* A {@link TaskScanner} that loads and runs all other {@link TaskScanner}s.
*/
public class RootTaskScanner implements TaskScanner {
private static RootTaskScanner instance;
| // Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskCollector.java
// public interface TaskCollector extends ICollector<Task> {
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/TaskScanner.java
// public interface TaskScanner {
//
// /**
// * Adds Tasks to the supplied collector.
// *
// * @param collector the collector of {@link Task}s.
// */
// void scan(TaskCollector collector);
//
// }
//
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/plugin/core/MechanicLog.java
// public class MechanicLog {
// private static MechanicLog DEFAULT;
//
// private final ILog log;
//
// /**
// * Get the default instance.
// */
// public synchronized static MechanicLog getDefault() {
// if (DEFAULT == null) {
// DEFAULT = new MechanicLog(MechanicPlugin.getDefault());
// }
// return DEFAULT;
// }
//
// MechanicLog(Plugin plugin) {
// this(plugin.getLog());
// }
//
// public MechanicLog(ILog log) {
// this.log = Preconditions.checkNotNull(log);
// }
//
// /**
// * Log a status.
// */
// public void log(IStatus status) {
// log.log(status);
// }
//
// /**
// * Log an error to the Eclipse log.
// *
// * @param t the throwable.
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logError(Throwable t, String fmt, Object... args) {
// String text = (args.length > 0) ? String.format(fmt, args) : fmt;
// log(new Status(IStatus.ERROR, MechanicPlugin.PLUGIN_ID, text, t));
// }
//
// /**
// * Log an error to the Eclipse log, using the exception's message as the log message text.
// *
// * @param t the throwable.
// */
// public void logError(Throwable t) {
// logError(t, t.getMessage());
// }
//
// /**
// * Log info to the Eclipse log.
// *
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logInfo(String fmt, Object... args) {
// log(IStatus.INFO, fmt, args);
// }
//
// /**
// * Log warning to the Eclipse log.
// *
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void logWarning(String fmt, Object... args) {
// log(IStatus.WARNING, fmt, args);
// }
//
//
// /**
// * Log a message to the Eclipse log.
// *
// * @param severity message severity. Reference {@link IStatus#getSeverity()}.
// * @param fmt string format
// * @param args args that accompany the string format. If this is empty, fmt is assumed to be
// * an unformatted string.
// */
// public void log(int severity, String fmt, Object... args) {
// String text = (args.length > 0) ? String.format(fmt, args) : fmt;
// log(new Status(severity, MechanicPlugin.PLUGIN_ID, text));
// }
// }
// Path: parent/bundles/com.google.eclipse.mechanic/src/com/google/eclipse/mechanic/internal/RootTaskScanner.java
import java.util.List;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.eclipse.mechanic.TaskCollector;
import com.google.eclipse.mechanic.TaskScanner;
import com.google.eclipse.mechanic.plugin.core.MechanicLog;
/*******************************************************************************
* Copyright (C) 2007, Google Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package com.google.eclipse.mechanic.internal;
/**
* A {@link TaskScanner} that loads and runs all other {@link TaskScanner}s.
*/
public class RootTaskScanner implements TaskScanner {
private static RootTaskScanner instance;
| private final MechanicLog log; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.