src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
FloatSlider extends BoundedFloatWidget { public FloatSlider() { super(); openComm(); } FloatSlider(); String getOrientation(); void setOrientation(String orientation); String getSlider_color(); void setSlider_color(String slider_color); Boolean getReadOut(); void setReadOut(Object readOut); Boolean getContinuous_update...
@Test public void shouldSendCommMsgWhenValueChange() throws Exception { FloatSlider floatSlider = floatSlider(); floatSlider.setValue(11.1); verifyMsgForProperty(groovyKernel, FloatSlider.VALUE, 11.1); } @Test public void shouldSendCommMsgWhenStepChange() throws Exception { FloatSlider floatSlider = floatSlider(); floa...
IntSlider extends BoundedIntWidget { public IntSlider() { super(); openComm(); } IntSlider(); String getOrientation(); void setOrientation(String orientation); String getSlider_color(); void setSlider_color(String slider_color); Boolean getReadOut(); void setReadOut(Object readOut); Boolean getContinuous_update(); void...
@Test public void shouldSendCommMsgWhenValueChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setValue(11); verifyMsgForProperty(groovyKernel, IntSlider.VALUE, 11); } @Test public void shouldSendCommMsgWhenDisableChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setDisabled...
ValueWidget extends DOMWidget { public Integer getInteger(Object input) { Integer ret = 0; if (input != null) { if (input instanceof Double) { ret = ((Double) input).intValue(); } else if (input instanceof Integer) { ret = (Integer) input; } else if (input instanceof String) { try { ret = Integer.parseInt((String) inpu...
@Test public void getIntegerWithStringParam_returnInteger() throws Exception { Integer value = valueWidget.getInteger("123"); Assertions.assertThat(value.intValue()).isEqualTo(123); } @Test public void getIntegerWithDoubleParam_returnInteger() throws Exception { Integer value = valueWidget.getInteger(new Double(123)); ...
ValueWidget extends DOMWidget { public Double getDouble(Object input) { Double ret = 0D; if (input != null) { if (input instanceof Integer) { ret = ((Integer) input).doubleValue(); } else if (input instanceof Double) { ret = (Double) input; } else if (input instanceof String) { try { ret = Double.parseDouble((String) i...
@Test public void getDoubleWithStringParam_returnDouble() throws Exception { Double value = valueWidget.getDouble("123"); Assertions.assertThat(value.doubleValue()).isEqualTo(123d); } @Test public void getDoubleWithDoubleParam_returnDouble() throws Exception { Double value = valueWidget.getDouble(new Double(123d)); Ass...
ValueWidget extends DOMWidget { protected Integer[] getArrayOfInteger(Object input, Integer lowerDefault, Integer upperDefault) { Integer[] ret = new Integer[2]; ret[0] = lowerDefault; ret[1] = upperDefault; if (input != null) { if (input instanceof Object[]) { Object[] array = (Object[]) input; if (array.length == 1) ...
@Test public void getArrayOfIntegerWithNullArrayParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(null, 5, 6); Assertions.assertThat(value[0]).isEqualTo(5); Assertions.assertThat(value[1]).isEqualTo(6); } @Test public void getArrayOfIntegerWithOneValueArrayParam_returnArray() throws...
JavaEvaluator implements Evaluator { @Override public void evaluate(SimpleEvaluationObject seo, String code) { jobQueue.add(new jobDescriptor(code,seo)); syncObject.release(); } JavaEvaluator(String id, String sId); @Override void startWorker(); String getShellId(); void killAllThreads(); void cancelExecution(); void r...
@Test public void evaluatePlot_shouldCreatePlotObject() throws Exception { String code = "import com.twosigma.beaker.chart.xychart.*;\n" + "Plot plot = new Plot(); plot.setTitle(\"test title\");\n" + "return plot;"; SimpleEvaluationObject seo = new SimpleEvaluationObject(code, new ExecuteCodeCallbackTest()); javaEvalua...
ValueWidget extends DOMWidget { protected Double[] getArrayOfDouble(Object input, Double lowerDefault, Double upperDefault) { Double[] ret = new Double[2]; ret[0] = lowerDefault; ret[1] = upperDefault; if (input != null) { if (input instanceof Object[]) { Object[] array = (Object[]) input; if (array.length == 1) { ret[...
@Test public void getArrayOfDoubleWithNullArrayParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(null, 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(5d); Assertions.assertThat(value[1]).isEqualTo(6d); } @Test public void getArrayOfDoubleWithOneValueArrayParam_returnArray() throws...
ValueWidget extends DOMWidget { public String getString(Object input) { String ret = ""; if (input != null) { if (input instanceof String) { ret = (String) input; } else if (input instanceof byte[]) { ret = new String((byte[]) input); } else { ret = input.toString(); } } return ret; } T getValue(); void setValue(Objec...
@Test public void getStringWithStringParam_returnString() throws Exception { String value = valueWidget.getString("abc"); Assertions.assertThat(value).isEqualTo("abc"); } @Test public void getStringWithByteArrayParam_returnString() throws Exception { String value = valueWidget.getString("abc".getBytes()); Assertions.as...
ValueWidget extends DOMWidget { public String[] getStringArray(Object input) { List<String> ret = new ArrayList<>(); if (input != null) { if (input instanceof Object[]) { Object[] array = (Object[]) input; for (Object o : array) { ret.add(getString(o)); } }else if(input instanceof Collection<?>){ Collection<Object> arr...
@Test public void getStringArrayWithNullArrayParam_returnEmptyArray() throws Exception { String[] value = valueWidget.getStringArray(null); Assertions.assertThat(value).isEmpty(); } @Test public void getStringArrayWithArrayParam_returnArray() throws Exception { String[] value = valueWidget.getStringArray(new String[]{"...
MorphiaUtils { public static List<String> getApplicationPackageName(final ApplicationContext applicationContext) { Set<String> candidateClasses = new HashSet<>(); candidateClasses.addAll(Arrays.asList(applicationContext.getBeanNamesForAnnotation(SpringBootApplication.class))); candidateClasses.addAll(Arrays.asList(appl...
@Test(expected = Exception.class) public void testWhenNoApplicationAnnotation_ShouldReturnAException() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringApplicationAcceptNoSpringBootApplication.class); MorphiaUtils.getApplicationPackageName(context); } @Test public void testCal...
MorphiaUtils { public static Set<Class<?>> getClasses(final String packageName) { Reflections reflections = new Reflections(packageName); return reflections.getTypesAnnotatedWith(Entity.class); } static List<String> getApplicationPackageName(final ApplicationContext applicationContext); static Set<Class<?>> getClasses...
@Test public void testCallGetClasses_ShouldReturnAClassesInPackage() { Set<Class<?>> classes = MorphiaUtils.getClasses("io.github.ganchix.morphia.utils.context.normal"); assertThat(classes.size(), is(1)); } @Test public void testCallGetClasses_ShouldReturnAClassesInPackage1() { Set<Class<?>> classes = MorphiaUtils.getC...
Fruit { public <T> T fromHtml(String html, Class<T> classOfT) { return fromHtml(html, (Type) classOfT); } Fruit(); T fromHtml(String html, Class<T> classOfT); T fromHtml(String html, Type typeOfT); T fromHtml(File file, String charsetName, String baseUri, Class<T> classOfT); @SuppressWarnings("unchecked") T fromHtml(El...
@Test public void testDirctList() { FruitItems items = new Fruit().fromHtml(htmlStr, FruitItems.class); assert items.size() == 5; assert items.get(4).getId() == 5; System.out.println("fruitItems: " + fruitInfo); } @Test public void testNullInput() { assert null == new Fruit().fromHtml("", Object.class); }
NoticesXmlParser { public static Notices parse(final InputStream inputStream) throws Exception { try { final XmlPullParser parser = Xml.newPullParser(); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false); parser.setInput(inputStream, null); parser.nextTag(); return parse(parser); } finally { inputStream...
@Test public void testParse() throws Exception { assertNotNull(NoticesXmlParser.parse(RuntimeEnvironment.application.getResources().openRawResource(R.raw.notices))); }
LicenseResolver { public static void registerLicense(final License license) { sLicenses.put(license.getName(), license); } private LicenseResolver(); static void registerLicense(final License license); static License read(final String license); }
@Test public void testRegisterLicense() throws Exception { LicenseResolver.registerLicense(new TestLicense()); final License license = LicenseResolver.read(TEST_LICENSE_NAME); assertNotNull(license); assertEquals(TEST_LICENSE_NAME, license.getName()); }
LicenseResolver { public static License read(final String license) { final String trimmedLicense = license.trim(); if (sLicenses.containsKey(trimmedLicense)) { return sLicenses.get(trimmedLicense); } else { throw new IllegalStateException(String.format("no such license available: %s, did you forget to register it?", tr...
@Test(expected = IllegalStateException.class) public void testReadUnknownLicense() throws Exception { LicenseResolver.read(TEST_LICENSE_NAME); } @Test public void testReadKnownLicense() throws Exception { final License license = LicenseResolver.read("MIT License"); assertNotNull(license); assertEquals("MIT License", li...
XPathRecordReader { public synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued) { addField0(xpath, name, multiValued, false, 0); return this; } XPathRecordReader(String forEachXpath); synchronized XPathRecordReader addField(String name, String xpath, boolean multiValued); synchronized...
@Test public void unsupported_Xpaths() { String xml = "<root><b><a x=\"a/b\" h=\"hello-A\"/> </b></root>"; XPathRecordReader rr=null; try { rr = new XPathRecordReader(" Assert.fail("A RuntimeException was expected: } catch (RuntimeException ex) { } try { rr.addField("bold" ,"b", false); Assert.fail("A RuntimeException ...
EvaluatorBag { public static Evaluator getSqlEscapingEvaluator() { return new Evaluator() { public String evaluate(String expression, Context context) { List l = parseParams(expression, context.getVariableResolver()); if (l.size() != 1) { throw new DataImportHandlerException(SEVERE, "'escapeSql' must have at least one ...
@Test public void testGetSqlEscapingEvaluator() { Evaluator sqlEscaper = EvaluatorBag.getSqlEscapingEvaluator(); runTests(sqlTests, sqlEscaper); }
EvaluatorBag { public static Evaluator getUrlEvaluator() { return new Evaluator() { public String evaluate(String expression, Context context) { List l = parseParams(expression, context.getVariableResolver()); if (l.size() != 1) { throw new DataImportHandlerException(SEVERE, "'encodeUrl' must have at least one paramete...
@Test public void testGetUrlEvaluator() throws Exception { Evaluator urlEvaluator = EvaluatorBag.getUrlEvaluator(); runTests(urlTests, urlEvaluator); }
EvaluatorBag { public static List parseParams(String expression, VariableResolver vr) { List result = new ArrayList(); expression = expression.trim(); String[] ss = expression.split(","); for (int i = 0; i < ss.length; i++) { ss[i] = ss[i].trim(); if (ss[i].startsWith("'")) { StringBuilder sb = new StringBuilder(); whi...
@Test public void parseParams() { Map m = new HashMap(); m.put("b","B"); VariableResolverImpl vr = new VariableResolverImpl(); vr.addNamespace("a",m); List l = EvaluatorBag.parseParams(" 1 , a.b, 'hello!', 'ds,o,u\'za',",vr); Assert.assertEquals(new Double(1),l.get(0)); Assert.assertEquals("B",((EvaluatorBag.VariableWr...
EvaluatorBag { static Map<String, Object> getFunctionsNamespace(final List<Map<String, String>> fn, DocBuilder docBuilder) { final Map<String, Evaluator> evaluators = new HashMap<String, Evaluator>(); evaluators.put(DATE_FORMAT_EVALUATOR, getDateFormatEvaluator()); evaluators.put(SQL_ESCAPE_EVALUATOR, getSqlEscapingEva...
@Test public void testEscapeSolrQueryFunction() { final VariableResolverImpl resolver = new VariableResolverImpl(); ContextImpl context = new ContextImpl(null, resolver, null, Context.FULL_DUMP, Collections.EMPTY_MAP, null, null); Context.CURRENT_CONTEXT.set(context); try { Map m= new HashMap(); m.put("query","c:t"); r...
DateFormatTransformer extends Transformer { @SuppressWarnings("unchecked") public Object transformRow(Map<String, Object> aRow, Context context) { for (Map<String, String> map : context.getAllEntityFields()) { Locale locale = Locale.getDefault(); String customLocale = map.get("locale"); if(customLocale != null){ locale...
@Test @SuppressWarnings("unchecked") public void testTransformRow_SingleRow() throws Exception { List fields = new ArrayList(); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "lastModified")); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "dateAdded", RegexTran...
DocBuilder { @SuppressWarnings("unchecked") static Class loadClass(String name, SolrCore core) throws ClassNotFoundException { try { return core != null ? core.getResourceLoader().findClass(name) : Class.forName(name); } catch (Exception e) { try { String n = DocBuilder.class.getPackage().getName() + "." + name; return...
@Test public void loadClass() throws Exception { Class clz = DocBuilder.loadClass("RegexTransformer", null); Assert.assertNotNull(clz); }
RegexTransformer extends Transformer { @SuppressWarnings("unchecked") public Map<String, Object> transformRow(Map<String, Object> row, Context ctx) { List<Map<String, String>> fields = ctx.getAllEntityFields(); for (Map<String, String> field : fields) { String col = field.get(DataImporter.COLUMN); String reStr = ctx.re...
@Test public void commaSeparated() { List<Map<String, String>> fields = new ArrayList<Map<String, String>>(); fields.add(getField("col1", "string", null, "a", ",")); Context context = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, fields, null); Map<String, Object> src = new HashMap<S...
VariableResolver { public abstract Object resolve(String name); abstract Object resolve(String name); abstract String replaceTokens(String template); }
@Test public void testSimpleNamespace() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace("hello", ns); Assert.assertEquals("WORLD", vri.resolve("hello.world")); } @Test public void testDefaults(){ System.setProper...
EntityProcessorBase extends EntityProcessor { public void init(Context context) { rowIterator = null; this.context = context; if (isFirstInit) { firstInit(context); } query = null; } void init(Context context); Map<String, Object> nextModifiedRowKey(); Map<String, Object> nextDeletedRowKey(); Map<String, Object> nextM...
@Test public void multiTransformer() { List<Map<String, String>> fields = new ArrayList<Map<String, String>>(); Map<String, String> entity = new HashMap<String, String>(); entity.put("transformer", T1.class.getName() + "," + T2.class.getName() + "," + T3.class.getName()); fields.add(TestRegexTransformer.getField("A", n...
NumberFormatTransformer extends Transformer { @SuppressWarnings("unchecked") public Object transformRow(Map<String, Object> row, Context context) { for (Map<String, String> fld : context.getAllEntityFields()) { String style = context.replaceTokens(fld.get(FORMAT_STYLE)); if (style != null) { String column = fld.get(Dat...
@Test @SuppressWarnings("unchecked") public void testTransformRow_SingleNumber() { char GERMAN_GROUPING_SEP = new DecimalFormatSymbols(Locale.GERMANY).getGroupingSeparator(); List l = new ArrayList(); l.add(AbstractDataImportHandlerTestCase.createMap("column", "num", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTr...
DataConfig { public void readFromXml(Element e) { List<Element> n = getChildNodes(e, "document"); if (n.isEmpty()) { throw new DataImportHandlerException(SEVERE, "DataImportHandler " + "configuration file must have one <document> node."); } document = new Document(n.get(0)); n = getChildNodes(e, SCRIPT); if (!n.isEmpty...
@Test public void basic() throws Exception { javax.xml.parsers.DocumentBuilder builder = DocumentBuilderFactory .newInstance().newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes())); DataConfig dc = new DataConfig(); dc.readFromXml(doc.getDocumentElement()); Assert.assertEquals("at...
TemplateTransformer extends Transformer { @SuppressWarnings("unchecked") public Object transformRow(Map<String, Object> row, Context context) { VariableResolverImpl resolver = (VariableResolverImpl) context .getVariableResolver(); for (Map<String, String> map : context.getAllEntityFields()) { String expr = map.get(TEMP...
@Test @SuppressWarnings("unchecked") public void testTransformRow() { List fields = new ArrayList(); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "firstName")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "lastName")); fields.add(AbstractDataImportHandlerTestCase.createMap("colu...
JdbcDataSource extends DataSource<Iterator<Map<String, Object>>> { protected Callable<Connection> createConnectionFactory(final Context context, final Properties initProps) { resolveVariables(context, initProps); final String jndiName = initProps.getProperty(JNDI_NAME); final String url = initProps.getProperty(...
@Test public void retrieveFromDriverManager() throws Exception { DriverManager.registerDriver(driver); EasyMock.expect( driver.connect((String) EasyMock.notNull(), (Properties) EasyMock .notNull())).andReturn(connection); connection.setAutoCommit(false); connection.setHoldability(1); props.put(JdbcDataSource.DRIVER, dr...
MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { private int compare(String a, String b) { if (a != null && b != null) { return a.compareTo(b); } if (a == null) { if (b == null) { return 0; } return -1; } return 1; } MetaLocale(); MetaLocale(String language, String script, String territory, String variant);...
@Test public void testCompare() { MetaLocale meta1 = new MetaLocale(null, "Latn", null, null); MetaLocale meta2 = new MetaLocale(null, "Grek", null, null); assertEquals(meta1.compareTo(meta2), 5); assertEquals(meta2.compareTo(meta1), -5); meta2 = new MetaLocale("en", "Latn", null, null); assertEquals(meta1.compareTo(me...
MessageFormat { public void format(MessageArgs args, StringBuilder buf) { this.args = args; this.buf = buf; this.reset(); format(streams[0], null); } MessageFormat(CLDR.Locale locale, ZoneId timeZone, String format); MessageFormat(CLDR.Locale locale, ZoneId timeZone, String format, int maxDepth); void setLocale(CLDR.L...
@Test public void testSelect() { String format = "{gender, select, male {MALE} female {FEMALE} other {OTHER}}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args().add("gender", "female").build()), "FEMALE"); assertEquals(format(msg, args().add("gender", "male").build()), "MAL...
MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { @Override public boolean equals(Object obj) { if (obj instanceof MetaLocale) { MetaLocale other = (MetaLocale) obj; return Arrays.equals(fields, other.fields); } return false; } MetaLocale(); MetaLocale(String language, String script, String territory, String...
@Test public void testEquals() { MetaLocale meta1 = new MetaLocale(null, "Latn", null, null); MetaLocale meta2 = new MetaLocale(null, "Latn", null, null); assertEquals(meta1, meta2); assertEquals(meta1.hashCode(), meta2.hashCode()); meta2 = new MetaLocale("und", "Latn", null, null); assertEquals(meta1, meta2); assertEq...
UnitFactorMap { public UnitCategory getUnitCategory() { return category; } UnitFactorMap(UnitCategory category); private UnitFactorMap(UnitCategory category, Map<Unit, Map<Unit, UnitFactor>> factors); UnitCategory getUnitCategory(); UnitValue convert(UnitValue value, Unit to); UnitValue convert(UnitValue value, Roundi...
@Test public void testBasics() { assertEquals(UnitCategory.ANGLE, new UnitFactorMap(UnitCategory.ANGLE).getUnitCategory()); }
UnitFactorMap { public void sortUnits(Unit[] units) { Arrays.sort(units, (a, b) -> { Integer ia = unitOrder.get(a); Integer ib = unitOrder.get(b); if (ia == null) { return 1; } if (ib == null) { return -1; } return Integer.compare(ia, ib); }); } UnitFactorMap(UnitCategory category); private UnitFactorMap(UnitCategory ...
@Test public void testSortUnits() { Unit[] units = new Unit[] { Unit.KILOMETER, Unit.NANOMETER, Unit.MILE, Unit.INCH, Unit.LIGHT_YEAR }; UnitFactors.LENGTH.sortUnits(units); Unit[] expected = new Unit[] { Unit.LIGHT_YEAR, Unit.MILE, Unit.KILOMETER, Unit.INCH, Unit.NANOMETER }; assertEquals(units, expected); units = new...
UnitFactorMap { public String dump(Unit unit) { StringBuilder buf = new StringBuilder(); buf.append(unit).append(":\n"); Map<Unit, UnitFactor> map = factors.get(unit); for (Unit base : map.keySet()) { UnitFactor factor = map.get(base); buf.append(" ").append(factor).append(" "); buf.append(factor.rational().compute(Rou...
@Test public void testDumpMapping() { String factors = UnitFactors.LENGTH.dump(Unit.INCH); assertTrue(factors.contains("Factor(2.54, CENTIMETER)")); assertTrue(factors.contains("Factor(1 / 12, FOOT)")); }
UnitFactorSet { public List<UnitValue> factors() { return factors; } UnitFactorSet(Unit base, UnitFactorMap factorMap, Unit...units); UnitFactorSet(UnitFactorMap factorMap, Unit...units); private UnitFactorSet(Unit unitBase, boolean forceBase, UnitFactorMap factorMap, Unit...units); Unit base(); List<UnitValue> facto...
@Test public void testDurationFactors() { UnitFactorSet set = new UnitFactorSet(UnitFactors.DURATION, Unit.YEAR, Unit.DAY, Unit.MONTH); assertEquals(set.factors(), Arrays.asList( new UnitValue("365.2425", Unit.YEAR), new UnitValue("30.436875", Unit.MONTH), new UnitValue("1", Unit.DAY) )); }
DigitBuffer implements CharSequence { @Override public DigitBuffer subSequence(int start, int end) { start = clamp(start, 0, size - 1); end = clamp(end, start, size - 1); int sz = end - start; char[] newbuf = new char[16 + sz]; System.arraycopy(buf, start, newbuf, 0, sz); return new DigitBuffer(newbuf, sz); } DigitBuff...
@Test public void testSubsequence() { DigitBuffer buf = new DigitBuffer(); for (int i = 0; i < 10; i++) { char ch = (char)('a' + i); buf.append(ch); } assertEquals(buf.length(), 10); DigitBuffer sub = buf.subSequence(2, 7); assertEquals(sub.length(), 5); assertEquals(sub.toString(), "cdefg"); sub = buf.subSequence(2, 2...
NumberFormattingUtils { public static int integerDigits(BigDecimal n) { return n.precision() - n.scale(); } static int integerDigits(BigDecimal n); static BigDecimal setup( BigDecimal n, // number to be formatted NumberRoundMode roundMode, // rounding mode NumberFormatMode ...
@Test public void testIntegerDigits() { for (int i = 1; i < 10; i++) { intDigits(num("12345", i), 5); intDigits(num("0.12345", i), 0); intDigits(num("12345.12345", i), 5); } }
NumberFormattingUtils { public static BigDecimal setup( BigDecimal n, NumberRoundMode roundMode, NumberFormatMode formatMode, int minIntDigits, int maxFracDigits, int minFracDigits, int maxSigDigits, int minSigDigits) { RoundingMode mode = roundMode.toRoundingMode(); boolean useSignificant = formatMode == SIGNIFICANT |...
@Test public void testSetup() { Builder fmt = format(SIGNIFICANT).minSigDigits(1).maxSigDigits(1); setup(fmt.get(), "0", "0"); setup(fmt.get(), "0.0", "0"); setup(fmt.get(), "1.0", "1"); setup(fmt.get(), "1.23004", "1"); setup(fmt.get(), "12345", "10000"); setup(fmt.get(), "0.12345", "0.1"); setup(fmt.get(), "3.14159",...
NumberFormattingUtils { public static void format( BigDecimal n, DigitBuffer buf, NumberFormatterParams params, boolean currencyMode, boolean grouping, int minIntDigits, int primaryGroupingSize, int secondaryGroupingSize) { if (secondaryGroupingSize <= 0) { secondaryGroupingSize = primaryGroupingSize; } int groupSize =...
@Test public void testCurrency() { Builder fmt = format(DEFAULT) .grouping(true) .currency(true) .currencyDecimal("^") .currencyGroup(" ") .minFracDigits(2) .secondaryGroupingSize(2); format(fmt.get(), "1234567890.126", "1 23 45 67 890^13"); } @Test public void testIntegers() { Builder fmt = format(DEFAULT).minIntDigit...
MetaLocale implements CLDR.Locale, Comparable<MetaLocale> { public String variant() { return getField(VARIANT, ""); } MetaLocale(); MetaLocale(String language, String script, String territory, String variant); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String varia...
@Test public void testVariant() { MetaLocale meta = new MetaLocale("en", null, "US", "POSIX"); assertEquals(meta.compact(), "en-US-POSIX"); assertEquals(meta.expanded(), "en-Zzzz-US-POSIX"); }
NumberPattern { public Format format() { return format == null ? DEFAULT_FORMAT : format; } protected NumberPattern(String pattern, List<Node> parsed, Format format); String pattern(); List<Node> parsed(); Format format(); String render(); @Override boolean equals(Object obj); @Override String toString(); }
@Test public void testDecimalStandard() { assertPattern("-#,##0.###", MINUS, format(3, 0, 1, 3, 0)); assertPattern("#,##,##0.###", format(3, 2, 1, 3, 0)); assertPattern("-#0.######", MINUS, format(0, 0, 1, 6, 0)); } @Test public void testDecimalPercent() { assertPattern("#,##0%", format(3, 0, 1, 0, 0), PERCENT); assert...
DateTimePatternParser { public List<Node> parse(String raw) { StringBuilder buf = new StringBuilder(); char field = '\0'; int width = 0; boolean inquote = false; int length = raw.length(); int i = 0; List<Node> nodes = new ArrayList<>(); while (i < length) { char ch = raw.charAt(i); if (inquote) { if (ch == '\'') { inq...
@Test public void testParse() { assertPattern("y/M/d 'at' h:m", field('y', 1), text("/"), field('M', 1), text("/"), field('d', 1), text(" at "), field('h', 1), text(":"), field('m', 1)); }
LanguageResolver { protected MetaLocale addLikelySubtags(MetaLocale src) { MetaLocale dst = src.copy(); if (src.hasAll()) { return dst; } MetaLocale temp = src.copy(); temp.setVariant(null); for (int flags : MATCH_ORDER) { set(src, temp, flags); MetaLocale match = likelySubtagsMap.get(temp); if (match != null) { if (!d...
@Test public void testAddLikelySubtags() { assertMatch("en", "en-Latn-US"); assertMatch("und-US", "en-Latn-US"); assertMatch("en-US", "en-Latn-US"); assertMatch("en_US", "en-Latn-US"); assertMatch("en-Zzzz-US", "en-Latn-US"); assertMatch("en-US-u-cu-USD", "en-Latn-US"); assertMatch("en-GB", "en-Latn-GB"); assertMatch("...
LanguageMatcher { public Match match(String desiredRaw) { return matchImpl(parse(desiredRaw), DEFAULT_THRESHOLD); } LanguageMatcher(String supportedLocales); LanguageMatcher(List<String> supportedLocales); Match match(String desiredRaw); Match match(String desiredRaw, int threshold); Match match(List<String> desired);...
@Test public void testCases() throws IOException { for (Case c : load()) { match(c.supported, c.desired, c.result); } } @Test public void testBasic() { match("en-US fr-FR de-DE es-ES", "zh ar de", "de-DE"); } @Test public void testList() { match(asList("en", "ar", "zh", "es"), asList("no", "he", "zh", "es"), "zh"); mat...
LanguageMatcher { public List<Match> matches(String desiredRaw) { return matchesImpl(parse(desiredRaw), DEFAULT_THRESHOLD); } LanguageMatcher(String supportedLocales); LanguageMatcher(List<String> supportedLocales); Match match(String desiredRaw); Match match(String desiredRaw, int threshold); Match match(List<String>...
@Test public void testMatches() { matchlist("es-419, es-ES", "es-AR", "es-419:4 es-ES:5"); matchlist("es-ES, es-419", "es-AR", "es-419:4 es-ES:5"); matchlist("es-419, es", "es-AR", "es-419:4 es:5"); matchlist("es, es-419", "es-AR", "es-419:4 es:5"); matchlist("es-MX, es", "es-AR", "es-MX:4 es:5"); matchlist("es, es-MX"...
FileInfosPresenter implements FileInfosContract.Presenter { @Override public void loadFileInfos() { mFileInfosRepository .listFileInfos(mDirectory) .observeOn(mSchedulerProvider.ui()) .subscribe(new Action1<List<FileInfo>>() { @Override public void call(List<FileInfo> fileInfos) { if (fileInfos.isEmpty()) { mView.showN...
@Test public void loadFileInfos_success() throws Exception { setAvailableFileInfos(mMockFileInfosRepository); mFileInfosPresenter.loadFileInfos(); Mockito.verify(mMockView, Mockito.times(1)).showFileInfos(Mockito.anyListOf(FileInfo.class)); }
UserServiceImpl implements UserService { @Override public void create(User user) { User existing = userRepository.findByUsername(user.getUsername()); Assert.isNull(existing, "user already exist: " + user.getUsername()); String hash = encoder.encode(user.getPassword()); user.setPassword(hash); user.setEnabled(true); use...
@Test public void shouldFailWhenUserIsNotFound() throws Exception { doReturn(null).when(userRepository).findByUsername(anyString()); try { final User user = new User("imrenagi", "imrenagi", "imre"); userService.create(user); fail(); } catch (Exception e) { } } @Test public void shouldSaveNewUserWithUserRole() { final U...
MysqlUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { User user = userRepository.findByUsername(s); log.info("user is found! -> " + user.getUsername()); if (user == null) { log.info("user is not found!"); throw new UsernameNo...
@Test public void shouldReturnUserDetailWhenAUserIsFound() throws Exception { final User user = new User("imrenagi", "1234", "imre", "nagi"); doReturn(user).when(repository).findByUsername(user.getUsername()); UserDetails found = userDetailsService.loadUserByUsername(user.getUsername()); assertEquals(user.getUsername()...
AccountServiceImpl implements AccountService { @Override public Account findByUserName(String username) { Assert.hasLength(username); return repository.findByUsername(username); } @Override Account findByUserName(String username); @Override Account findByEmail(String email); @Override Account create(User user); @Overr...
@Test public void shouldFindByUserName() { final Account account = new Account(); account.setUsername("test"); doReturn(account).when(repository).findByUsername(account.getUsername()); Account found = accountService.findByUserName(account.getUsername()); assertEquals(account, found); verify(repository, times(1)).findBy...
AccountServiceImpl implements AccountService { @Override public Account findByEmail(String email) { Assert.hasLength(email); return repository.findByEmail(email); } @Override Account findByUserName(String username); @Override Account findByEmail(String email); @Override Account create(User user); @Override List<Accoun...
@Test public void shouldFindByEmail() { final Account account = new Account(); account.setUsername("imrenagi"); account.setEmail("imre.nagi2812@gmail.com"); doReturn(account).when(repository).findByEmail(account.getEmail()); Account found = accountService.findByEmail(account.getEmail()); assertEquals(account, found); v...
BigFontGenerator { public String convert(String text, int position) { HashMap<Character, String> hashMap = fonts.get(position); ArrayList<String> chars = new ArrayList<>(); for (int i = 0; i < text.length(); i++) { String s = hashMap.get(Character.toUpperCase(text.charAt(i))); if (s == null) { throw new UnsupportedOper...
@Test public void convert() throws Exception { String path = "C:\\github\\ascii_generate\\app\\src\\test\\java\\com\\duy\\ascii\\art\\bigtext\\out.txt"; PrintStream stream = new PrintStream(new FileOutputStream(path)); for (int i = 0; i < mBigFontGenerator.getSize(); i++) { String convert = mBigFontGenerator.convert("h...
JavacTaskImpl extends JavacTask { public Boolean call() { if (!used.getAndSet(true)) { initContext(); notYetEntered = new HashMap<JavaFileObject, JCCompilationUnit>(); compilerMain.setAPIMode(true); result = compilerMain.compile(args, context, fileObjects, processors); cleanup(); return result == 0; } else { throw new ...
@Test public void testDynamicArgs() { javax.tools.JavaCompiler compiler = javax.tools.ToolProvider.getSystemJavaCompiler(); List<String> args = Arrays.asList("-help"); try { javax.tools.JavaCompiler.CompilationTask compilationTask = compiler.getTask(null, null, null, args, null, null); compilationTask.call(); } catch (...
Main { public static void main(String[] args) throws Exception { if (args.length > 0 && args[0].equals("-Xjdb")) { String[] newargs = new String[args.length + 2]; Class<?> c = Class.forName("com.sun.tools.example.debug.tty.TTY"); Method method = c.getDeclaredMethod("main", new Class<?>[] { args.getClass() }); method.se...
@Test public void testMain_fullversion() throws Exception { String[] args = {"-fullversion"}; Main.main(args); } @Test public void testMain_SimpleCompile() { String [] args = { JavacTestTool.JAVAFILES_PATH + "Simple.java", "-d", JavacTestTool.CLASSFILES_PATH, "-verbose" }; try { Main.main(args); } catch (Exception e) {...
Launcher { public static void main(String... args) { JavaCompiler javac = ToolProvider.getSystemJavaCompiler(); JFileChooser fileChooser; Preferences prefs = Preferences.userNodeForPackage(Launcher.class); if (args.length > 0) fileChooser = new JFileChooser(args[0]); else { String fileName = prefs.get("recent.file", nu...
@Test public void testLauncher_fileChooser() { String[] args = {"D:/Workspace/JSE/workspace/Compiler_javac"}; Launcher.main(args); } @Test public void testLauncher_noArgs() { String[] args = {}; Launcher.main(args); } @Test public void testLauncher_Xprint() throws Exception { String[] args = { "-Xprint", "java.lang.Str...
Main { public static int compile(String[] args) { com.sun.tools.javac.main.Main compiler = new com.sun.tools.javac.main.Main("javac"); return compiler.compile(args); } static void main(String[] args); static int compile(String[] args); static int compile(String[] args, PrintWriter out); }
@Test public void testMain_nullArgs() throws Exception { String[] args = {}; int status = Main.compile(args); assertTrue(status == 2); System.exit(status); }
Parser { public MavenRepositoryURL getRepositoryURL() { return m_repositoryURL; } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String ver...
@Test public void behaviorSnapshotEnbled() throws MalformedURLException { Parser parser; parser = new Parser( "http: assertTrue(parser.getRepositoryURL().isSnapshotsEnabled()); assertTrue(parser.getRepositoryURL().isReleasesEnabled()); }
Parser { public String getResourceName() { return m_resourceName; } Parser( final String path ); String getResourceName(); }
@Test public void getResourceNameWithContainingSlash() throws MalformedURLException { assertEquals( "Resource name", "somewhere/resource", new Parser( "somewhere/resource" ).getResourceName() ); } @Test public void getResourceNameWithoutLeadingSlash() throws MalformedURLException { assertEquals( "Resource name", "resou...
AbstractConnection extends URLConnection { protected static boolean checkJarIsLegal(String name) { boolean isMatched = false; for (Pattern pattern : blacklist) { isMatched = pattern.matcher(name).find(); if (isMatched) { break; } } return !isMatched; } protected AbstractConnection( final URL url, ...
@Test public void testCheckJarIsLegal() { String[] servletJarNamesToTest = { "servlet.jar", "servlet-2.5.jar", "servlet-api.jar", "servlet-api-2.5.jar" }; for (String servletName : servletJarNamesToTest) { assertFalse(AbstractConnection.checkJarIsLegal(servletName)); } String[] jasperJarNamesToTest = { "jasper.jar", "j...
Parser { public URL getWrappedJarURL() { return m_wrappedJarURL; } Parser( final String path, final boolean certificateCheck ); URL getWrappedJarURL(); Properties getWrappingProperties(); OverwriteMode getOverwriteMode(); }
@Test public void validWrappedJarURL() throws MalformedURLException { Parser parser = new Parser( "file:toWrap.jar", true ); assertEquals( "Wrapped Jar URL", new URL( "file:toWrap.jar" ), parser.getWrappedJarURL() ); assertNotNull( "Properties was not expected to be null", parser.getWrappedJarURL() ); }
ConfigurationImpl extends PropertyStore implements Configuration { public Boolean getCertificateCheck() { if( !contains( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ) ) { return set( ServiceConstants.PROPERTY_CERTIFICATE_CHECK, Boolean.valueOf( m_propertyResolver.get( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ) ) ); ...
@Test public void getCertificateCheck() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.url.wrap.certificateCheck" ) ).andReturn( "true" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals(...
Connection extends URLConnection { @Override public InputStream getInputStream() throws IOException { return new BundleBuilder( m_parser.getOptions(), new ResourceWriter( new FileTailImpl( m_parser.getDirectory(), m_parser.getTailExpr() ) .getParentOfTail() ) ).build(); } Connection( URL url, Configuration config ); @O...
@Test public void simple() throws IOException { String clazz = this.getClass().getName().replaceAll( "\\.", "/" ) + ".class"; URL url = new URL( "http:.$tail=" + clazz + "&Foo=bar" ); Configuration config = createMock( Configuration.class ); Connection con = new Connection( url, config ); InputStream inp = con.getInput...
Parser { public File getDirectory() { return m_directory; } Parser( String url ); File getDirectory(); Properties getOptions(); String getTailExpr(); }
@Test public void parseValidURL() throws IOException { File f = new File( System.getProperty( "java.io.tmpdir" ) ); assertEquals( f.getCanonicalPath(), new Parser( "http:" + f.getCanonicalPath() ).getDirectory().getAbsolutePath() ); }
Parser { public Properties getOptions() { return m_options; } Parser( String url ); File getDirectory(); Properties getOptions(); String getTailExpr(); }
@Test public void parseWithMoreParams() throws IOException, URISyntaxException { Parser parser = new Parser( "http:." + "$a=1&b=2" ); assertEquals( "1", parser.getOptions().get( "a" ) ); assertEquals( "2", parser.getOptions().get( "b" ) ); assertEquals( 2, parser.getOptions().size() ); }
Parser { public String getSnapshotPath( final String version, final String timestamp, final String buildnumber ) { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( version ) .append( FILE_SEPARA...
@Test public void snapshotPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version-SNAPSHOT" ); assertEquals( "Artifact snapshot path", "group/artifact/version-SNAPSHOT/artifact-version-timestamp-build.jar", parser.getSnapshotPath( "version-SNAPSHOT", "timestamp", "build" ) ); }
Parser { public String getArtifactPath() { return getArtifactPath( m_version ); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String ver...
@Test public void artifactPathWithVersion() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact path", "group/artifact/version2/artifact-version2.jar", parser.getArtifactPath( "version2" ) ); }
Parser { public String getVersionMetadataPath( final String version ) { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( version ) .append( FILE_SEPARATOR ) .append( METADATA_FILE ) .toString();...
@Test public void versionMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Version metadata path", "group/artifact/version2/maven-metadata.xml", parser.getVersionMetadataPath( "version2" ) ); }
Parser { public String getArtifactMetdataPath() { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( METADATA_FILE ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL...
@Test public void artifactMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact metadata path", "group/artifact/maven-metadata.xml", parser.getArtifactMetdataPath() ); }
Parser { public String getArtifactLocalMetdataPath() { return new StringBuilder() .append( m_group.replaceAll( GROUP_SEPARATOR, FILE_SEPARATOR ) ) .append( FILE_SEPARATOR ) .append( m_artifact ) .append( FILE_SEPARATOR ) .append( METADATA_FILE_LOCAL ) .toString(); } Parser( final String path ); MavenRepositoryURL getRe...
@Test public void artifactLocalMetadataPath() throws MalformedURLException { Parser parser = new Parser( "group/artifact/version" ); assertEquals( "Artifact local metadata path", "group/artifact/maven-metadata-local.xml", parser.getArtifactLocalMetdataPath() ); }
MavenRepositoryURL { public MavenRepositoryURL( final String repositorySpec ) throws MalformedURLException { NullArgumentException.validateNotEmpty( repositorySpec, true, "Repository spec" ); final String[] segments = repositorySpec.split( ServiceConstants.SEPARATOR_OPTIONS ); final StringBuilder urlBuilder = new Strin...
@Test public void testMavenRepositoryURL() throws MalformedURLException { File localrepo = new File( "my dir/repository" ).getAbsoluteFile(); String uri = localrepo.toURI().toASCIIString(); MavenRepositoryURL mavenRepo = new MavenRepositoryURL( uri + "@id=repository1" ); assertEquals( localrepo, mavenRepo.getFile() ); ...
Connection extends URLConnection { public InputStream getInputStream() throws IOException { connect(); InputStream is; if( url.getAuthority() != null ) { is = getFromSpecificBundle(); } else { is = getFromClasspath(); if( is == null ) { is = getFromInstalledBundles(); } } if( is == null ) { throw new IOException( "URL ...
@Test public void searchFirstTheThreadClasspath() throws IOException { BundleContext context = createMock( BundleContext.class ); replay( context ); InputStream is = new Connection( new URL( "http:connection/resource" ), context ).getInputStream(); assertNotNull( "Returned input stream is null", is ); verify( context )...
MatrixUtils { public static double[] slicedSimilarity(double[][] matrix, double[] vector, int sliceSize) { int size = matrix.length; double[] result = new double[size]; for (int i = 0; i < size; i = i + sliceSize) { int end = i + sliceSize; if (end > size) { end = size; } double[][] m = Arrays.copyOfRange(matrix, i, en...
@Test public void slicedSimilarityEven() { double[][] matrix = { {1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6} }; double[] vector = {0, 1}; int sliceSize = 2; double[] similarity = MatrixUtils.slicedSimilarity(matrix, vector, sliceSize); double[] expected = {1, 2, 3, 4, 5, 6}; assertTrue(Arrays.equals(expected, simila...
RelevanceModel { public static Dataset concat(Dataset d1, Dataset d2) { double[][] X = concat(d1.getX(), d2.getX()); double[] y = concat(d1.getY(), d2.getY()); return new Dataset(X, y); } static void main(String[] args); static Dataset concat(Dataset d1, Dataset d2); static double[] concat(double[] y1, double[] y2); s...
@Test public void concat1d() { double[] y1 = { 1.0, 2.0, 3.0 }; double[] y2 = { 4.0, 5.0 }; double[] y = RelevanceModel.concat(y1, y2); double[] expected = { 1.0, 2.0, 3.0, 4.0, 5.0 }; assertTrue(Arrays.equals(y, expected)); } @Test public void concat2d() { double[][] X1 = { { 0.0, 1.0 }, { 0.0, 2.0 }, { 0.0, 3.0 } }; ...
NerGroup { public static List<String> groupNer(List<Word> tokens) { if (tokens.isEmpty()) { return Collections.emptyList(); } String prevNer = "O"; List<List<Word>> groups = new ArrayList<>(); List<Word> group = new ArrayList<>(); for (Word w : tokens) { String ner = w.getNer(); if (prevNer.equals(ner) && !"O".equals(n...
@Test public void test() { List<Word> tokens = Arrays.asList( new Word("My", "My", "_", "O"), new Word("name", "name", "_", "O"), new Word("is", "is", "_", "O"), new Word("Justin", "Justin", "_", "PERSON"), new Word("Bieber", "Bieber", "_", "PERSON"), new Word("I", "I", "_", "O"), new Word("live", "live", "_", "O"), ne...
DefaultJavaRunner implements StoppableJavaRunner { static String getJavaExecutable( final String javaHome ) throws PlatformException { if( javaHome == null ) { throw new PlatformException( "JAVA_HOME is not set." ); } return javaHome + "/bin/java"; } DefaultJavaRunner(); DefaultJavaRunner( boolean wait ); synchronized...
@Test public void getJavaExecutable() throws Exception { assertEquals( "Java executable", "javaHome/bin/java", DefaultJavaRunner.getJavaExecutable( "javaHome" ) ); } @Test( expected = PlatformException.class ) public void getJavaExecutableWithInvalidJavaHome() throws Exception { DefaultJavaRunner.getJavaExecutable( nul...
ConciergePlatformBuilder implements PlatformBuilder { public String[] getArguments( final PlatformContext context ) { return null; } ConciergePlatformBuilder( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final...
@Test public void getArguments() throws MalformedURLException { replay( m_bundleContext ); assertArrayEquals( "Arguments", null, new ConciergePlatformBuilder( m_bundleContext, "version" ).getArguments( m_platformContext ) ); verify( m_bundleContext ); }
ConciergePlatformBuilder implements PlatformBuilder { public String[] getVMOptions( final PlatformContext context ) { NullArgumentException.validateNotNull( context, "Platform context" ); final Collection<String> vmOptions = new ArrayList<String>(); final File workingDirectory = context.getWorkingDirectory(); vmOptions...
@Test public void getVMOptions() { expect( m_configuration.getBootDelegation() ).andReturn( "javax.*" ); replay( m_configuration, m_bundleContext ); assertArrayEquals( "System options", new String[]{ "-Dosgi.maxLevel=100", "-Dxargs=" + m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "conci...
ConciergePlatformBuilder implements PlatformBuilder { public void prepare( final PlatformContext context ) throws PlatformException { NullArgumentException.validateNotNull( context, "Platform context" ); final List<BundleReference> bundles = context.getBundles(); OutputStream os = null; try { final File workingDirector...
@Test( expected = IllegalArgumentException.class ) public void prepareWithNullPlatformContext() throws PlatformException { replay( m_bundleContext ); new ConciergePlatformBuilder( m_bundleContext, "version" ).prepare( null ); verify( m_bundleContext ); } @Test public void prepareWithoutBundles() throws PlatformExceptio...
KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String getMainClassName() { return MAIN_CLASS_NAME; } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final Pla...
@Test public void mainClassName() { replay( m_bundleContext ); assertEquals( "Main class name", "org.knopflerfish.framework.Main", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getMainClassName() ); verify( m_bundleContext ); }
KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String getRequiredProfile( final PlatformContext context ) { final Boolean console = context.getConfiguration().startConsole(); if( console == null || !console ) { return null; } else { return CONSOLE_PROFILE; } } KnopflerfishPlatformBuilderF300( final...
@Test public void getRequiredProfilesWithoutConsole() { expect( m_configuration.startConsole() ).andReturn( null ); replay( m_bundleContext, m_configuration ); assertNull( "Required profiles is not null", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getRequiredProfile( m_platformContext ) ); verify...
PlatformImpl implements Platform { public void start( final List<SystemFileReference> systemFiles, final List<BundleReference> bundles, final Properties properties, @SuppressWarnings("rawtypes") final Dictionary config, final JavaRunner javaRunner ) throws PlatformException { LOGGER.info( "Preparing framework [" + this...
@Test( expected = PlatformException.class ) public void startWithAJarWithNoManifestAttr() throws Exception { List<BundleReference> bundles = new ArrayList<BundleReference>(); bundles .add( new BundleReferenceBean( FileUtils.getFileFromClasspath( "platform/noManifestAttr.jar" ).toURL() ) ); start( bundles ); } @Test pub...
KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String[] getArguments( final PlatformContext context ) { NullArgumentException.validateNotNull( context, "Platform context" ); return new String[]{ "-xargs", context.getFilePathStrategy().normalizeAsUrl( new File( new File( context.getWorkingDirectory(...
@Test public void getArguments() throws MalformedURLException { replay( m_bundleContext ); assertArrayEquals( "Arguments", new String[]{ "-xargs", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "knopflerfish/config.ini" ) ), }, new KnopflerfishPlatformBuilderF300( m_bundleContext, "version...
KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public String[] getVMOptions( final PlatformContext context ) { NullArgumentException.validateNotNull( context, "Platform context" ); final Collection<String> vmOptions = new ArrayList<String>(); final File workingDirectory = context.getWorkingDirectory(); vm...
@Test public void getVMOptions() { replay( m_bundleContext ); assertArrayEquals( "System properties", new String[]{ "-Dorg.osgi.framework.dir=" + m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "knopflerfish/fwdir" ) ) }, new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).ge...
KnopflerfishPlatformBuilderF300 implements PlatformBuilder { public void prepare( final PlatformContext context ) throws PlatformException { NullArgumentException.validateNotNull( context, "Platform context" ); final List<BundleReference> bundles = context.getBundles(); OutputStream os = null; try { final File workingD...
@Test( expected = IllegalArgumentException.class ) public void prepareWithNullPlatformContext() throws PlatformException { replay( m_bundleContext ); new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).prepare( null ); verify( m_bundleContext ); } @Test public void prepareWithoutBundles() throws PlatformE...
CommandLineImpl implements CommandLine { public String getOption( final String key ) { final List<String> values = m_options.get( key ); return values == null || values.size() == 0 ? null : values.get( 0 ); } CommandLineImpl( final String... args ); String getOption( final String key ); String[] getMultipleOption( fina...
@Test public void simpleOption() { CommandLine commandLine = new CommandLineImpl( "--simpleOption=simpleValue" ); assertEquals( "Option value", "simpleValue", commandLine.getOption( "simpleOption" ) ); } @Test public void optionWithAValueThatContainsEqual01() { CommandLine commandLine = new CommandLineImpl( "--simpleOp...
CommandLineImpl implements CommandLine { public String[] getMultipleOption( final String key ) { final List<String> values = m_options.get( key ); return values == null || values.size() == 0 ? new String[0] : values.toArray( new String[values.size()] ); } CommandLineImpl( final String... args ); String getOption( final...
@Test public void arrayValueNotDefined() { CommandLine commandLine = new CommandLineImpl( "--some" ); assertArrayEquals( "Option value", new String[0], commandLine.getMultipleOption( "array" ) ); }
ExtensionBasedProvisionSchemaResolver implements ProvisionSchemaResolver { public String resolve( final String toResolve ) { if( toResolve == null || toResolve.trim().length() == 0 ) { return null; } if( toResolve.matches( "scan-.*:.*" ) ) { return toResolve; } String options = ""; String resolve = toResolve; if( toRes...
@Test public void resolveStartingWithScan() { assertEquals( "Resolved", "scan-x:any", m_underTest.resolve( "scan-x:any" ) ); } @Test public void resolvePOMWithFileProtocol() { assertEquals( "Resolved", "scan-pom:file:pom.xml", m_underTest.resolve( "file:pom.xml" ) ); } @Test public void resolvePOMWithMvnProtocol() { as...
PlatformImpl implements Platform { void validateBundle( final URL url, final File file ) throws PlatformException { String bundleSymbolicName = null; String bundleName = null; JarFile jar = null; try { jar = new JarFile( file, false ); final Manifest manifest = jar.getManifest(); if ( manifest == null ) { throw new Pla...
@Test( expected = PlatformException.class ) public void validateBundleWithNoManifestAndCheckAttributes() throws Exception { replay( m_builder, m_bundleContext, m_config ); PlatformImpl platform = new PlatformImpl( m_builder ); File file = FileUtils.getFileFromClasspath( "platform/withoutManifest.jar" ); URL url = file....
PlatformImpl implements Platform { String determineCachingName( final File file, final String defaultBundleSymbolicName ) { String bundleSymbolicName = null; String bundleVersion = null; JarFile jar = null; try { jar = new JarFile( file, false ); final Manifest manifest = jar.getManifest(); if ( manifest != null ) { bu...
@Test public void determineCachingNameWithNoManifestAttributes() throws Exception { replay( m_builder, m_bundleContext, m_config ); PlatformImpl platform = new PlatformImpl( m_builder ); File file = FileUtils.getFileFromClasspath( "platform/noManifestAttr.jar" ); assertEquals( "defaultBSN_0.0.0.jar", platform.determine...
Run { public static void start( final JavaRunner runner, final String... args ) { final CommandLine commandLine = new CommandLineImpl( args ); String configURL = commandLine.getOption( OPTION_CONFIG ); if( configURL == null ) { configURL = "classpath:META-INF/runner.properties"; } final Configuration config = new Confi...
@Test( expected = IllegalArgumentException.class ) public void startWithNullCommandLine() { new Run().start( null, createMock( Configuration.class ), createMock( OptionResolver.class ) ); } @Test( expected = IllegalArgumentException.class ) public void startWithNullConfiguration() { new Run().start( createMock( Command...
ConfigurationImpl implements Configuration { public String getProperty( final String key ) { return m_properties.getProperty( key ); } ConfigurationImpl( final String url ); String getProperty( final String key ); @SuppressWarnings( "unchecked" ) String[] getPropertyNames( final String regex ); }
@Test public void constructorWithValidClasspathConfiguration() { Configuration config = new ConfigurationImpl( "classpath:org/ops4j/pax/runner/configuration/runner.properties" ); assertEquals( "platform.test", "org.ops4j.pax.runner.platform.Activator", config.getProperty( "platform.test" ) ); }
ExecutionEnvironment { public String getSystemPackages() { return m_systemPackages; } ExecutionEnvironment( final String ee ); String getSystemPackages(); String getExecutionEnvironment(); static String join( final Collection<String> toJoin, final String delimiter ); }
@Test public void createPackageListWithURLEE() throws Exception { assertEquals( "System packages", "system.package.1,system.package.2", new ExecutionEnvironment( FileUtils.getFileFromClasspath( "platform/systemPackages.profile" ).toURL().toExternalForm() ).getSystemPackages() ); } @Test public void createPackageListNON...
ConfigurationImpl extends PropertyStore implements Configuration { public URL getDefinitionURL() throws MalformedURLException { if( !contains( ServiceConstants.CONFIG_DEFINITION_URL ) ) { final String urlSpec = m_propertyResolver.get( ServiceConstants.CONFIG_DEFINITION_URL ); URL url = null; if( urlSpec != null ) { url...
@Test public void getDefinitionURL() throws MalformedURLException { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.definitionURL" ) ).andReturn( "file:definition.xml" ); replay( propertyResolver ); Configuration config = new Configu...
ConfigurationImpl extends PropertyStore implements Configuration { public String getWorkingDirectory() { if( !contains( ServiceConstants.CONFIG_WORKING_DIRECTORY ) ) { String workDir = m_propertyResolver.get( ServiceConstants.CONFIG_WORKING_DIRECTORY ); if( workDir == null ) { workDir = DEFAULT_WORKING_DIRECTORY; } ret...
@Test public void getWorkingDirectory() throws MalformedURLException { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.workingDirectory" ) ).andReturn( "myWorkingDirectory" ); replay( propertyResolver ); Configuration config = new Co...
ConfigurationImpl extends PropertyStore implements Configuration { public String getSystemPackages() { if( !contains( ServiceConstants.CONFIG_SYSTEM_PACKAGES ) ) { return set( ServiceConstants.CONFIG_SYSTEM_PACKAGES, m_propertyResolver.get( ServiceConstants.CONFIG_SYSTEM_PACKAGES ) ); } return get( ServiceConstants.CON...
@Test public void getSystemPackages() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.systemPackages" ) ).andReturn( "systemPackages" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); ...
ConfigurationImpl extends PropertyStore implements Configuration { public String getExecutionEnvironment() { if( !contains( ServiceConstants.CONFIG_EXECUTION_ENV ) ) { String javaVersion = m_propertyResolver.get( ServiceConstants.CONFIG_EXECUTION_ENV ); if( javaVersion == null ) { javaVersion = "J2SE-" + System.getProp...
@Test public void getExecutionEnvironment() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.ee" ) ).andReturn( "some-ee" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals(...
ConfigurationImpl extends PropertyStore implements Configuration { public String getJavaHome() { if( !contains( ServiceConstants.CONFIG_JAVA_HOME ) ) { String javaHome = m_propertyResolver.get( ServiceConstants.CONFIG_JAVA_HOME ); if( javaHome == null ) { javaHome = System.getProperty( "JAVA_HOME" ); if( javaHome == nu...
@Test public void getJavaHome() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.javaHome" ) ).andReturn( "javaHome" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Jav...
Activator implements BundleActivator { public void start( final BundleContext bundleContext ) throws Exception { NullArgumentException.validateNotNull( bundleContext, "Bundle context" ); m_bundleContext = bundleContext; m_registrations = new HashMap<ServiceReference, ServiceRegistration>(); m_platforms = Collections.sy...
@Test( expected = IllegalArgumentException.class ) public void startWithNullBundleContext() throws Exception { new Activator().start( null ); } @Test public void start() throws Exception { BundleContext context = createMock( BundleContext.class ); expect( context.registerService( eq( ManagedService.class.getName() ), n...
ConfigurationImpl extends PropertyStore implements Configuration { public Integer getProfileStartLevel() { return resolveStartLevel( ServiceConstants.CONFIG_PROFILE_START_LEVEL, DEFAULT_PROFILE_START_LEVEL ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirect...
@Test public void getProfileStartLevel() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.profileStartLevel" ) ).andReturn( "10" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assert...
ConfigurationImpl extends PropertyStore implements Configuration { public Integer getStartLevel() { return resolveStartLevel( ServiceConstants.CONFIG_START_LEVEL, DEFAULT_START_LEVEL ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOp...
@Test public void getStartLevel() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.startLevel" ) ).andReturn( "10" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Platf...