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(); void setContinuous_update(Boolean continuous_update); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }
@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(); floatSlider.setStep(12.1); verifyMsgForProperty(groovyKernel, BoundedFloatWidget.STEP, 12.1); } @Test public void shouldSendCommMsgWhenMaxChange() throws Exception { FloatSlider floatSlider = floatSlider(); floatSlider.setMax(122.3); verifyMsgForProperty(groovyKernel, BoundedFloatWidget.MAX, 122.3); } @Test public void shouldSendCommMsgWhenMinChange() throws Exception { FloatSlider floatSlider = floatSlider(); floatSlider.setMin(10.2); verifyMsgForProperty(groovyKernel, BoundedFloatWidget.MIN, 10.2); }
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 setContinuous_update(Boolean continuous_update); @Override String getModelNameValue(); @Override String getViewNameValue(); static final String VIEW_NAME_VALUE; static final String MODEL_NAME_VALUE; }
@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(true); verifyMsgForProperty(groovyKernel, Widget.DISABLED, true); } @Test public void shouldSendCommMsgWhenVisibleChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setVisible(false); verifyMsgForProperty(groovyKernel, Widget.VISIBLE, false); } @Test public void shouldSendCommMsgWhenDescriptionChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setDescription("Description 2"); verifyMsgForProperty(groovyKernel, Widget.DESCRIPTION, "Description 2"); } @Test public void shouldSendCommMsgWhenMsg_throttleChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setMsg_throttle(12); verifyMsgForProperty(groovyKernel, Widget.MSG_THROTTLE, 12); } @Test public void shouldSendCommMsgWhenStepChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setStep(12); verifyMsgForProperty(groovyKernel, BoundedIntWidget.STEP, 12); } @Test public void shouldSendCommMsgWhenMaxChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setMax(122); verifyMsgForProperty(groovyKernel, BoundedIntWidget.MAX, 122); } @Test public void shouldSendCommMsgWhenMinChange() throws Exception { IntSlider intSlider = intSlider(); intSlider.setMin(10); verifyMsgForProperty(groovyKernel, BoundedIntWidget.MIN, 10); }
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) input); } catch (NumberFormatException e) { } } else if (input instanceof Object[]) { Object[] array = (Object[]) input; if (array.length > 0) { ret = (Integer) getInteger(array[0]); } } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }
@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)); Assertions.assertThat(value.intValue()).isEqualTo(123); } @Test public void getIntegerWithIntegerParam_returnInteger() throws Exception { Integer value = valueWidget.getInteger(new Integer(123)); Assertions.assertThat(value.intValue()).isEqualTo(123); } @Test public void getIntegerWithArrayParam_returnInteger() throws Exception { Integer value = valueWidget.getInteger(new Integer[]{123, 234}); Assertions.assertThat(value.intValue()).isEqualTo(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) input); } catch (NumberFormatException e) { } } else if (input instanceof Object[]) { Object[] array = (Object[]) input; if (array.length > 0) { ret = (Double) getDouble(array[0]); } } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }
@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)); Assertions.assertThat(value.doubleValue()).isEqualTo(123d); } @Test public void getDoubleWithIntegerParam_returnDouble() throws Exception { Double value = valueWidget.getDouble(new Double(123d)); Assertions.assertThat(value.doubleValue()).isEqualTo(123d); } @Test public void getDoubleWithArrayParam_returnDouble() throws Exception { Double value = valueWidget.getDouble(new Double[]{123d, 234d}); Assertions.assertThat(value.doubleValue()).isEqualTo(123d); }
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) { ret[0] = (Integer) getInteger(array[0]); } else if (array.length > 1) { ret[0] = (Integer) getInteger(array[0]); ret[1] = (Integer) getInteger(array[1]); } } else if (input instanceof Collection<?>) { Collection<?> coll = (Collection<?>) input; if (coll.size() == 1) { ret[0] = (Integer) getInteger(coll.toArray()[0]); } else if (coll.size() > 1) { ret[0] = (Integer) getInteger(coll.toArray()[0]); ret[1] = (Integer) getInteger(coll.toArray()[1]); } } else { ret[0] = getInteger(input); } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }
@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 Exception { Integer[] value = valueWidget.getArrayOfInteger(new String[]{"1"}, 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(6); } @Test public void getArrayOfIntegerWithTwoValueArrayParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(new String[]{"1", "2"}, 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(2); } @Test public void getArrayOfIntegerWithOneValueListParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(Arrays.asList("1"), 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(6); } @Test public void getArrayOfIntegerWithTwoValueListParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger(Arrays.asList("1", "2"), 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(2); } @Test public void getArrayOfIntegerWithStringParam_returnArray() throws Exception { Integer[] value = valueWidget.getArrayOfInteger("1", 5, 6); Assertions.assertThat(value[0]).isEqualTo(1); Assertions.assertThat(value[1]).isEqualTo(6); }
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 resetEnvironment(); @Override void exit(); @Override void setShellOptions(final KernelParameters kernelParameters); @Override void evaluate(SimpleEvaluationObject seo, String code); @Override AutocompleteResult autocomplete(String code, int caretPosition); }
@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()); javaEvaluator.evaluate(seo, code); waitForResult(seo); Assertions.assertThat(seo.getStatus()).isEqualTo(FINISHED); Assertions.assertThat(seo.getPayload() instanceof Plot).isTrue(); Assertions.assertThat(((Plot)seo.getPayload()).getTitle()).isEqualTo("test title"); } @Test public void evaluateDivisionByZero_shouldReturnArithmeticException() throws Exception { String code = "return 16/0;"; SimpleEvaluationObject seo = new SimpleEvaluationObject(code, new ExecuteCodeCallbackTest()); javaEvaluator.evaluate(seo, code); waitForResult(seo); Assertions.assertThat(seo.getStatus()).isEqualTo(ERROR); Assertions.assertThat((String)seo.getPayload()).contains("java.lang.ArithmeticException"); }
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[0] = (Double) getDouble(array[0]); } else if (array.length > 1) { ret[0] = (Double) getDouble(array[0]); ret[1] = (Double) getDouble(array[1]); } } else if (input instanceof Collection<?>) { Collection<?> coll = (Collection<?>) input; if (coll.size() == 1) { ret[0] = (Double) getDouble(coll.toArray()[0]); } else if (coll.size() > 1) { ret[0] = (Double) getDouble(coll.toArray()[0]); ret[1] = (Double) getDouble(coll.toArray()[1]); } } else { ret[0] = getDouble(input); } } return ret; } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }
@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 Exception { Double[] value = valueWidget.getArrayOfDouble(new String[]{"1"}, 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(6d); } @Test public void getArrayOfDoubleWithTwoValueArrayParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(new String[]{"1", "2"}, 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(2d); } @Test public void getArrayOfDoubleWithOneValueListParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(Arrays.asList("1"), 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(6d); } @Test public void getArrayOfDoubleWithTwoValueListParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble(Arrays.asList("1", "2"), 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(2d); } @Test public void getArrayOfDoubleWithStringParam_returnArray() throws Exception { Double[] value = valueWidget.getArrayOfDouble("1", 5d, 6d); Assertions.assertThat(value[0]).isEqualTo(1d); Assertions.assertThat(value[1]).isEqualTo(6d); }
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(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }
@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.assertThat(value).isEqualTo("abc"); } @Test public void getStringWithDoubleParam_returnString() throws Exception { String value = valueWidget.getString(new Integer(123)); Assertions.assertThat(value).isEqualTo("123"); } @Test public void getStringWithNullParam_returnEmptyString() throws Exception { String value = valueWidget.getString(null); Assertions.assertThat(value).isEmpty(); }
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> array = (Collection<Object>) input; for (Object o : array) { ret.add(getString(o)); } } else { ret.add(getString(input)); } } return ((ArrayList<String>) ret).stream().toArray(String[]::new); } T getValue(); void setValue(Object value); @Override void updateValue(Object input); abstract T getValueFromObject(Object input); Boolean getDisabled(); void setDisabled(Object disabled); Boolean getVisible(); void setVisible(Object visible); String getDescription(); void setDescription(Object description); Integer getMsg_throttle(); void setMsg_throttle(Object msg_throttle); Integer getInteger(Object input); Double getDouble(Object input); String getString(Object input); String[] getStringArray(Object input); Boolean getBoolean(Object input); }
@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[]{"ab", "cd"}); Assertions.assertThat(value[0]).isEqualTo("ab"); Assertions.assertThat(value[1]).isEqualTo("cd"); } @Test public void getStringArrayWithListParam_returnArray() throws Exception { String[] value = valueWidget.getStringArray(Arrays.asList("ab", "cd")); Assertions.assertThat(value[0]).isEqualTo("ab"); Assertions.assertThat(value[1]).isEqualTo("cd"); } @Test public void getStringArrayWithIntegerParam_returnArray() throws Exception { String[] value = valueWidget.getStringArray(new Integer(123)); Assertions.assertThat(value[0]).isEqualTo("123"); }
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(applicationContext.getBeanNamesForAnnotation(EnableAutoConfiguration.class))); candidateClasses.addAll(Arrays.asList(applicationContext.getBeanNamesForAnnotation(ComponentScan.class))); if (candidateClasses.isEmpty()) { throw new RuntimeException("Is mandatory for the starter have @SpringBootApplication, @EnableAutoConfiguration or @ComponentScan annotation"); } else { return candidateClasses.parallelStream() .map(candidateClazz -> applicationContext.getBean(candidateClazz).getClass().getPackage().getName()) .distinct() .collect(Collectors.toList()); } } static List<String> getApplicationPackageName(final ApplicationContext applicationContext); static Set<Class<?>> getClasses(final String packageName); }
@Test(expected = Exception.class) public void testWhenNoApplicationAnnotation_ShouldReturnAException() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringApplicationAcceptNoSpringBootApplication.class); MorphiaUtils.getApplicationPackageName(context); } @Test public void testCallGetPackageName_ShouldReturnAPackageName() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringApplicationTest.class); List<String> applicationPackageName = MorphiaUtils.getApplicationPackageName(context); assertThat(applicationPackageName.size(), is(1)); assertThat(applicationPackageName.get(0), is("io.github.ganchix.morphia.utils.context.normal")); }
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(final String packageName); }
@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.getClasses("io.github.ganchix.morphia.utils.context.normal.NotClass.class"); }
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(Element element, Type typeOfT); PickAdapter<T> getAdapter(Class<T> type); @SuppressWarnings("unchecked") PickAdapter<T> getAdapter(TypeToken<T> type); }
@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.close(); } } private NoticesXmlParser(); static Notices parse(final InputStream 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?", trimmedLicense)); } } private LicenseResolver(); static void registerLicense(final License license); static License read(final String license); }
@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", license.getName()); }
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 XPathRecordReader addField(String name, String xpath, boolean multiValued, int flags); List<Map<String, Object>> getAllRecords(Reader r); void streamRecords(Reader r, Handler handler); static final int FLATTEN; }
@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 was expected: 'b' xpaths must begin with '/'."); } catch (RuntimeException ex) { } }
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 parameter "); } String s = l.get(0).toString(); return s.replaceAll("'", "''").replaceAll("\"", "\"\"").replaceAll("\\\\", "\\\\\\\\"); } }; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }
@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 parameter "); } String s = l.get(0).toString(); try { return URLEncoder.encode(s.toString(), "UTF-8"); } catch (Exception e) { wrapAndThrow(SEVERE, e, "Unable to encode expression: " + expression + " with value: " + s); return null; } } }; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }
@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(); while (true) { sb.append(ss[i]); if (ss[i].endsWith("'")) break; i++; if (i >= ss.length) throw new DataImportHandlerException(SEVERE, "invalid string at " + ss[i - 1] + " in function params: " + expression); sb.append(","); } String s = sb.substring(1, sb.length() - 1); s = s.replaceAll("\\\\'", "'"); result.add(s); } else { if (Character.isDigit(ss[i].charAt(0))) { try { Double doub = Double.parseDouble(ss[i]); result.add(doub); } catch (NumberFormatException e) { if (vr.resolve(ss[i]) == null) { wrapAndThrow( SEVERE, e, "Invalid number :" + ss[i] + "in parameters " + expression); } } } else { result.add(new VariableWrapper(ss[i], vr)); } } } return result; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }
@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.VariableWrapper)l.get(1)).resolve()); Assert.assertEquals("hello!",l.get(2)); Assert.assertEquals("ds,o,u'za",l.get(3)); }
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, getSqlEscapingEvaluator()); evaluators.put(URL_ENCODE_EVALUATOR, getUrlEvaluator()); evaluators.put(ESCAPE_SOLR_QUERY_CHARS, getSolrQueryEscapingEvaluator()); SolrCore core = docBuilder == null ? null : docBuilder.dataImporter.getCore(); for (Map<String, String> map : fn) { try { evaluators.put(map.get(NAME), (Evaluator) loadClass(map.get(CLASS), core).newInstance()); } catch (Exception e) { wrapAndThrow(SEVERE, e, "Unable to instantiate evaluator: " + map.get(CLASS)); } } return new HashMap<String, Object>() { @Override public String get(Object key) { if (key == null) return null; Matcher m = FORMAT_METHOD.matcher((String) key); if (!m.find()) return null; String fname = m.group(1); Evaluator evaluator = evaluators.get(fname); if (evaluator == null) return null; VariableResolverImpl vri = VariableResolverImpl.CURRENT_VARIABLE_RESOLVER.get(); return evaluator.evaluate(m.group(2), Context.CURRENT_CONTEXT.get()); } }; } static Evaluator getSqlEscapingEvaluator(); static Evaluator getSolrQueryEscapingEvaluator(); static Evaluator getUrlEvaluator(); static Evaluator getDateFormatEvaluator(); static List parseParams(String expression, VariableResolver vr); static final String DATE_FORMAT_EVALUATOR; static final String URL_ENCODE_EVALUATOR; static final String ESCAPE_SOLR_QUERY_CHARS; static final String SQL_ESCAPE_EVALUATOR; }
@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"); resolver.addNamespace("dataimporter.functions", EvaluatorBag .getFunctionsNamespace(Collections.EMPTY_LIST, null)); resolver.addNamespace("e",m); String s = resolver .replaceTokens("${dataimporter.functions.escapeQueryChars(e.query)}"); org.junit.Assert.assertEquals("c\\:t", s); } finally { Context.CURRENT_CONTEXT.remove(); } }
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 = new Locale(customLocale); } String fmt = map.get(DATE_TIME_FMT); if (fmt == null) continue; String column = map.get(DataImporter.COLUMN); String srcCol = map.get(RegexTransformer.SRC_COL_NAME); if (srcCol == null) srcCol = column; try { Object o = aRow.get(srcCol); if (o instanceof List) { List inputs = (List) o; List<Date> results = new ArrayList<Date>(); for (Object input : inputs) { results.add(process(input, fmt, locale)); } aRow.put(column, results); } else { if (o != null) { aRow.put(column, process(o, fmt, locale)); } } } catch (ParseException e) { LOG.warn("Could not parse a Date field ", e); } } return aRow; } @SuppressWarnings("unchecked") Object transformRow(Map<String, Object> aRow, Context context); static final String DATE_TIME_FMT; }
@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", RegexTransformer.SRC_COL_NAME, "lastModified", DateFormatTransformer.DATE_TIME_FMT, "MM/dd/yyyy")); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); Date now = format.parse(format.format(new Date())); Map row = AbstractDataImportHandlerTestCase.createMap("lastModified", format .format(now)); VariableResolverImpl resolver = new VariableResolverImpl(); resolver.addNamespace("e", row); Context context = AbstractDataImportHandlerTestCase.getContext(null, resolver, null, Context.FULL_DUMP, fields, null); new DateFormatTransformer().transformRow(row, context); Assert.assertEquals(now, row.get("dateAdded")); } @Test @SuppressWarnings("unchecked") public void testTransformRow_MultipleRows() throws Exception { List fields = new ArrayList(); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "lastModified")); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "dateAdded", RegexTransformer.SRC_COL_NAME, "lastModified", DateFormatTransformer.DATE_TIME_FMT, "MM/dd/yyyy hh:mm:ss.SSS")); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS"); Date now1 = format.parse(format.format(new Date())); Date now2 = format.parse(format.format(new Date())); Map row = new HashMap(); List list = new ArrayList(); list.add(format.format(now1)); list.add(format.format(now2)); row.put("lastModified", list); VariableResolverImpl resolver = new VariableResolverImpl(); resolver.addNamespace("e", row); Context context = AbstractDataImportHandlerTestCase.getContext(null, resolver, null, Context.FULL_DUMP, fields, null); new DateFormatTransformer().transformRow(row, context); List output = new ArrayList(); output.add(now1); output.add(now2); Assert.assertEquals(output, row.get("dateAdded")); }
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 core != null ? core.getResourceLoader().findClass(n) : Class.forName(n); } catch (Exception e1) { throw new ClassNotFoundException("Unable to load " + name + " or " + DocBuilder.class.getPackage().getName() + "." + name, e); } } } DocBuilder(DataImporter dataImporter, SolrWriter writer, DataImporter.RequestParams reqParams); VariableResolverImpl getVariableResolver(); @SuppressWarnings("unchecked") void execute(); @SuppressWarnings("unchecked") void addStatusMessage(String msg); @SuppressWarnings("unchecked") Set<Map<String, Object>> collectDelta(DataConfig.Entity entity, VariableResolverImpl resolver, Set<Map<String, Object>> deletedRows); void abort(); public Statistics importStatistics; static final String TIME_ELAPSED; static final String LAST_INDEX_TIME; static final String INDEX_START_TIME; }
@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.replaceTokens(field.get(REGEX)); String splitBy = ctx.replaceTokens(field.get(SPLIT_BY)); String replaceWith = ctx.replaceTokens(field.get(REPLACE_WITH)); String groupNames = ctx.replaceTokens(field.get(GROUP_NAMES)); if (reStr != null || splitBy != null) { String srcColName = field.get(SRC_COL_NAME); if (srcColName == null) { srcColName = col; } Object tmpVal = row.get(srcColName); if (tmpVal == null) continue; if (tmpVal instanceof List) { List<String> inputs = (List<String>) tmpVal; List results = new ArrayList(); Map<String,List> otherVars= null; for (String input : inputs) { Object o = process(col, reStr, splitBy, replaceWith, input, groupNames); if (o != null){ if (o instanceof Map) { Map map = (Map) o; for (Object e : map.entrySet()) { Map.Entry<String ,Object> entry = (Map.Entry<String, Object>) e; List l = results; if(!col.equals(entry.getKey())){ if(otherVars == null) otherVars = new HashMap<String, List>(); l = otherVars.get(entry.getKey()); if(l == null){ l = new ArrayList(); otherVars.put(entry.getKey(), l); } } if (entry.getValue() instanceof Collection) { l.addAll((Collection) entry.getValue()); } else { l.add(entry.getValue()); } } } else { if (o instanceof Collection) { results.addAll((Collection) o); } else { results.add(o); } } } } row.put(col, results); if(otherVars != null) row.putAll(otherVars); } else { String value = tmpVal.toString(); Object o = process(col, reStr, splitBy, replaceWith, value, groupNames); if (o != null){ if (o instanceof Map) { row.putAll((Map) o); } else{ row.put(col, o); } } } } } return row; } @SuppressWarnings("unchecked") Map<String, Object> transformRow(Map<String, Object> row, Context ctx); static final String REGEX; static final String REPLACE_WITH; static final String SPLIT_BY; static final String SRC_COL_NAME; static final String GROUP_NAMES; }
@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<String, Object>(); src.put("a", "a,bb,cc,d"); Map<String, Object> result = new RegexTransformer().transformRow(src, context); Assert.assertEquals(2, result.size()); Assert.assertEquals(4, ((List) result.get("col1")).size()); } @Test public void groupNames() { List<Map<String, String>> fields = new ArrayList<Map<String, String>>(); Map<String ,String > m = new HashMap<String, String>(); m.put(COLUMN,"fullName"); m.put(GROUP_NAMES,",firstName,lastName"); m.put(REGEX,"(\\w*) (\\w*) (\\w*)"); fields.add(m); Context context = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, fields, null); Map<String, Object> src = new HashMap<String, Object>(); src.put("fullName", "Mr Noble Paul"); Map<String, Object> result = new RegexTransformer().transformRow(src, context); Assert.assertEquals("Noble", result.get("firstName")); Assert.assertEquals("Paul", result.get("lastName")); src= new HashMap<String, Object>(); List<String> l= new ArrayList(); l.add("Mr Noble Paul") ; l.add("Mr Shalin Mangar") ; src.put("fullName", l); result = new RegexTransformer().transformRow(src, context); List l1 = (List) result.get("firstName"); List l2 = (List) result.get("lastName"); Assert.assertEquals("Noble", l1.get(0)); Assert.assertEquals("Shalin", l1.get(1)); Assert.assertEquals("Paul", l2.get(0)); Assert.assertEquals("Mangar", l2.get(1)); } @Test public void replaceWith() { List<Map<String, String>> fields = new ArrayList<Map<String, String>>(); Map<String, String> fld = getField("name", "string", "'", null, null); fld.put(REPLACE_WITH, "''"); fields.add(fld); Context context = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, fields, null); Map<String, Object> src = new HashMap<String, Object>(); String s = "D'souza"; src.put("name", s); Map<String, Object> result = new RegexTransformer().transformRow(src, context); Assert.assertEquals("D''souza", result.get("name")); } @Test public void mileage() { List<Map<String, String>> fields = getFields(); Map<String, String> fld = getField("hltCityMPG", "string", ".*(${e.city_mileage})", "rowdata", null); fld.put(REPLACE_WITH, "*** $1 ***"); fields.add(fld); fld = getField("t1", "string","duff", "rowdata", null); fields.add(fld); fld = getField("t2", "string","duff", "rowdata", null); fld.put(REPLACE_WITH, "60"); fields.add(fld); fld = getField("t3", "string","(Range)", "rowdata", null); fld.put(REPLACE_WITH, "range"); fld.put(GROUP_NAMES,"t4,t5"); fields.add(fld); Map<String, Object> row = new HashMap<String, Object>(); String s = "Fuel Economy Range: 26 mpg Hwy, 19 mpg City"; row.put("rowdata", s); VariableResolverImpl resolver = new VariableResolverImpl(); resolver.addNamespace("e", row); Map<String, String> eAttrs = AbstractDataImportHandlerTestCase.createMap("name", "e"); Context context = AbstractDataImportHandlerTestCase.getContext(null, resolver, null, Context.FULL_DUMP, fields, eAttrs); Map<String, Object> result = new RegexTransformer().transformRow(row, context); Assert.assertEquals(5, result.size()); Assert.assertEquals(s, result.get("rowdata")); Assert.assertEquals("26", result.get("highway_mileage")); Assert.assertEquals("19", result.get("city_mileage")); Assert.assertEquals("*** 19 *** mpg City", result.get("hltCityMPG")); Assert.assertEquals("Fuel Economy range: 26 mpg Hwy, 19 mpg City", result.get("t3")); } @Test public void testMultiValuedRegex(){ List<Map<String, String>> fields = new ArrayList<Map<String, String>>(); Map<String, String> fld = getField("participant", null, "(.*)", "person", null); fields.add(fld); Context context = getContext(null, null, null, Context.FULL_DUMP, fields, null); ArrayList<String> strings = new ArrayList<String>(); strings.add("hello"); strings.add("world"); Map<String, Object> result = new RegexTransformer().transformRow(createMap("person", strings), context); Assert.assertEquals(strings,result.get("participant")); }
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.setProperty(TestVariableResolver.class.getName(),"hello"); HashMap m = new HashMap(); m.put("hello","world"); VariableResolverImpl vri = new VariableResolverImpl(m); Object val = vri.resolve(TestVariableResolver.class.getName()); Assert.assertEquals("hello", val); Assert.assertEquals("world",vri.resolve("hello")); } @Test public void testNestedNamespace() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace("hello", ns); ns = new HashMap<String, Object>(); ns.put("world1", "WORLD1"); vri.addNamespace("hello.my", ns); Assert.assertEquals("WORLD1", vri.resolve("hello.my.world1")); } @Test public void test3LevelNestedNamespace() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace("hello", ns); ns = new HashMap<String, Object>(); ns.put("world1", "WORLD1"); vri.addNamespace("hello.my.new", ns); Assert.assertEquals("WORLD1", vri.resolve("hello.my.new.world1")); } @Test public void testDefaultNamespace() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace(null, ns); Assert.assertEquals("WORLD", vri.resolve("world")); } @Test public void testDefaultNamespace1() { VariableResolverImpl vri = new VariableResolverImpl(); Map<String, Object> ns = new HashMap<String, Object>(); ns.put("world", "WORLD"); vri.addNamespace(null, ns); Assert.assertEquals("WORLD", vri.resolve("world")); }
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> nextModifiedParentRowKey(); Map<String, Object> nextRow(); void destroy(); static final String TRANSFORMER; static final String TRANSFORM_ROW; static final String ON_ERROR; static final String ABORT; static final String CONTINUE; static final String SKIP; static final String SKIP_DOC; static final String CACHE_KEY; static final String CACHE_LOOKUP; }
@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", null, null, null, null)); fields.add(TestRegexTransformer.getField("B", null, null, null, null)); Context context = AbstractDataImportHandlerTestCase.getContext(null, null, new MockDataSource(), Context.FULL_DUMP, fields, entity); Map<String, Object> src = new HashMap<String, Object>(); src.put("A", "NA"); src.put("B", "NA"); EntityProcessorWrapper sep = new EntityProcessorWrapper(new SqlEntityProcessor(), null); sep.init(context); Map<String, Object> res = sep.applyTransformer(src); Assert.assertNotNull(res.get("T1")); Assert.assertNotNull(res.get("T2")); Assert.assertNotNull(res.get("T3")); }
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(DataImporter.COLUMN); String srcCol = fld.get(RegexTransformer.SRC_COL_NAME); Locale locale = null; String localeStr = context.replaceTokens(fld.get(LOCALE)); if (srcCol == null) srcCol = column; if (localeStr != null) { Matcher matcher = localeRegex.matcher(localeStr); if (matcher.find() && matcher.groupCount() == 2) { locale = new Locale(matcher.group(1), matcher.group(2)); } else { throw new DataImportHandlerException(DataImportHandlerException.SEVERE, "Invalid Locale specified for field: " + fld); } } else { locale = Locale.getDefault(); } Object val = row.get(srcCol); String styleSmall = style.toLowerCase(Locale.ENGLISH); if (val instanceof List) { List<String> inputs = (List) val; List results = new ArrayList(); for (String input : inputs) { try { results.add(process(input, styleSmall, locale)); } catch (ParseException e) { throw new DataImportHandlerException( DataImportHandlerException.SEVERE, "Failed to apply NumberFormat on column: " + column, e); } } row.put(column, results); } else { if (val == null || val.toString().trim().equals("")) continue; try { row.put(column, process(val.toString(), styleSmall, locale)); } catch (ParseException e) { throw new DataImportHandlerException( DataImportHandlerException.SEVERE, "Failed to apply NumberFormat on column: " + column, e); } } } } return row; } @SuppressWarnings("unchecked") Object transformRow(Map<String, Object> row, Context context); static final String FORMAT_STYLE; static final String LOCALE; static final String NUMBER; static final String PERCENT; static final String INTEGER; static final String CURRENCY; }
@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, NumberFormatTransformer.NUMBER)); l.add(AbstractDataImportHandlerTestCase.createMap("column", "localizedNum", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.NUMBER, NumberFormatTransformer.LOCALE, "de-DE")); Context c = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, l, null); Map m = AbstractDataImportHandlerTestCase.createMap("num", "123" + GROUPING_SEP + "567", "localizedNum", "123" + GERMAN_GROUPING_SEP + "567"); new NumberFormatTransformer().transformRow(m, c); Assert.assertEquals(new Long(123567), m.get("num")); Assert.assertEquals(new Long(123567), m.get("localizedNum")); } @Test @SuppressWarnings("unchecked") public void testTransformRow_MultipleNumbers() throws Exception { List fields = new ArrayList(); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "inputs")); fields.add(AbstractDataImportHandlerTestCase.createMap(DataImporter.COLUMN, "outputs", RegexTransformer.SRC_COL_NAME, "inputs", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.NUMBER)); List inputs = new ArrayList(); inputs.add("123" + GROUPING_SEP + "567"); inputs.add("245" + GROUPING_SEP + "678"); Map row = AbstractDataImportHandlerTestCase.createMap("inputs", inputs); VariableResolverImpl resolver = new VariableResolverImpl(); resolver.addNamespace("e", row); Context context = AbstractDataImportHandlerTestCase.getContext(null, resolver, null, Context.FULL_DUMP, fields, null); new NumberFormatTransformer().transformRow(row, context); List output = new ArrayList(); output.add(new Long(123567)); output.add(new Long(245678)); Map outputRow = AbstractDataImportHandlerTestCase.createMap("inputs", inputs, "outputs", output); Assert.assertEquals(outputRow, row); } @Test(expected = DataImportHandlerException.class) @SuppressWarnings("unchecked") public void testTransformRow_InvalidInput1_Number() { List l = new ArrayList(); l.add(AbstractDataImportHandlerTestCase.createMap("column", "num", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.NUMBER)); Context c = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, l, null); Map m = AbstractDataImportHandlerTestCase.createMap("num", "123" + GROUPING_SEP + "5a67"); new NumberFormatTransformer().transformRow(m, c); } @Test(expected = DataImportHandlerException.class) @SuppressWarnings("unchecked") public void testTransformRow_InvalidInput2_Number() { List l = new ArrayList(); l.add(AbstractDataImportHandlerTestCase.createMap("column", "num", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.NUMBER)); Context c = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, l, null); Map m = AbstractDataImportHandlerTestCase.createMap("num", "123" + GROUPING_SEP + "567b"); new NumberFormatTransformer().transformRow(m, c); } @Test(expected = DataImportHandlerException.class) @SuppressWarnings("unchecked") public void testTransformRow_InvalidInput2_Currency() { List l = new ArrayList(); l.add(AbstractDataImportHandlerTestCase.createMap("column", "num", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.CURRENCY)); Context c = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, l, null); Map m = AbstractDataImportHandlerTestCase.createMap("num", "123" + GROUPING_SEP + "567b"); new NumberFormatTransformer().transformRow(m, c); } @Test(expected = DataImportHandlerException.class) @SuppressWarnings("unchecked") public void testTransformRow_InvalidInput1_Percent() { List l = new ArrayList(); l.add(AbstractDataImportHandlerTestCase.createMap("column", "num", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.PERCENT)); Context c = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, l, null); Map m = AbstractDataImportHandlerTestCase.createMap("num", "123" + GROUPING_SEP + "5a67"); new NumberFormatTransformer().transformRow(m, c); } @Test(expected = DataImportHandlerException.class) @SuppressWarnings("unchecked") public void testTransformRow_InvalidInput3_Currency() { List l = new ArrayList(); l.add(AbstractDataImportHandlerTestCase.createMap("column", "num", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.CURRENCY)); Context c = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, l, null); Map m = AbstractDataImportHandlerTestCase.createMap( "num", "123" + DECIMAL_SEP + "456" + DECIMAL_SEP + "789"); new NumberFormatTransformer().transformRow(m, c); } @Test(expected = DataImportHandlerException.class) @SuppressWarnings("unchecked") public void testTransformRow_InvalidInput3_Number() { List l = new ArrayList(); l.add(AbstractDataImportHandlerTestCase.createMap("column", "num", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.NUMBER)); Context c = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, l, null); Map m = AbstractDataImportHandlerTestCase.createMap( "num", "123" + DECIMAL_SEP + "456" + DECIMAL_SEP + "789"); new NumberFormatTransformer().transformRow(m, c); } @Test @SuppressWarnings("unchecked") public void testTransformRow_MalformedInput_Number() { List l = new ArrayList(); l.add(AbstractDataImportHandlerTestCase.createMap("column", "num", NumberFormatTransformer.FORMAT_STYLE, NumberFormatTransformer.NUMBER)); Context c = AbstractDataImportHandlerTestCase.getContext(null, null, null, Context.FULL_DUMP, l, null); Map m = AbstractDataImportHandlerTestCase.createMap( "num", "123" + GROUPING_SEP + GROUPING_SEP + "789"); new NumberFormatTransformer().transformRow(m, c); Assert.assertEquals(new Long(123789), m.get("num")); }
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()) { script = new Script(n.get(0)); } n = getChildNodes(e, FUNCTION); if (!n.isEmpty()) { for (Element element : n) { String func = getStringAttribute(element, NAME, null); String clz = getStringAttribute(element, CLASS, null); if (func == null || clz == null){ throw new DataImportHandlerException( SEVERE, "<function> must have a 'name' and 'class' attributes"); } else { functions.add(getAllAttributes(element)); } } } n = getChildNodes(e, DATA_SRC); if (!n.isEmpty()) { for (Element element : n) { Properties p = new Properties(); HashMap<String, String> attrs = getAllAttributes(element); for (Map.Entry<String, String> entry : attrs.entrySet()) { p.setProperty(entry.getKey(), entry.getValue()); } dataSources.put(p.getProperty("name"), p); } } if(dataSources.get(null) == null){ for (Properties properties : dataSources.values()) { dataSources.put(null,properties); break; } } } void readFromXml(Element e); static String getTxt(Node elem, StringBuilder buffer); static List<Element> getChildNodes(Element e, String byName); void clearCaches(); public Document document; public List<Map<String, String >> functions; public Script script; public Map<String, Properties> dataSources; public Map<String, SchemaField> lowerNameVsSchemaField; static final String SCRIPT; static final String NAME; static final String PROCESSOR; @Deprecated static final String IMPORTER_NS; static final String IMPORTER_NS_SHORT; static final String ROOT_ENTITY; static final String FUNCTION; static final String CLASS; static final String DATA_SRC; }
@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("atrimlisting", dc.document.entities.get(0).name); }
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(TEMPLATE); if (expr == null) continue; String column = map.get(DataImporter.COLUMN); boolean resolvable = true; List<String> variables = getVars(expr); for (String v : variables) { if (resolver.resolve(v) == null) { LOG.warn("Unable to resolve variable: " + v + " while parsing expression: " + expr); resolvable = false; } } if (!resolvable) continue; if(variables.size() == 1 && expr.startsWith("${") && expr.endsWith("}")){ row.put(column, resolver.resolve(variables.get(0))); } else { row.put(column, resolver.replaceTokens(expr)); } } return row; } @SuppressWarnings("unchecked") Object transformRow(Map<String, Object> row, Context context); static final String TEMPLATE; }
@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("column", "middleName")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "name", TemplateTransformer.TEMPLATE, "${e.lastName}, ${e.firstName} ${e.middleName}")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "emails", TemplateTransformer.TEMPLATE, "${e.mail}")); fields.add(AbstractDataImportHandlerTestCase.createMap("column", "mrname", TemplateTransformer.TEMPLATE,"Mr ${e.name}")); List<String> mails = Arrays.asList(new String[]{"[email protected]", "[email protected]"}); Map row = AbstractDataImportHandlerTestCase.createMap( "firstName", "Shalin", "middleName", "Shekhar", "lastName", "Mangar", "mail", mails); VariableResolverImpl resolver = new VariableResolverImpl(); resolver.addNamespace("e", row); Map<String, String> entityAttrs = AbstractDataImportHandlerTestCase.createMap( "name", "e"); Context context = AbstractDataImportHandlerTestCase.getContext(null, resolver, null, Context.FULL_DUMP, fields, entityAttrs); new TemplateTransformer().transformRow(row, context); Assert.assertEquals("Mangar, Shalin Shekhar", row.get("name")); Assert.assertEquals("Mr Mangar, Shalin Shekhar", row.get("mrname")); Assert.assertEquals(mails,row.get("emails")); }
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(URL); final String driver = initProps.getProperty(DRIVER); if (url == null && jndiName == null) throw new DataImportHandlerException(SEVERE, "JDBC URL or JNDI name has to be specified"); if (driver != null) { try { DocBuilder.loadClass(driver, context.getSolrCore()); } catch (ClassNotFoundException e) { wrapAndThrow(SEVERE, e, "Could not load driver: " + driver); } } else { if(jndiName == null){ throw new DataImportHandlerException(SEVERE, "One of driver or jndiName must be specified in the data source"); } } String s = initProps.getProperty("maxRows"); if (s != null) { maxRows = Integer.parseInt(s); } return factory = new Callable<Connection>() { public Connection call() throws Exception { LOG.info("Creating a connection for entity " + context.getEntityAttribute(DataImporter.NAME) + " with URL: " + url); long start = System.currentTimeMillis(); Connection c = null; try { if(url != null){ c = DriverManager.getConnection(url, initProps); } else if(jndiName != null){ InitialContext ctx = new InitialContext(); Object jndival = ctx.lookup(jndiName); if (jndival instanceof javax.sql.DataSource) { javax.sql.DataSource dataSource = (javax.sql.DataSource) jndival; String user = (String) initProps.get("user"); String pass = (String) initProps.get("password"); if(user == null || user.trim().equals("")){ c = dataSource.getConnection(); } else { c = dataSource.getConnection(user, pass); } } else { throw new DataImportHandlerException(SEVERE, "the jndi name : '"+jndiName +"' is not a valid javax.sql.DataSource"); } } } catch (SQLException e) { Driver d = (Driver) DocBuilder.loadClass(driver, context.getSolrCore()).newInstance(); c = d.connect(url, initProps); } if (c != null) { if (Boolean.parseBoolean(initProps.getProperty("readOnly"))) { c.setReadOnly(true); c.setAutoCommit(true); c.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); c.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); } if (!Boolean.parseBoolean(initProps.getProperty("autoCommit"))) { c.setAutoCommit(false); } String transactionIsolation = initProps.getProperty("transactionIsolation"); if ("TRANSACTION_READ_UNCOMMITTED".equals(transactionIsolation)) { c.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); } else if ("TRANSACTION_READ_COMMITTED".equals(transactionIsolation)) { c.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); } else if ("TRANSACTION_REPEATABLE_READ".equals(transactionIsolation)) { c.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); } else if ("TRANSACTION_SERIALIZABLE".equals(transactionIsolation)) { c.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); } else if ("TRANSACTION_NONE".equals(transactionIsolation)) { c.setTransactionIsolation(Connection.TRANSACTION_NONE); } String holdability = initProps.getProperty("holdability"); if ("CLOSE_CURSORS_AT_COMMIT".equals(holdability)) { c.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT); } else if ("HOLD_CURSORS_OVER_COMMIT".equals(holdability)) { c.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT); } } LOG.info("Time taken for getConnection(): " + (System.currentTimeMillis() - start)); return c; } }; } void init(Context context, Properties initProps); Iterator<Map<String, Object>> getData(String query); void close(); static final String URL; static final String JNDI_NAME; static final String DRIVER; static final String CONVERT_TYPE; }
@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, driver.getClass().getName()); props.put(JdbcDataSource.URL, "jdbc:fakedb"); props.put("holdability", "HOLD_CURSORS_OVER_COMMIT"); mockControl.replay(); Connection conn = jdbcDataSource.createConnectionFactory(context, props) .call(); mockControl.verify(); Assert.assertSame("connection", conn, connection); }
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); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
@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(meta2), -1); assertEquals(meta2.compareTo(meta1), 1); }
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.Locale locale); void setTimeZone(ZoneId timeZone); void setFormat(String format); void format(MessageArgs args, StringBuilder buf); static long toLong(CharSequence seq, int pos, int length); }
@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()), "MALE"); assertEquals(format(msg, args().add("gender", "xyz").build()), "OTHER"); } @Test public void testPlural() { String format = "{0 plural =2{is two} one{# is one} few{# is few} many{# is many} other{# is other}}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("1")), "1 is one"); assertEquals(format(msg, args("1.0")), "1.0 is other"); assertEquals(format(msg, args("1.3")), "1.3 is other"); assertEquals(format(msg, args("6")), "6 is other"); msg = new MessageFormat(pl, NY_ZONE, format); assertEquals(format(msg, args("1")), "1 is one"); assertEquals(format(msg, args("2")), "is two"); assertEquals(format(msg, args("3")), "3 is few"); assertEquals(format(msg, args("6")), "6 is many"); assertEquals(format(msg, args("1.0")), "1.0 is other"); assertEquals(format(msg, args("1.3")), "1.3 is other"); } @Test public void testPluralOffset() { String format = "{0, plural, offset:1 " + " =0 {Be the first to like this}" + " =1 {You liked this}" + " one {You and someone else liked this}" + " other {You and # others liked this}" + "}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("0")), "Be the first to like this"); assertEquals(format(msg, args("1")), "You liked this"); assertEquals(format(msg, args("2")), "You and someone else liked this"); assertEquals(format(msg, args("3")), "You and 2 others liked this"); assertEquals(format(msg, args("4")), "You and 3 others liked this"); } @Test public void testOrdinal() { String format = "{0 selectordinal one{#st} two{#nd} few{#rd} other{#th}}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("1")), "1st"); assertEquals(format(msg, args("-2")), "-2nd"); assertEquals(format(msg, args("3")), "3rd"); assertEquals(format(msg, args("-4")), "-4th"); assertEquals(format(msg, args("5")), "5th"); assertEquals(format(msg, args("22")), "22nd"); assertEquals(format(msg, args("34")), "34th"); assertEquals(format(msg, args("101")), "101st"); assertEquals(format(msg, args("103")), "103rd"); assertEquals(format(msg, args("-1047")), "-1047th"); } @Test public void testRecursive() { String format = "{0 plural " + " =1 {# action on {1 datetime date:long}} " + " other {# actions starting on {1 datetime date:long}}" + "}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("1", "1498583746000")), "1 action on June 27, 2017"); assertEquals(format(msg, args("5", "1498583746000")), "5 actions starting on June 27, 2017"); } @Test public void testUnits() { String format = "{0 unit format:long compact:duration in:seconds}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("123456")), "1.4 days"); format = "{0 unit format:long sequence:day,hour in:seconds maxfrac:0}"; msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("123456")), "1 day 10 hours"); msg = new MessageFormat(fr_FR, PARIS_ZONE, format); assertEquals(format(msg, args("123456")), "1 jour 10 heures"); format = "Transmission of {0 unit in:bytes compact:bytes} " + "took {1 unit in:second sequence:hour,minute,second format:long}"; msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("12345678900", "12345")), "Transmission of 11.5GB took 3 hours 25 minutes 45 seconds"); msg = new MessageFormat(fr_FR, PARIS_ZONE, format); assertEquals(format(msg, args("12345678900", "12345")), "Transmission of 11,5 Go took 3 heures 25 minutes 45 secondes"); format = "{0 unit in:inches sequence:mile,foot,inch group}"; msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("123456789")), "1,948mi 2,625′ 9″"); format = "{0 unit in:centimeter sequence:kilometer,meter,centimeter group}"; msg = new MessageFormat(fr_FR, PARIS_ZONE, format); assertEquals(format(msg, args("123456789")), "1 234km 567m 89cm"); } @Test public void testCurrency() { String format = "{0 currency style:name}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args(money("10.25", "USD"))), "10.25 US dollars"); assertEquals(format(msg, args(money("10.25", "EUR"))), "10.25 euros"); msg = new MessageFormat(fr_FR, PARIS_ZONE, format); assertEquals(format(msg, args(money("10.25", "USD"))), "10,25 dollars des États-Unis"); assertEquals(format(msg, args(money("10.25", "EUR"))), "10,25 euros"); format = "{0 currency style:short}"; msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args(money("1234", "USD"))), "$1.2K"); assertEquals(format(msg, args(money("999990", "USD"))), "$1M"); format = "{0 currency style:short mode:significant-maxfrac maxsig:5 minfrac:2}"; msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args(money("1234", "USD"))), "$1.23K"); assertEquals(format(msg, args(money("999990", "USD"))), "$999.99K"); assertEquals(format(msg, args(money("1234", "XYZ"))), ""); } @Test public void testNumber() { String format = "{0 number maxfrac:2}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("3.141592653589793")), "3.14"); format = "{0 number mode:significant maxsig:6}"; msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("3.141592653589793")), "3.14159"); } @Test public void testDateTime() { String format = "{0 datetime date:long time:medium}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("1498583746000")), "June 27, 2017 at 1:15:46 PM"); } @Test public void testMultiTimezones() { String format = "{0 datetime date:long time:medium} ({1 datetime date:long time:medium} UTC)"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args(zoneDateTime("1498583746000", ZoneId.of("America/New_York")), zoneDateTime("1498583746000", ZoneId.of("Etc/UTC")))), "June 27, 2017 at 1:15:46 PM (June 27, 2017 at 5:15:46 PM UTC)"); } @Test public void testDateTimeInterval() { String format = "{0;1 datetime-interval}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("1509647217000", "1510641417000")), "Nov 2 – 14, 2017"); assertEquals(format(msg, args("1502298000000", "1502305200000")), "1:00 – 3:00 PM ET"); msg = new MessageFormat(fr_FR, PARIS_ZONE, format); assertEquals(format(msg, args("1509647217000", "1510641417000")), "2–14 nov. 2017"); assertEquals(format(msg, args("1502298000000", "1502305200000")), "7:00 – 9:00 PM UTC+2"); format = "{0 datetime-interval}"; msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("1509647217000", "1510641417000")), ""); format = "{0;1 datetime-interval yMMMd}"; msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args("1509647217000", "1510641417000")), "Nov 2 – 14, 2017"); assertEquals(format(msg, args("1502298000000", "1502305200000")), "Aug 9, 2017 – Aug 9, 2017"); } @Test public void testIncomplete() { for (String prefix : new String[] { "", " ", "a ", "a }" }) { for (String pattern : INCOMPLETE_PATTERNS) { MessageFormat msg = new MessageFormat(en_US, NY_ZONE, prefix + pattern); assertEquals(format(msg, args("1")), prefix); } } } @Test public void testHideTag() { String format = "{0}{a}{-0}{-a}{}{-}{--}{---}"; MessageFormat msg = new MessageFormat(en_US, NY_ZONE, format); assertEquals(format(msg, args().add("a", "A").build()), "AA{0}{a}{}{-}{--}"); String plural = "0 plural =2{is two} one{# is one} few{# is few} many{# is many} other{# is other}"; format = "{city} {-city} {--city} {state} {-{{state}}} {-" + plural + "}"; msg = new MessageFormat(en_US, NY_ZONE, format); MessageArgs args = args().add("state", "California").add("city", "Los Angeles").build(); assertEquals(format(msg, args), "Los Angeles {city} {-city} California {{{state}}} {" + plural + "}"); }
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 variant); protected MetaLocale(MetaLocale other); String language(); String script(); String territory(); String variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
@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); assertEquals(meta1.hashCode(), meta2.hashCode()); meta2 = new MetaLocale("en", "Latn", null, null); assertNotEquals(meta1, meta2); assertNotEquals(meta1.hashCode(), meta2.hashCode()); }
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, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }
@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 category, Map<Unit, Map<Unit, UnitFactor>> factors); UnitCategory getUnitCategory(); UnitValue convert(UnitValue value, Unit to); UnitValue convert(UnitValue value, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }
@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 Unit[] { Unit.AMPERE, Unit.INCH, Unit.BUSHEL, Unit.MILE }; UnitFactors.LENGTH.sortUnits(units); expected = new Unit[] { Unit.MILE, Unit.INCH, Unit.AMPERE, Unit.BUSHEL }; assertEquals(units, expected); }
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(RoundingMode.HALF_EVEN).toPlainString()).append('\n'); } return buf.toString(); } 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, RoundingMode mode, Unit to); void sortUnits(Unit[] units); List<UnitValue> getFactors(Unit base, Unit...units); List<UnitValue> getFactors(Unit base, RoundingMode mode, Unit...units); UnitFactor get(Unit from, Unit to); String dump(Unit unit); }
@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> factors(); }
@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); } DigitBuffer(); DigitBuffer(int capacity); private DigitBuffer(char[] buf, int size); void reset(); @Override int length(); @Override DigitBuffer subSequence(int start, int end); @Override char charAt(int i); int capacity(); char first(); char last(); DigitBuffer append(String s); void append(DigitBuffer other); DigitBuffer append(char ch); void appendTo(StringBuilder dest); void reverse(int start); @Override String toString(); }
@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); assertEquals(sub.length(), 0); assertEquals(sub.toString(), ""); sub = buf.subSequence(-1, 5); assertEquals(sub.length(), 5); assertEquals(sub.toString(), "abcde"); sub = buf.subSequence(2, 20); assertEquals(sub.length(), 7); assertEquals(sub.toString(), "cdefghi"); sub = buf.subSequence(7, 2); assertEquals(sub.length(), 0); assertEquals(sub.toString(), ""); }
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 formatMode, // formatting mode (significant digits, etc) int minIntDigits, // maximum integer digits to emit int maxFracDigits, // maximum fractional digits to emit int minFracDigits, // minimum fractional digits to emit int maxSigDigits, // maximum significant digits to emit int minSigDigits); static void format( BigDecimal n, DigitBuffer buf, NumberFormatterParams params, boolean currencyMode, boolean grouping, int minIntDigits, int primaryGroupingSize, int secondaryGroupingSize); }
@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 || formatMode == SIGNIFICANT_MAXFRAC; if (useSignificant && minSigDigits > 0 && maxSigDigits > 0) { if (n.precision() > maxSigDigits) { int scale = maxSigDigits - n.precision() + n.scale(); n = n.setScale(scale, mode); } if (formatMode == NumberFormatMode.SIGNIFICANT_MAXFRAC && maxFracDigits < n.scale()) { n = n.setScale(maxFracDigits, mode); } n = n.stripTrailingZeros(); boolean zero = n.signum() == 0; int precision = n.precision(); if (zero && n.scale() == 1) { precision--; } if (precision < minSigDigits) { int scale = minSigDigits - precision + n.scale(); n = n.setScale(scale, mode); } } else { int scale = Math.max(minFracDigits, Math.min(n.scale(), maxFracDigits)); n = n.setScale(scale, mode); n = n.stripTrailingZeros(); if (n.scale() < minFracDigits) { n = n.setScale(minFracDigits, mode); } } return n; } static int integerDigits(BigDecimal n); static BigDecimal setup( BigDecimal n, // number to be formatted NumberRoundMode roundMode, // rounding mode NumberFormatMode formatMode, // formatting mode (significant digits, etc) int minIntDigits, // maximum integer digits to emit int maxFracDigits, // maximum fractional digits to emit int minFracDigits, // minimum fractional digits to emit int maxSigDigits, // maximum significant digits to emit int minSigDigits); static void format( BigDecimal n, DigitBuffer buf, NumberFormatterParams params, boolean currencyMode, boolean grouping, int minIntDigits, int primaryGroupingSize, int secondaryGroupingSize); }
@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", "3"); setup(fmt.get(), "0.1", "0.1"); setup(fmt.get(), "0.999999", "1"); fmt = format(NumberFormatMode.DEFAULT).minFracDigits(1).maxFracDigits(3); setup(fmt.get(), "0", "0.0"); setup(fmt.get(), "0.0", "0.0"); setup(fmt.get(), "1.0", "1.0"); setup(fmt.get(), "1.23004", "1.23"); setup(fmt.get(), "12345", "12345.0"); setup(fmt.get(), "0.12345", "0.123"); setup(fmt.get(), "3.14159", "3.142"); setup(fmt.get(), "0.1", "0.1"); setup(fmt.get(), "0.999999", "1.0"); }
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 = primaryGroupingSize; boolean shouldGroup = false; long intDigits = integerDigits(n); if (minIntDigits == 0 && n.compareTo(BigDecimal.ONE) == -1) { intDigits = 0; } else { intDigits = Math.max(intDigits, minIntDigits); } if (grouping) { if (primaryGroupingSize > 0) { shouldGroup = intDigits >= (params.minimumGroupingDigits + primaryGroupingSize); } } String decimal = currencyMode ? params.currencyDecimal : params.decimal; String group = currencyMode ? params.currencyGroup : params.group; int bufferStart = buf.length(); if (n.signum() == -1) { n = n.negate(); } String s = n.toPlainString(); int end = s.length() - 1; int idx = s.lastIndexOf('.'); if (idx != -1) { while (end > idx) { buf.append(s.charAt(end)); end--; } end--; buf.append(decimal); } int emitted = 0; while (intDigits > 0 && end >= 0) { if (shouldGroup) { boolean emit = emitted > 0 && emitted % groupSize == 0; if (emit) { buf.append(group); emitted -= groupSize; groupSize = secondaryGroupingSize; } } buf.append(s.charAt(end)); end--; emitted++; intDigits--; } if (intDigits > 0) { for (int i = 0; i < intDigits; i++) { if (shouldGroup) { boolean emit = emitted > 0 && emitted % groupSize == 0; if (emit) { buf.append(group); emitted -= groupSize; groupSize = secondaryGroupingSize; } } buf.append('0'); emitted++; } } buf.reverse(bufferStart); } static int integerDigits(BigDecimal n); static BigDecimal setup( BigDecimal n, // number to be formatted NumberRoundMode roundMode, // rounding mode NumberFormatMode formatMode, // formatting mode (significant digits, etc) int minIntDigits, // maximum integer digits to emit int maxFracDigits, // maximum fractional digits to emit int minFracDigits, // minimum fractional digits to emit int maxSigDigits, // maximum significant digits to emit int minSigDigits); static void format( BigDecimal n, DigitBuffer buf, NumberFormatterParams params, boolean currencyMode, boolean grouping, int minIntDigits, int primaryGroupingSize, int secondaryGroupingSize); }
@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).minIntDigits(3); format(fmt.get(), "0", "000"); format(fmt.get(), "1", "001"); format(fmt.get(), "12345", "12345"); format(fmt.get(), "12.6", "012.6"); fmt.minIntDigits(1).maxFracDigits(0); format(fmt.get(), "1", "1"); format(fmt.get(), "1.1", "1"); format(fmt.get(), "1.5", "2"); format(fmt.get(), "0", "0"); format(fmt.get(), "0.1", "0"); format(fmt.get(), "0.5", "0"); format(fmt.get(), "0.6", "1"); format(fmt.get(), "1.4", "1"); format(fmt.get(), "1.5", "2"); format(fmt.get(), "0.0001", "0"); fmt.minFracDigits(1).maxFracDigits(3); format(fmt.get(), "1.20000", "1.2"); format(fmt.get(), "0.0020000", "0.002"); fmt.minFracDigits(3); format(fmt.get(), "1.20000", "1.200"); format(fmt.get(), "0.0020000", "0.002"); fmt.minIntDigits(0); format(fmt.get(), "0.002", ".002"); format(fmt.get(), "0.556", ".556"); format(fmt.get(), "0.66", ".660"); format(fmt.get(), "1.234", "1.234"); format(fmt.get(), "12345", "12345.000"); fmt.minFracDigits(0).maxFracDigits(1); format(fmt.get(), "0.94", ".9"); format(fmt.get(), "0.95", "1"); format(fmt.get(), "0.99", "1"); } @Test public void testGrouping() { Builder fmt = format(DEFAULT).grouping(true); format(fmt.get(), "1234567", "1,234,567"); format(fmt.get(), "11111111111111.123", "11,111,111,111,111.12"); fmt.minimumGroupingDigits(2); format(fmt.get(), "1234", "1234"); format(fmt.get(), "12345", "12,345"); format(fmt.get(), "1234567", "1,234,567"); fmt.primaryGroupingSize(4).secondaryGroupingSize(2); format(fmt.get(), "1234567", "1,23,4567"); format(fmt.get(), "11111111111111.123", "11,11,11,11,11,1111.12"); fmt.minIntDigits(12); format(fmt.get(), "123", "00,00,00,00,0123"); fmt.primaryGroupingSize(3).secondaryGroupingSize(3); format(fmt.get(), "123", "000,000,000,123"); }
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 variant(); static MetaLocale fromLanguageTag(String tag); static MetaLocale fromJavaLocale(java.util.Locale java); String expanded(); String compact(); @Override int compareTo(MetaLocale o); @Override int hashCode(); @Override boolean equals(Object obj); @Override String toString(); }
@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); assertPattern("#,##0\u00a0%", format(3, 0, 1, 0, 0), text(NBSP), PERCENT); assertPattern("#,##,##0%", format(3, 2, 1, 0, 0), PERCENT); assertPattern("-%#,##0", MINUS, PERCENT, format(3, 0, 1, 0, 0)); assertPattern("%\u00a0#,##0", PERCENT, text(NBSP), format(3, 0, 1, 0, 0)); } @Test public void testDecimalLong() { assertPattern("0 billion", format(0, 0, 1, 0, 0), text(" billion")); assertPattern("000 thousand", format(0, 0, 3, 0, 0), text(" thousand")); }
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 == '\'') { inquote = false; field = '\0'; } else { buf.append(ch); } i++; continue; } switch (ch) { case 'G': case 'y': case 'Y': case 'u': case 'U': case 'r': case 'Q': case 'q': case 'M': case 'L': case 'l': case 'w': case 'W': case 'd': case 'D': case 'F': case 'g': case 'E': case 'e': case 'c': case 'a': case 'b': case 'B': case 'h': case 'H': case 'K': case 'k': case 'j': case 'J': case 'C': case 'm': case 's': case 'S': case 'A': case 'z': case 'Z': case 'O': case 'v': case 'V': case 'X': case 'x': if (buf.length() > 0) { nodes.add(new Text(buf.toString())); buf.setLength(0); } if (ch != field) { if (field != '\0') { nodes.add(new Field(field, width)); } field = ch; width = 1; } else { width++; } break; default: if (field != '\0') { nodes.add(new Field(field, width)); } field = '\0'; if (ch == '\'') { inquote = true; } else { buf.append(ch); } break; } i++; } if (width > 0 && field != '\0') { nodes.add(new Field(field, width)); } else if (buf.length() > 0) { nodes.add(new Text(buf.toString())); } return nodes; } Pair<List<Node>, List<Node>> splitIntervalPattern(String raw); static String render(List<Node> nodes); List<Node> parse(String raw); }
@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 (!dst.hasLanguage()) { dst.setLanguage(match._language()); } if (!dst.hasScript()) { dst.setScript(match._script()); } if (!dst.hasTerritory()) { dst.setTerritory(match._territory()); } break; } } return dst; } LanguageResolver(Map<MetaLocale, MetaLocale> likelySubtagsMap); CLDR.Locale matchLanguageTag(String tag); CLDR.Locale matchLocale(java.util.Locale locale); }
@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("es", "es-Latn-ES"); assertMatch("es_ES", "es-Latn-ES"); assertMatch("es_419", "es-Latn-419"); assertMatch("es-Latn-419", "es-Latn-419"); assertMatch("sr", "sr-Cyrl-RS"); assertMatch("sr-Cyrl", "sr-Cyrl-RS"); assertMatch("sr-RS", "sr-Cyrl-RS"); assertMatch("sr-Cyrl-BA", "sr-Cyrl-BA"); assertMatch("sr-Latn", "sr-Latn-RS"); assertMatch("sr_Latn_BA", "sr-Latn-BA"); assertMatch("sr-Latn-RS", "sr-Latn-RS"); assertMatch("sr-Cyrl-XY", "sr-Cyrl-XY"); assertMatch("be", "be-Cyrl-BY"); assertMatch("be-BY", "be-Cyrl-BY"); assertMatch("be-Cyrl-BY", "be-Cyrl-BY"); assertMatch("und-BY", "be-Cyrl-BY"); assertMatch("zh-TW", "zh-Hant-TW"); assertMatch("zh-CN", "zh-Hans-CN"); assertMatch("zh", "zh-Hans-CN"); }
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); Match match(List<String> desired, int threshold); List<Match> matches(String desiredRaw); List<Match> matches(String desiredRaw, int threshold); List<Match> matches(List<String> desired); List<Match> matches(List<String> desired, int threshold); }
@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"); match(asList("en_US", "fr_FR", "und-DE"), asList("zh", "de"), "und-DE"); match(asList("en ar", "de es fr"), asList("no he", "es"), "es"); }
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> desired); Match match(List<String> desired, int threshold); List<Match> matches(String desiredRaw); List<Match> matches(String desiredRaw, int threshold); List<Match> matches(List<String> desired); List<Match> matches(List<String> desired, int threshold); }
@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", "es-AR", "es-MX:4 es:5"); matchlist("es-ES, es-419, es-PT", "es-MX", "es-419:4 es-ES:5 es-PT:5"); matchlist("es-MX, es-419, es-ES", "es-AR", "es-419:4 es-MX:4 es-ES:5"); matchlist("zh-HK, zh-TW, zh", "zh-MO", "zh-HK:4 zh-TW:5 zh:23"); matchlist("en-US", "en-GB", "en-US:3"); matchlist("en-IN", "en-GB", "en-IN:4"); matchlist("en-GB", "en-US", "en-GB:5"); matchlist("en-IN, en-US", "en-GB", "en-US:3 en-IN:4"); matchlist("en-GB, en-US", "en-IN", "en-GB:3 en-US:5"); matchlist("en-GB, en-US", "en-VI", "en-US:4 en-GB:5"); matchlist("en-US, en-GB, en-VI", "en-IN", "en-GB:3 en-US:5 en-VI:5"); matchlist("en-US, en-IN, en-VI", "en-GB", "en-US:3 en-IN:4 en-VI:5"); matchlist("en-IN, en-GB, en-US", "en-VI", "en-US:4 en-GB:5 en-IN:5"); }
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.showNoFileInfos(); } else { mView.showFileInfos(fileInfos); } } }); } FileInfosPresenter(@NonNull FileInfo directory, @NonNull BaseSchedulerProvider schedulerProvider, @NonNull FileInfosContract.View view, @NonNull FileInfosRepository fileInfosRepository); @Override void subscribe(); @Override void unsubscribe(); @Override void loadFileInfos(); }
@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); user = userRepository.save(user); UserRole userRole = new UserRole(user.getId(), UserUtility.ROLE_USER); userRoleRepository.save(userRole); logger.info("new user has been created {}", user.getUsername()); } @Override void create(User user); }
@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 User user = new User("imrenagi", "imrenagi", "imre", "nagi"); user.setId(1L); doReturn(null).when(userRepository).findByUsername(user.getUsername()); doReturn(user).when(userRepository).save(any(User.class)); userService.create(user); verify(userRepository, times(1)).save(any(User.class)); verify(userRoleRepository, times(1)).save(any(UserRole.class)); }
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 UsernameNotFoundException(s); } return user; } @Override UserDetails loadUserByUsername(String s); }
@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(), found.getUsername()); assertEquals(user.getPassword(), found.getPassword()); verify(repository, times(1)).findByUsername(user.getUsername()); } @Test public void shouldFailWhenUserIsNotFound() throws Exception { doReturn(null).when(repository).findByUsername(anyString()); try { userDetailsService.loadUserByUsername(anyString()); fail(); } catch (Exception e) { } }
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); @Override List<Account> findAll(); }
@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)).findByUsername(account.getUsername()); } @Test(expected = IllegalArgumentException.class) public void shouldFailFindByUserNameForEmptyUsername() { accountService.findByUserName(""); }
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<Account> findAll(); }
@Test public void shouldFindByEmail() { final Account account = new Account(); account.setUsername("imrenagi"); account.setEmail("[email protected]"); doReturn(account).when(repository).findByEmail(account.getEmail()); Account found = accountService.findByEmail(account.getEmail()); assertEquals(account, found); verify(repository, times(1)).findByEmail(account.getEmail()); } @Test(expected = IllegalArgumentException.class) public void shouldThrowExceptionWhenFindByEmptyEmail() { accountService.findByEmail(""); }
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 UnsupportedOperationException("Invalid character " + text.charAt(i)); } chars.add(s); } StringBuilder result = new StringBuilder(); String[][] maps = new String[chars.size()][chars.get(0).split("\\n").length]; for (int i = 0; i < chars.size(); i++) { String str = chars.get(i); maps[i] = str.split("\\r?\\n"); } for (int j = 0; j < maps[0].length; j++) { for (int i = 0; i < chars.size(); i++) { result.append(maps[i][j]); } if (j != maps[0].length - 1) { result.append("\n"); } } return result.toString(); } BigFontGenerator(); boolean isLoaded(); void load(InputStream[] inputStream); int getSize(); String convert(String text, int position); }
@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("hello", i); stream.println(convert); System.out.println(convert); } stream.flush(); stream.close(); }
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 IllegalStateException("multiple calls to method 'call'"); } } JavacTaskImpl(Main compilerMain, String[] args, Context context, List<JavaFileObject> fileObjects); JavacTaskImpl(Main compilerMain, Iterable<String> flags, Context context, Iterable<String> classes, Iterable<? extends JavaFileObject> fileObjects); Boolean call(); void setProcessors(Iterable<? extends Processor> processors); void setLocale(Locale locale); JavaFileObject asJavaFileObject(File file); void setTaskListener(TaskListener taskListener); Iterable<? extends CompilationUnitTree> parse(); Iterable<? extends TypeElement> enter(); Iterable<? extends TypeElement> enter(Iterable<? extends CompilationUnitTree> trees); @Override Iterable<? extends Element> analyze(); Iterable<? extends Element> analyze(Iterable<? extends TypeElement> classes); @Override Iterable<? extends JavaFileObject> generate(); Iterable<? extends JavaFileObject> generate(Iterable<? extends TypeElement> classes); TypeMirror getTypeMirror(Iterable<? extends Tree> path); JavacElements getElements(); JavacTypes getTypes(); Iterable<? extends Tree> pathFor(CompilationUnitTree unit, Tree node); Context getContext(); void updateContext(Context newContext); Type parseType(String expr, TypeElement scope); }
@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 (IllegalArgumentException e) { System.out.println("必然会抛IllegalArgumentException异常"); } }
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.setAccessible(true); System.arraycopy(args, 1, newargs, 3, args.length - 1); newargs[0] = "-connect"; newargs[1] = "com.sun.jdi.CommandLineLaunch:options=-esa -ea:com.sun.tools..."; newargs[2] = "com.sun.tools.javac.Main"; method.invoke(null, new Object[] { newargs }); } else { System.exit(compile(args)); } } static void main(String[] args); static int compile(String[] args); static int compile(String[] args, PrintWriter out); }
@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) { e.printStackTrace(); } } @Test public void testMain_Xprint() throws Exception { String[] args = { "-Xprint", "java.lang.String"}; Main.main(args); } @Test public void testMain_X() throws Exception { String[] args = {"-X"}; Main.main(args); } @Test public void testMain_help() throws Exception { String[] args = {"-help"}; Main.main(args); } @Test public void testMain_version() throws Exception { String[] args = {"-version"}; Main.main(args); }
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", null); fileChooser = new JFileChooser(); if (fileName != null) { fileChooser = new JFileChooser(); fileChooser.setSelectedFile(new File(fileName)); } } if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { String fileName = fileChooser.getSelectedFile().getPath(); prefs.put("recent.file", fileName); javac.run( System.in, null, null, "-d", "D:/Workspace/JSE/workspace/Compiler_javac/test-files/class-files", fileName); } } static void main(String... args); }
@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.String"}; Launcher.main(args); }
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 version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }
@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", "resource", new Parser( "resource" ).getResourceName() ); } @Test public void getResourceNameWithLeadingSlash() throws MalformedURLException { assertEquals( "Resource name", "resource", new Parser( "/resource" ).getResourceName() ); }
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, final Configuration configuration ); @Override InputStream getInputStream(); @Override void connect(); }
@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", "jasper-2.5.jar", }; for (String servletName : jasperJarNamesToTest) { assertFalse(AbstractConnection.checkJarIsLegal(servletName)); } }
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 ) ) ); } return get( ServiceConstants.PROPERTY_CERTIFICATE_CHECK ); } ConfigurationImpl( final PropertyResolver propertyResolver ); Boolean getCertificateCheck(); }
@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( "Certificate check", true, config.getCertificateCheck() ); verify( propertyResolver ); } @Test public void getDefaultCertificateCheck() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.url.wrap.certificateCheck" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Certificate check", false, config.getCertificateCheck() ); verify( propertyResolver ); }
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 ); @Override InputStream getInputStream(); void connect(); }
@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.getInputStream(); FunctionalTest.dumpToConsole( inp, 16 ); }
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_SEPARATOR ) .append( m_artifact ) .append( VERSION_SEPARATOR ) .append( getSnapshotVersion( version, timestamp, buildnumber ) ) .append( m_fullClassifier ) .append( TYPE_SEPARATOR ) .append( m_type ) .toString(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }
@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 version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }
@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(); } Parser( final String path ); MavenRepositoryURL getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }
@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(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }
@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 getRepositoryURL(); String getGroup(); String getArtifact(); String getVersion(); String getType(); String getClassifier(); String getArtifactPath(); String getArtifactPath( final String version ); String getSnapshotVersion( final String version, final String timestamp, final String buildnumber ); String getSnapshotPath( final String version, final String timestamp, final String buildnumber ); String getVersionMetadataPath( final String version ); String getVersionLocalMetadataPath( final String version ); String getArtifactLocalMetdataPath(); String getArtifactMetdataPath(); static final String VERSION_LATEST; static final String FILE_SEPARATOR; }
@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 StringBuilder(); boolean snapshotEnabled = false; boolean releasesEnabled = true; boolean multi = false; String name = null; String update = null; String updateReleases = null; String updateSnapshots = null; String checksum = null; String checksumReleases = null; String checksumSnapshots = null; for( int i = 0; i < segments.length; i++ ) { String segment = segments[i].trim(); if( segment.equalsIgnoreCase( ServiceConstants.OPTION_ALLOW_SNAPSHOTS ) ) { snapshotEnabled = true; } else if( segment.equalsIgnoreCase( ServiceConstants.OPTION_DISALLOW_RELEASES ) ) { releasesEnabled = false; } else if( segment.equalsIgnoreCase( ServiceConstants.OPTION_MULTI ) ) { multi = true; } else if( segment.startsWith( ServiceConstants.OPTION_ID + "=" ) ) { try { name = segments[ i ].split( "=" )[1].trim(); } catch (Exception e) { LOG.warn( "Problem with segment " + segments[i] + " in " + repositorySpec ); } } else if( segment.startsWith( ServiceConstants.OPTION_RELEASES_UPDATE + "=" ) ) { try { updateReleases = segments[ i ].split( "=" )[1].trim(); } catch (Exception e) { LOG.warn( "Problem with segment " + segments[i] + " in " + repositorySpec ); } } else if( segment.startsWith( ServiceConstants.OPTION_SNAPSHOTS_UPDATE + "=" ) ) { try { updateSnapshots = segments[ i ].split( "=" )[1].trim(); } catch (Exception e) { LOG.warn( "Problem with segment " + segments[i] + " in " + repositorySpec ); } } else if( segment.startsWith( ServiceConstants.OPTION_UPDATE + "=" ) ) { try { update = segments[ i ].split( "=" )[1].trim(); } catch (Exception e) { LOG.warn( "Problem with segment " + segments[i] + " in " + repositorySpec ); } } else if( segment.startsWith( ServiceConstants.OPTION_RELEASES_CHECKSUM + "=" ) ) { try { checksumReleases = segments[ i ].split( "=" )[1].trim(); } catch (Exception e) { LOG.warn( "Problem with segment " + segments[i] + " in " + repositorySpec ); } } else if( segment.startsWith( ServiceConstants.OPTION_SNAPSHOTS_CHECKSUM + "=" ) ) { try { checksumSnapshots = segments[ i ].split( "=" )[1].trim(); } catch (Exception e) { LOG.warn( "Problem with segment " + segments[i] + " in " + repositorySpec ); } } else if( segment.startsWith( ServiceConstants.OPTION_CHECKSUM + "=" ) ) { try { checksum = segments[ i ].split( "=" )[1].trim(); } catch (Exception e) { LOG.warn( "Problem with segment " + segments[i] + " in " + repositorySpec ); } } else { if( i > 0 ) { urlBuilder.append( ServiceConstants.SEPARATOR_OPTIONS ); } urlBuilder.append( segments[ i ] ); } } String spec = buildSpec( urlBuilder ); m_repositoryURL = new URL( spec ); m_snapshotsEnabled = snapshotEnabled; m_releasesEnabled = releasesEnabled; m_multi = multi; if (name == null) { String warn = "Repository spec " + spec + " does not contain an identifier. Give your repository a name, for example: " + repositorySpec + "@id=MyName"; LOG.warn( warn ); name = "repo_" + spec.hashCode(); } m_id = name; m_releasesUpdatePolicy = updateReleases != null ? updateReleases : update; m_snapshotsUpdatePolicy = updateSnapshots != null ? updateSnapshots : update; m_releasesChecksumPolicy = checksumReleases != null ? checksumReleases : checksum; m_snapshotsChecksumPolicy = checksumSnapshots != null ? checksumSnapshots : checksum; if( m_repositoryURL.getProtocol().equals( "file" ) ) { try { spec = spec.replaceAll( "\\\\", "/" ); spec = spec.replaceAll( " ", "%20" ); URI uri = new URI( spec ); String path = uri.getPath(); if( path == null ) path = uri.getSchemeSpecificPart(); m_file = new File( path ); } catch ( URISyntaxException e ) { throw new MalformedURLException( e.getMessage() ); } } else { m_file = null; } } MavenRepositoryURL( final String repositorySpec ); String getId(); URL getURL(); File getFile(); boolean isReleasesEnabled(); boolean isSnapshotsEnabled(); String getReleasesUpdatePolicy(); String getSnapshotsUpdatePolicy(); String getReleasesChecksumPolicy(); String getSnapshotsChecksumPolicy(); boolean isMulti(); boolean isFileRepository(); @Override String toString(); }
@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() ); localrepo = new File( "myédir/repository" ).getAbsoluteFile(); uri = localrepo.toURI().toASCIIString(); mavenRepo = new MavenRepositoryURL( uri + "@id=repository1" ); assertEquals( localrepo, mavenRepo.getFile() ); String spec = "file:repository1/@id=repository1"; mavenRepo = new MavenRepositoryURL( spec ); assertEquals( new File( "repository1/" ), mavenRepo.getFile() ); spec = "file:repositories/repository1/@id=repository1"; mavenRepo = new MavenRepositoryURL( spec ); assertEquals( new File( "repositories/repository1/" ), mavenRepo.getFile() ); spec = "file:somewhere/localrepository\\"; mavenRepo = new MavenRepositoryURL( spec + "@id=repository1" ); assertEquals( new File( "somewhere/localrepository/" ), mavenRepo.getFile() ); assertEquals( new URL( spec ), mavenRepo.getURL() ); spec = "file:repository1\\"; mavenRepo = new MavenRepositoryURL( spec + "@id=repository1" ); assertEquals( new File( "repository1/" ), mavenRepo.getFile() ); assertEquals( new URL( spec ), mavenRepo.getURL() ); spec = "file:somewhere/localrepository%5C"; mavenRepo = new MavenRepositoryURL( spec + "@id=repository1" ); assertEquals( new URL( spec + "/" ), mavenRepo.getURL() ); spec = "file:repository1%5C"; mavenRepo = new MavenRepositoryURL( spec + "@id=repository1" ); assertEquals( new URL( spec + "/" ), mavenRepo.getURL() ); spec = "file:r%C3%A9positories%20/r%C3%A9pository1"; mavenRepo = new MavenRepositoryURL( spec + "@id=repository1" ); File expected = new File( "répositories /répository1/" ); assertEquals( expected, 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 [" + m_parser.getResourceName() + "] could not be resolved from classpath" ); } return is; } Connection( final URL url, final BundleContext bundleContext ); @Override void connect(); InputStream getInputStream(); static final String PROTOCOL; }
@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, end); double[] sim = mult(m, vector); System.arraycopy(sim, 0, result, i, sim.length); } return result; } static double[] vectorSimilarity(SparseDataset matrix, SparseArray vector); static SparseVector asSparseVector(int ncol, SparseArray vector); static double[] vectorSimilarity(double[][] matrix, double[] vector); static double[] slicedSimilarity(double[][] matrix, double[] vector, int sliceSize); static double[][] matrixSimilarity(SparseDataset d1, SparseDataset d2); static double[][] to2d(DenseMatrix dense); static CompRowMatrix asRowMatrix(SparseDataset dataset); static double[][] l2RowNormalize(double[][] data); static double[] rowWiseDot(double[][] m1, double[][] m2); static double[] rowWiseSparseDot(SparseDataset m1, SparseDataset m2); }
@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, similarity)); } @Test public void slicedSimilarityUneven() { double[][] matrix = { {1, 1}, {1, 2}, {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, }; double[] vector = {0, 1}; int sliceSize = 3; double[] similarity = MatrixUtils.slicedSimilarity(matrix, vector, sliceSize); double[] expected = {1, 2, 3, 4, 5, 6, 7}; assertTrue(Arrays.equals(expected, similarity)); }
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); static double[][] concat(double[][] X1, double[][] X2); static double auc(SoftClassifier<double[]> model, Dataset dataset); static double[] predict(SoftClassifier<double[]> model, Dataset dataset); }
@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 } }; double[][] X2 = { { 0.0, 4.0 }, { 0.0, 5.0 } }; double[][] X = RelevanceModel.concat(X1, X2); double[][] expected = { { 0.0, 1.0 }, { 0.0, 2.0 }, { 0.0, 3.0 }, { 0.0, 4.0 }, { 0.0, 5.0 } }; assertTrue(Arrays.deepEquals(X, expected)); }
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(ner)) { group.add(w); continue; } groups.add(group); group = new ArrayList<>(); group.add(w); prevNer = ner; } groups.add(group); return groups.stream() .filter(l -> !l.isEmpty()) .map(list -> joinLemmas(list)) .collect(Collectors.toList()); } static List<String> groupNer(List<Word> tokens); }
@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"), new Word("in", "in", "_", "O"), new Word("Brooklyn", "Brooklyn", "_", "LOCATION"), new Word(",", ",", "_", "O"), new Word("New", "New", "_", "LOCATION"), new Word("York", "York", "_", "LOCATION"), new Word(".", ".", "_", "O") ); List<String> results = NerGroup.groupNer(tokens); List<String> expected = Arrays.asList("My", "name", "is", "Justin Bieber", "I", "live", "in", "Brooklyn", ",", "New York", "."); assertEquals(expected, results); }
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 void exec( final String[] vmOptions, final String[] classpath, final String mainClass, final String[] programOptions, final String javaHome, final File workingDirectory ); synchronized void exec( final String[] vmOptions, final String[] classpath, final String mainClass, final String[] programOptions, final String javaHome, final File workingDirectory, final String[] envOptions ); void shutdown(); void waitForExit(); }
@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( null ); }
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 PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }
@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.add( "-Dosgi.maxLevel=100" ); vmOptions.add( "-Dxargs=" + context.getFilePathStrategy().normalizeAsPath( new File( new File( workingDirectory, CONFIG_DIRECTORY ), CONFIG_INI ) ) ); final String bootDelegation = context.getConfiguration().getBootDelegation(); if( bootDelegation != null ) { vmOptions.add( "-D" + Constants.FRAMEWORK_BOOTDELEGATION + "=" + bootDelegation ); } return vmOptions.toArray( new String[vmOptions.size()] ); } ConciergePlatformBuilder( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }
@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, "concierge/config.ini" ) ), "-D" + Constants.FRAMEWORK_BOOTDELEGATION + "=javax.*" }, new ConciergePlatformBuilder( m_bundleContext, "version" ).getVMOptions( m_platformContext ) ); verify( m_configuration, m_bundleContext ); } @Test public void getVMOptionsWithoutBootDelegation() { expect( m_configuration.getBootDelegation() ).andReturn( null ); replay( m_configuration, m_bundleContext ); assertArrayEquals( "System options", new String[]{ "-Dosgi.maxLevel=100", "-Dxargs=" + m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "concierge/config.ini" ) ) }, new ConciergePlatformBuilder( m_bundleContext, "version" ).getVMOptions( m_platformContext ) ); verify( m_configuration, m_bundleContext ); } @Test( expected = IllegalArgumentException.class ) public void getSystemPropertiesWithNullPlatformContext() { replay( m_bundleContext ); new ConciergePlatformBuilder( m_bundleContext, "version" ).getVMOptions( null ); verify( m_bundleContext ); }
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 workingDirectory = context.getWorkingDirectory(); final File configDirectory = new File( workingDirectory, CONFIG_DIRECTORY ); configDirectory.mkdirs(); final File configFile = new File( configDirectory, CONFIG_INI ); configFile.createNewFile(); LOGGER.debug( "Create concierge configuration ini file [" + configFile + "]" ); final Configuration configuration = context.getConfiguration(); os = new FileOutputStream( configFile ); final PropertiesWriter writer = new PropertiesWriter( os ); writeHeader( writer ); writer.append( "#############################" ); writer.append( " Concierge settings" ); writer.append( "#############################" ); writer .append( "-D" + Constants.FRAMEWORK_SYSTEMPACKAGES, context.getSystemPackages() ) .append( "-Dch.ethz.iks.concierge.basedir", context.getFilePathStrategy().normalizeAsPath( configDirectory ) ); final Boolean usePersistedState = configuration.usePersistedState(); if( usePersistedState != null && !usePersistedState ) { writer.appendRaw( "-init" ); } final Integer startLevel = configuration.getStartLevel(); if( startLevel != null ) { writer.appendRaw( "-startlevel " + startLevel.toString() ); } final Integer bundleStartLevel = configuration.getBundleStartLevel(); if( bundles != null && bundles.size() > 0 ) { writer.append(); writer.append( "#############################" ); writer.append( " Client bundles to install" ); writer.append( "#############################" ); appendBundles( writer, bundles, context, bundleStartLevel ); } writer.append(); writer.append( "#############################" ); writer.append( " System properties" ); writer.append( "#############################" ); appendProperties( writer, context.getProperties() ); writer.write(); } catch( IOException e ) { throw new PlatformException( "Could not create concierge configuration file", e ); } finally { if( os != null ) { try { os.close(); } catch( IOException e ) { throw new PlatformException( "Could not create concierge configuration file", e ); } } } } ConciergePlatformBuilder( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }
@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 PlatformException, IOException { m_platformContext.setSystemPackages( "sys.package.one,sys.package.two" ); Properties properties = new Properties(); properties.setProperty( "myProperty", "myValue" ); m_platformContext.setProperties( properties ); expect( m_configuration.usePersistedState() ).andReturn( false ); expect( m_configuration.getStartLevel() ).andReturn( null ); expect( m_configuration.getBundleStartLevel() ).andReturn( null ); replay( m_bundleContext, m_configuration ); new ConciergePlatformBuilder( m_bundleContext, "version" ).prepare( m_platformContext ); verify( m_bundleContext, m_configuration ); Map<String, String> replacements = new HashMap<String, String>(); replacements.put( "${basedir.path}", m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "concierge" ) ) ); compareFiles( FileUtils.getFileFromClasspath( "conciergeplatformbuilder/configWithNoBundles.ini" ), new File( m_workDir + "/concierge/config.ini" ), true, replacements ); } @Test public void prepare() throws PlatformException, IOException { List<BundleReference> bundles = new ArrayList<BundleReference>(); BundleReference bundle1 = createMock( BundleReference.class ); bundles.add( bundle1 ); expect( bundle1.getURL() ).andReturn( new File( m_workDir, "bundles/bundle1.jar" ).toURL() ); expect( bundle1.getStartLevel() ).andReturn( 10 ); expect( bundle1.shouldStart() ).andReturn( true ); BundleReference bundle2 = createMock( BundleReference.class ); bundles.add( bundle2 ); expect( bundle2.getURL() ).andReturn( new File( m_workDir, "bundles/bundle2.jar" ).toURL() ); expect( bundle2.getStartLevel() ).andReturn( 10 ); expect( bundle2.shouldStart() ).andReturn( null ); BundleReference bundle3 = createMock( BundleReference.class ); bundles.add( bundle3 ); expect( bundle3.getURL() ).andReturn( new File( m_workDir, "bundles/bundle3.jar" ).toURL() ); expect( bundle3.getStartLevel() ).andReturn( null ); expect( bundle3.shouldStart() ).andReturn( true ); BundleReference bundle4 = createMock( BundleReference.class ); bundles.add( bundle4 ); expect( bundle4.getURL() ).andReturn( new File( m_workDir, "bundles/bundle4.jar" ).toURL() ); expect( bundle4.getStartLevel() ).andReturn( null ); expect( bundle4.shouldStart() ).andReturn( null ); expect( m_configuration.usePersistedState() ).andReturn( true ); expect( m_configuration.getStartLevel() ).andReturn( 10 ); expect( m_configuration.getBundleStartLevel() ).andReturn( 20 ); m_platformContext.setBundles( bundles ); m_platformContext.setSystemPackages( "sys.package.one,sys.package.two" ); Properties properties = new Properties(); properties.setProperty( "myProperty", "myValue" ); m_platformContext.setProperties( properties ); replay( m_bundleContext, m_configuration, bundle1, bundle2, bundle3, bundle4 ); new ConciergePlatformBuilder( m_bundleContext, "version" ).prepare( m_platformContext ); verify( m_bundleContext, m_configuration, bundle1, bundle2, bundle3, bundle4 ); Map<String, String> replacements = new HashMap<String, String>(); replacements.put( "${basedir.path}", m_platformContext.getFilePathStrategy().normalizeAsPath( new File( m_workDir, "concierge" ) ) ); replacements.put( "${bundle1.path}", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "bundles/bundle1.jar" ) ) ); replacements.put( "${bundle2.path}", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "bundles/bundle2.jar" ) ) ); replacements.put( "${bundle3.path}", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "bundles/bundle3.jar" ) ) ); replacements.put( "${bundle4.path}", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "bundles/bundle4.jar" ) ) ); compareFiles( FileUtils.getFileFromClasspath( "conciergeplatformbuilder/config.ini" ), new File( m_workDir + "/concierge/config.ini" ), true, replacements ); }
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 PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }
@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 BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }
@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( m_bundleContext, m_configuration ); } @Test public void getRequiredProfilesWithConsole() { expect( m_configuration.startConsole() ).andReturn( true ); replay( m_bundleContext, m_configuration ); assertEquals( "Required profiles", "tui", new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getRequiredProfile( m_platformContext ) ); verify( m_bundleContext, m_configuration ); }
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 + "]" ); final String mainClassName = m_platformBuilder.getMainClassName(); if ( mainClassName == null || mainClassName.trim().length() == 0 ) { throw new PlatformException( "Main class of the platform cannot be null or empty" ); } final PlatformContext context = mandatory( "Platform context", createPlatformContext() ); context.setProperties( properties ); final Configuration configuration = mandatory( "Configuration", createConfiguration( config ) ); context.setConfiguration( configuration ); final PlatformDefinition definition = mandatory( "Definition", createPlatformDefinition( configuration ) ); LOGGER.debug( "Using platform definition [" + definition + "]" ); final File workDir = mandatory( "Working dir", createWorkingDir( configuration.getWorkingDirectory() ) ); LOGGER.debug( "Using working directory [" + workDir + "]" ); context.setWorkingDirectory( workDir ); if ( configuration.useAbsoluteFilePaths() ) { context.setFilePathStrategy( new AbsoluteFilePathStrategy() ); } else { context.setFilePathStrategy( new RelativeFilePathStrategy( workDir ) ); } final Boolean overwriteBundles = configuration.isOverwrite(); final Boolean overwriteUserBundles = configuration.isOverwriteUserBundles(); final Boolean overwriteSystemBundles = configuration.isOverwriteSystemBundles(); final Boolean downloadFeeback = configuration.isDownloadFeedback(); LOGGER.info( "Downloading bundles..." ); LOGGER.debug( "Download system package" ); final File systemFile = downloadSystemFile( workDir, definition, overwriteBundles || overwriteSystemBundles, downloadFeeback ); LOGGER.debug( "Download additional system libraries" ); final List<LocalSystemFile> localSystemFiles = downloadSystemFiles( workDir, systemFiles, overwriteBundles || overwriteSystemBundles, downloadFeeback ); final List<BundleReference> bundlesToInstall = new ArrayList<BundleReference>(); LOGGER.debug( "Download platform bundles" ); bundlesToInstall.addAll( downloadPlatformBundles( workDir, definition, context, overwriteBundles || overwriteSystemBundles, downloadFeeback, configuration.validateBundles(), configuration.skipInvalidBundles() ) ); LOGGER.debug( "Download bundles" ); bundlesToInstall.addAll( downloadBundles( workDir, bundles, overwriteBundles || overwriteUserBundles, downloadFeeback, configuration.isAutoWrap(), configuration.keepOriginalUrls(), configuration.validateBundles(), configuration.skipInvalidBundles() ) ); context.setBundles( bundlesToInstall ); final ExecutionEnvironment ee = new ExecutionEnvironment( configuration.getExecutionEnvironment() ); context.setSystemPackages( createPackageList( ee.getSystemPackages(), configuration.getSystemPackages(), definition.getPackages() ) ); context.setExecutionEnvironment( ee.getExecutionEnvironment() ); m_platformBuilder.prepare( context ); final CommandLineBuilder vmOptions = new CommandLineBuilder(); vmOptions.append( configuration.getVMOptions() ); vmOptions.append( m_platformBuilder.getVMOptions( context ) ); if ( configuration.keepOriginalUrls() ) { vmOptions.append( "-Djava.protocol.handler.pkgs=org.ops4j.pax.url" ); } final String[] classpath = buildClassPath( systemFile, localSystemFiles, configuration, context ); final CommandLineBuilder programOptions = new CommandLineBuilder(); programOptions.append( m_platformBuilder.getArguments( context ) ); programOptions.append( getFrameworkOptions() ); JavaRunner runner = javaRunner; if ( runner == null ) { runner = new DefaultJavaRunner(); } final String javaHome = configuration.getJavaHome(); LOGGER.debug( "Using " + runner.getClass() + " [" + mainClassName + "]" ); LOGGER.debug( "VM options: [" + Arrays.toString( vmOptions.toArray() ) + "]" ); LOGGER.debug( "Classpath: [" + Arrays.toString( classpath ) + "]" ); LOGGER.debug( "Platform options: [" + Arrays.toString( programOptions.toArray() ) + "]" ); LOGGER.debug( "Java home: [" + javaHome + "]" ); LOGGER.debug( "Working dir: [" + workDir + "]" ); LOGGER.debug( "Environment options: [" + Arrays.toString( configuration.getEnvOptions() ) + "]" ); runner.exec( vmOptions.toArray(), classpath, mainClassName, programOptions.toArray(), javaHome, workDir, configuration.getEnvOptions() ); } PlatformImpl( final PlatformBuilder platformBuilder ); void setResolver( final PropertyResolver propertyResolver ); void start( final List<SystemFileReference> systemFiles, final List<BundleReference> bundles, final Properties properties, @SuppressWarnings("rawtypes") final Dictionary config, final JavaRunner javaRunner ); String toString(); }
@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 public void startWithoutBundlesAndASystemJarThatIsNotBunlde() throws Exception { start( null, FileUtils.getFileFromClasspath( "platform/noManifestAttr.jar" ).toURL() ); } @Test public void startWithBundles() throws Exception { List<BundleReference> bundles = new ArrayList<BundleReference>(); bundles.add( new BundleReferenceBean( FileUtils.getFileFromClasspath( "platform/bundle1.jar" ).toURL() ) ); bundles.add( new BundleReferenceBean( FileUtils.getFileFromClasspath( "platform/bundle2.jar" ).toURL() ) ); start( bundles ); } @Test public void startWithoutBundles() throws Exception { start( null ); } @Test( expected = PlatformException.class ) public void startWithNotAJarBundle() throws Exception { List<BundleReference> bundles = new ArrayList<BundleReference>(); bundles.add( new BundleReferenceBean( FileUtils.getFileFromClasspath( "platform/invalid.jar" ).toURL() ) ); start( bundles ); }
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(), CONFIG_DIRECTORY ), CONFIG_INI ) ) }; } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }
@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" ).getArguments( m_platformContext ) ); verify( m_bundleContext ); }
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(); vmOptions.add( "-Dorg.osgi.framework.dir=" + context.getFilePathStrategy().normalizeAsPath( new File( new File( workingDirectory, CONFIG_DIRECTORY ), CACHE_DIRECTORY ) ) ); return vmOptions.toArray( new String[vmOptions.size()] ); } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }
@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" ).getVMOptions( m_platformContext ) ); verify( m_bundleContext ); } @Test( expected = IllegalArgumentException.class ) public void getSystemPropertiesWithNullPlatformContext() { replay( m_bundleContext ); new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).getVMOptions( null ); verify( m_bundleContext ); }
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 workingDirectory = context.getWorkingDirectory(); final File configDirectory = new File( workingDirectory, CONFIG_DIRECTORY ); configDirectory.mkdirs(); final File configFile = new File( configDirectory, CONFIG_INI ); configFile.createNewFile(); LOGGER.debug( "Create knopflerfish configuration ini file [" + configFile + "]" ); final Configuration configuration = context.getConfiguration(); os = new FileOutputStream( configFile ); final PropertiesWriter writer = new PropertiesWriter( os, SEPARATOR ); writeHeader( writer ); writer.append( "#############################" ); writer.append( " Knopflerfish settings" ); writer.append( "#############################" ); { writer .append( "-Dorg.osgi.provisioning.spid", "knopflerfish" ) .append( "-Dorg.knopflerfish.verbosity", "0" ) .append( "-Doscar.repository.url", "http: .append( "-Dorg.knopflerfish.framework.usingwrapperscript", "false" ) .append( "-Dorg.knopflerfish.framework.exitonshutdown", "true" ) .append( "-Dorg.knopflerfish.framework.debug.packages", "false" ) .append( "-Dorg.knopflerfish.framework.debug.errors", "true" ) .append( "-Dorg.knopflerfish.framework.debug.classloader", "false" ) .append( "-Dorg.knopflerfish.framework.debug.startlevel", "false" ) .append( "-Dorg.knopflerfish.framework.debug.ldap", "false" ) .append( "-Dorg.knopflerfish.startlevel.use", "true" ); } { final File cacheDirectory = new File( configDirectory, CACHE_DIRECTORY ); writer.append( "-Dorg.osgi.framework.storage", context.getFilePathStrategy().normalizeAsPath( cacheDirectory ).replace( File.separatorChar, '/' ) ); } { final Integer startLevel = configuration.getStartLevel(); if( startLevel != null ) { writer.append( "-Dorg.osgi.framework.startlevel.beginning", startLevel.toString() ); } } { final Boolean usePersistedState = configuration.usePersistedState(); if( usePersistedState != null && !usePersistedState ) { writer.append( "-Dorg.osgi.framework.storage.clean", "onFirstInit" ); } } { writer.append( "-D" + Constants.FRAMEWORK_EXECUTIONENVIRONMENT, context.getExecutionEnvironment() ); } { final String bootDelegation = context.getConfiguration().getBootDelegation(); if( bootDelegation != null ) { writer.append( "-D" + Constants.FRAMEWORK_BOOTDELEGATION, bootDelegation ); } } { writer.append( "-Dorg.knopflerfish.framework.system.packages.base", context.getSystemPackages() ); } { final Integer startLevel = configuration.getStartLevel(); if( startLevel != null ) { writer.append(); writer.append( " Framework start level" ); writer.appendRaw( "-startlevel " + startLevel.toString() ); } } { if( bundles != null && bundles.size() > 0 ) { writer.append(); writer.append( "#############################" ); writer.append( " Client bundles to install" ); writer.append( "#############################" ); appendBundles( writer, bundles, context, configuration.getBundleStartLevel() ); } } { writer.append(); writer.append( "#############################" ); writer.append( " System properties" ); writer.append( "#############################" ); appendProperties( writer, context.getProperties() ); } { final Integer bundleStartLevel = configuration.getBundleStartLevel(); if( bundleStartLevel != null ) { writer.append(); writer.append( " Initial bundles start level" ); writer.appendRaw( "-initlevel " + bundleStartLevel.toString() ); } } writer.write(); } catch( IOException e ) { throw new PlatformException( "Could not create knopflerfish configuration file", e ); } finally { if( os != null ) { try { os.close(); } catch( IOException e ) { throw new PlatformException( "Could not create knopflerfish configuration file", e ); } } } } KnopflerfishPlatformBuilderF300( final BundleContext bundleContext, final String version ); void prepare( final PlatformContext context ); String getMainClassName(); String[] getArguments( final PlatformContext context ); String[] getVMOptions( final PlatformContext context ); InputStream getDefinition( final Configuration configuration ); String getRequiredProfile( final PlatformContext context ); String toString(); String getProviderName(); String getProviderVersion(); }
@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 PlatformException, IOException { m_platformContext.setExecutionEnvironment( "EE-1,EE-2" ); m_platformContext.setSystemPackages( "sys.package.one,sys.package.two" ); Properties properties = new Properties(); properties.setProperty( "myProperty", "myValue" ); m_platformContext.setProperties( properties ); expect( m_configuration.usePersistedState() ).andReturn( true ); expect( m_configuration.getBootDelegation() ).andReturn( "javax.*" ); expect( m_configuration.getStartLevel() ).andReturn( null ).anyTimes(); expect( m_configuration.getBundleStartLevel() ).andReturn( null ); replay( m_bundleContext, m_configuration ); new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).prepare( m_platformContext ); verify( m_bundleContext, m_configuration ); compareFiles( FileUtils.getFileFromClasspath( "knopflerfishplatformbuilder/configWithNoBundles300.ini" ), new File( m_workDir + "/knopflerfish/config.ini" ), true, null ); } @Test public void prepare() throws PlatformException, IOException { List<BundleReference> bundles = new ArrayList<BundleReference>(); BundleReference bundle1 = createMock( BundleReference.class ); bundles.add( bundle1 ); expect( bundle1.getURL() ).andReturn( new File( m_workDir, "bundles/bundle1.jar" ).toURL() ); expect( bundle1.getStartLevel() ).andReturn( 10 ); expect( bundle1.shouldStart() ).andReturn( true ); BundleReference bundle2 = createMock( BundleReference.class ); bundles.add( bundle2 ); expect( bundle2.getURL() ).andReturn( new File( m_workDir, "bundles/bundle2.jar" ).toURL() ); expect( bundle2.getStartLevel() ).andReturn( 15 ); expect( bundle2.shouldStart() ).andReturn( null ); BundleReference bundle3 = createMock( BundleReference.class ); bundles.add( bundle3 ); expect( bundle3.getURL() ).andReturn( new File( m_workDir, "bundles/bundle3.jar" ).toURL() ); expect( bundle3.getStartLevel() ).andReturn( null ); expect( bundle3.shouldStart() ).andReturn( true ); BundleReference bundle4 = createMock( BundleReference.class ); bundles.add( bundle4 ); expect( bundle4.getURL() ).andReturn( new File( m_workDir, "bundles/bundle4.jar" ).toURL() ); expect( bundle4.getStartLevel() ).andReturn( 10 ); expect( bundle4.shouldStart() ).andReturn( null ); expect( m_configuration.usePersistedState() ).andReturn( false ); expect( m_configuration.getBootDelegation() ).andReturn( null ); expect( m_configuration.getStartLevel() ).andReturn( 10 ).anyTimes(); expect( m_configuration.getBundleStartLevel() ).andReturn( 20 ).times( 2 ); m_platformContext.setBundles( bundles ); m_platformContext.setExecutionEnvironment( "EE-1,EE-2" ); m_platformContext.setSystemPackages( "sys.package.one,sys.package.two" ); Properties properties = new Properties(); properties.setProperty( "myProperty", "myValue" ); m_platformContext.setProperties( properties ); replay( m_bundleContext, m_configuration, bundle1, bundle2, bundle3, bundle4 ); new KnopflerfishPlatformBuilderF300( m_bundleContext, "version" ).prepare( m_platformContext ); verify( m_bundleContext, m_configuration, bundle1, bundle2, bundle3, bundle4 ); Map<String, String> replacements = new HashMap<String, String>(); replacements.put( "${bundle1.path}", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "bundles/bundle1.jar" ) ) ); replacements.put( "${bundle2.path}", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "bundles/bundle2.jar" ) ) ); replacements.put( "${bundle3.path}", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "bundles/bundle3.jar" ) ) ); replacements.put( "${bundle4.path}", m_platformContext.getFilePathStrategy().normalizeAsUrl( new File( m_workDir, "bundles/bundle4.jar" ) ) ); compareFiles( FileUtils.getFileFromClasspath( "knopflerfishplatformbuilder/config300.ini" ), new File( m_workDir + "/knopflerfish/config.ini" ), true, replacements ); }
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( final String key ); List<String> getArguments(); String getArgumentsFileURL(); @Override String toString(); static final Pattern OPTION_PATTERN; }
@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( "--simpleOption=-Dhttp.port=80" ); assertEquals( "Option value", "-Dhttp.port=80", commandLine.getOption( "simpleOption" ) ); } @Test public void optionWithAValueThatContainsEqual02() { CommandLine commandLine = new CommandLineImpl( "--simpleOption=-Dhttp.port=80 -Dhttp.port.secure=443" ); assertEquals( "Option value", "-Dhttp.port=80 -Dhttp.port.secure=443", commandLine.getOption( "simpleOption" ) ); } @Test public void implicitFalseValue() { CommandLine commandLine = new CommandLineImpl( "--noSimpleOption" ); assertEquals( "Option value", "false", commandLine.getOption( "simpleOption" ) ); } @Test public void implicitTrueValue() { CommandLine commandLine = new CommandLineImpl( "--simpleOption" ); assertEquals( "Option value", "true", commandLine.getOption( "simpleOption" ) ); } @Test public void readArgsFile() { CommandLine commandLine = new CommandLineImpl( "--args=file:src/test/resources/runner.args" ); assertEquals( "option1 value", "value1", commandLine.getOption( "option1" ) ); assertEquals( "option2 value", "-Dhttp.port=80", commandLine.getOption( "option2" ) ); assertEquals( "option3 value", "false", commandLine.getOption( "option3" ) ); assertEquals( "option4 value", "true", commandLine.getOption( "option4" ) ); assertEquals( "vmo value", "-Doscar.embedded.execution=false " + "-Djava.library.path=native " + "-Djava.util.logging.config.file=../conf/logging.properties", commandLine.getOption( "vmo" ) ); assertEquals( "option5 value", "value5", commandLine.getOption( "option5" ) ); assertEquals( "option6 value", "", commandLine.getOption( "option6" ) ); assertEquals( "sp value", "org.osgi.framework; javax.swing; " + "javax.swing.event; javax.swing.table; javax.swing.text; " + "javax.swing.text.html;", commandLine.getOption( "sp" ) ); assertEquals( "option7 value", "value7continued", commandLine.getOption( "option7" ) ); assertEquals( "option8 value", "value8", commandLine.getOption( "option8" ) ); } @Test public void profilesAsArgs() { CommandLine commandLine = new CommandLineImpl( "--noArgs", "log", "web/[1.0,2.0)" ); assertEquals( "Profiles option", "log:web/[1.0,2.0)", commandLine.getOption( "profiles" ) ); }
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 String key ); String[] getMultipleOption( final String key ); List<String> getArguments(); String getArgumentsFileURL(); @Override String toString(); static final Pattern OPTION_PATTERN; }
@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( toResolve.contains( "@" ) ) { final int startOfOption = toResolve.indexOf( "@" ); options = toResolve.substring( startOfOption ); resolve = toResolve.substring( 0, startOfOption ); } String schema = org.ops4j.pax.scanner.dir.ServiceConstants.SCHEMA; if( !resolve.endsWith( "/" ) && !resolve.endsWith( "\\" ) && !resolve.contains( "!/" ) ) { if( resolve.startsWith( org.ops4j.pax.url.mvn.ServiceConstants.PROTOCOL ) && resolve.endsWith( "pom" ) ) { schema = org.ops4j.pax.scanner.pom.ServiceConstants.SCHEMA; } else if( resolve.startsWith( org.ops4j.pax.url.mvn.ServiceConstants.PROTOCOL ) || resolve.startsWith( org.ops4j.pax.url.wrap.ServiceConstants.PROTOCOL ) || resolve.startsWith( org.ops4j.pax.url.war.ServiceConstants.PROTOCOL_WAR ) || resolve.startsWith( org.ops4j.pax.url.war.ServiceConstants.PROTOCOL_WAR_INSTRUCTIONS ) || resolve.startsWith( org.ops4j.pax.url.war.ServiceConstants.PROTOCOL_WAR_REFERENCE ) || resolve.startsWith( org.ops4j.pax.url.war.ServiceConstants.PROTOCOL_WEB_BUNDLE ) || resolve.startsWith( org.ops4j.pax.url.obr.ServiceConstants.PROTOCOL ) || resolve.startsWith( org.ops4j.pax.url.assembly.ServiceConstants.PROTOCOL ) || resolve.startsWith( org.ops4j.pax.url.assembly.ServiceConstants.PROTOCOL_REFERENCE ) || resolve.startsWith( org.ops4j.pax.url.dir.ServiceConstants.PROTOCOL ) ) { schema = org.ops4j.pax.scanner.bundle.ServiceConstants.SCHEMA; } else { int indexOfSlash = resolve.lastIndexOf( "/" ); if( indexOfSlash == -1 ) { indexOfSlash = resolve.lastIndexOf( "\\" ); } final int indexOfDot = resolve.lastIndexOf( "." ); if( indexOfDot > indexOfSlash ) { schema = org.ops4j.pax.scanner.file.ServiceConstants.SCHEMA; if( indexOfDot < resolve.length() - 1 ) { final String extension = resolve.substring( indexOfDot + 1 ).toUpperCase(); if( "XML".equals( extension ) ) { schema = org.ops4j.pax.scanner.pom.ServiceConstants.SCHEMA; } else if( "ZIP".equals( extension ) ) { schema = org.ops4j.pax.scanner.dir.ServiceConstants.SCHEMA; } else if( "JAR".equals( extension ) || "BUNDLE".equals( extension ) ) { schema = org.ops4j.pax.scanner.bundle.ServiceConstants.SCHEMA; } else if( "OBR".equals( extension ) ) { schema = org.ops4j.pax.scanner.obr.ServiceConstants.SCHEMA; } else if( "COMPOSITE".equals( extension ) || "PROFILE".equals( extension ) ) { schema = org.ops4j.pax.scanner.composite.ServiceConstants.SCHEMA; } } } } } final File file = new File( resolve ); String resolved = resolve; if( file.exists() ) { try { resolved = file.toURL().toExternalForm(); } catch( MalformedURLException ignore ) { } } return schema + org.ops4j.pax.scanner.ServiceConstants.SEPARATOR_SCHEME + resolved + options; } String resolve( final String toResolve ); }
@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() { assertEquals( "Resolved", "scan-pom:mvn:group/artifact/version/pom", m_underTest.resolve( "mvn:group/artifact/version/pom" ) ); } @Test public void resolvePOMWithAnyProtocol() { assertEquals( "Resolved", "scan-pom:http:pom.xml", m_underTest.resolve( "http:pom.xml" ) ); } @Test public void resolvePOMWithoutProtocol() throws Exception { File file = FileUtils.getFileFromClasspath( "ebpsresolver/pom.xml" ); assertEquals( "Resolved", "scan-pom:" + file.toURL().toExternalForm(), m_underTest.resolve( file.getAbsolutePath() ) ); } @Test public void resolveJarWithFileProtocol() { assertEquals( "Resolved", "scan-bundle:file:x.jar", m_underTest.resolve( "file:x.jar" ) ); } @Test public void resolveJarWithAnyProtocol() { assertEquals( "Resolved", "scan-bundle:http:x.jar", m_underTest.resolve( "http:x.jar" ) ); } @Test public void resolveJarWithoutProtocol() throws Exception { File file = FileUtils.getFileFromClasspath( "ebpsresolver/x.jar" ); assertEquals( "Resolved", "scan-bundle:" + file.toURL().toExternalForm(), m_underTest.resolve( file.getAbsolutePath() ) ); } @Test public void resolveBundleWithFileProtocol() { assertEquals( "Resolved", "scan-bundle:file:x.bundle", m_underTest.resolve( "file:x.bundle" ) ); } @Test public void resolveBundleWithAnyProtocol() { assertEquals( "Resolved", "scan-bundle:http:x.bundle", m_underTest.resolve( "http:x.bundle" ) ); } @Test public void resolveBundleWithOptions() { assertEquals( "Resolved", "scan-bundle:file:x.jar@5@nostart", m_underTest.resolve( "file:x.jar@5@nostart" ) ); } @Test public void resolveBundleWithoutProtocol() throws Exception { File file = FileUtils.getFileFromClasspath( "ebpsresolver/x.bundle" ); assertEquals( "Resolved", "scan-bundle:" + file.toURL().toExternalForm(), m_underTest.resolve( file.getAbsolutePath() ) ); } @Test public void resolveDirWithFileProtocol() { assertEquals( "Resolved", "scan-dir:file:x.zip", m_underTest.resolve( "file:x.zip" ) ); } @Test public void resolveDirWithAnyProtocol() { assertEquals( "Resolved", "scan-dir:http:x.zip", m_underTest.resolve( "http:x.zip" ) ); } @Test public void resolveDirWithFullFilterSeparator() { assertEquals( "Resolved", "scan-dir:x.zip!/", m_underTest.resolve( "x.zip!/" ) ); } @Test public void resolveDirWithoutProtocol() throws Exception { File file = FileUtils.getFileFromClasspath( "ebpsresolver/x.zip" ); assertEquals( "Resolved", "scan-dir:" + file.toURL().toExternalForm(), m_underTest.resolve( file.getAbsolutePath() ) ); } @Test public void resolveAnyExtensionWithFileProtocol() { assertEquals( "Resolved", "scan-file:file:x.any", m_underTest.resolve( "file:x.any" ) ); } @Test public void resolveAnyExtensionWithAnyProtocol() { assertEquals( "Resolved", "scan-file:http:x.any", m_underTest.resolve( "http:x.any" ) ); } @Test public void resolveAnyExtensionWithoutProtocol() throws Exception { File file = FileUtils.getFileFromClasspath( "ebpsresolver/x.any" ); assertEquals( "Resolved", "scan-file:" + file.toURL().toExternalForm(), m_underTest.resolve( file.getAbsolutePath() ) ); } @Test public void resolveNoExtensionWithFileProtocol() { assertEquals( "Resolved", "scan-dir:file:x", m_underTest.resolve( "file:x" ) ); } @Test public void resolveNoExtensionWithAnyProtocol() { assertEquals( "Resolved", "scan-dir:http:x", m_underTest.resolve( "http:x" ) ); } @Test public void resolveNoExtensionWithoutProtocol() throws Exception { File file = FileUtils.getFileFromClasspath( "ebpsresolver/x" ); assertEquals( "Resolved", "scan-dir:" + file.toURL().toExternalForm(), m_underTest.resolve( file.getAbsolutePath() ) ); } @Test public void resolveSlashWithFileProtocol() { assertEquals( "Resolved", "scan-dir:file:x/", m_underTest.resolve( "file:x/" ) ); } @Test public void resolveSlashWithAnyProtocol() { assertEquals( "Resolved", "scan-dir:http:x/", m_underTest.resolve( "http:x/" ) ); } @Test public void resolveSlashWithoutProtocol() throws Exception { File file = FileUtils.getFileFromClasspath( "ebpsresolver/x/" ); assertEquals( "Resolved", "scan-dir:" + file.toURL().toExternalForm(), m_underTest.resolve( file.getAbsolutePath() ) ); } @Test public void resolveBackslashWithFileProtocol() { assertEquals( "Resolved", "scan-dir:file:x\\", m_underTest.resolve( "file:x\\" ) ); } @Test public void resolveBackslashWithAnyProtocol() { assertEquals( "Resolved", "scan-dir:http:x\\", m_underTest.resolve( "http:x\\" ) ); } @Test public void resolveBackSlashWithoutProtocol() throws Exception { File file = FileUtils.getFileFromClasspath( "ebpsresolver/x" + File.separator ); assertEquals( "Resolved", "scan-dir:" + file.toURL().toExternalForm(), m_underTest.resolve( file.getAbsolutePath() ) ); } @Test public void resolveNull() { assertNull( "Resolved expected to be null", m_underTest.resolve( null ) ); } @Test public void resolveEmpty() { assertNull( "Resolved expected to be null", m_underTest.resolve( " " ) ); } @Test public void resolveMvnWithoutVersion() throws MalformedURLException { assertEquals( "Resolved", "scan-bundle:mvn:org.ops4j/mine", m_underTest.resolve( "mvn:org.ops4j/mine" ) ); } @Test public void resolveMvnWithVersion() throws MalformedURLException { assertEquals( "Resolved", "scan-bundle:mvn:org.ops4j/mine/0.2.0", m_underTest.resolve( "mvn:org.ops4j/mine/0.2.0" ) ); } @Test public void resolveWrap() throws MalformedURLException { assertEquals( "Resolved", "scan-bundle:wrap:mvn:org.ops4j/mine", m_underTest.resolve( "wrap:mvn:org.ops4j/mine" ) ); } @Test public void resolveWrapWithInstructions() throws MalformedURLException { assertEquals( "Resolved", "scan-bundle:wrap:mvn:org.ops4j/mine!instruction=value", m_underTest.resolve( "wrap:mvn:org.ops4j/mine!instruction=value" ) ); }
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 PlatformException( "[" + url + "] is not a valid bundle" ); } bundleSymbolicName = manifest.getMainAttributes().getValue( Constants.BUNDLE_SYMBOLICNAME ); bundleName = manifest.getMainAttributes().getValue( Constants.BUNDLE_NAME ); } catch ( IOException e ) { throw new PlatformException( "[" + url + "] is not a valid bundle", e ); } finally { if ( jar != null ) { try { jar.close(); } catch ( IOException ignore ) { } } } if ( bundleSymbolicName == null && bundleName == null ) { throw new PlatformException( "[" + url + "] is not a valid bundle" ); } } PlatformImpl( final PlatformBuilder platformBuilder ); void setResolver( final PropertyResolver propertyResolver ); void start( final List<SystemFileReference> systemFiles, final List<BundleReference> bundles, final Properties properties, @SuppressWarnings("rawtypes") final Dictionary config, final JavaRunner javaRunner ); String toString(); }
@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.toURL(); platform.validateBundle( url, file ); } @Test( expected = PlatformException.class ) public void validateBundleWithInvalidFile() throws Exception { replay( m_builder, m_bundleContext, m_config ); PlatformImpl platform = new PlatformImpl( m_builder ); File file = FileUtils.getFileFromClasspath( "platform/invalid.jar" ); URL url = file.toURL(); platform.validateBundle( 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 ) { bundleSymbolicName = manifest.getMainAttributes().getValue( Constants.BUNDLE_SYMBOLICNAME ); bundleVersion = manifest.getMainAttributes().getValue( Constants.BUNDLE_VERSION ); } } catch ( IOException ignore ) { } finally { if ( jar != null ) { try { jar.close(); } catch ( IOException ignore ) { } } } if ( bundleSymbolicName == null ) { bundleSymbolicName = defaultBundleSymbolicName; } else { int semicolonPos = bundleSymbolicName.indexOf( ";" ); if ( semicolonPos > 0 ) { bundleSymbolicName = bundleSymbolicName.substring( 0, semicolonPos ); } } if ( bundleVersion == null ) { bundleVersion = "0.0.0"; } return bundleSymbolicName + "_" + bundleVersion + ".jar"; } PlatformImpl( final PlatformBuilder platformBuilder ); void setResolver( final PropertyResolver propertyResolver ); void start( final List<SystemFileReference> systemFiles, final List<BundleReference> bundles, final Properties properties, @SuppressWarnings("rawtypes") final Dictionary config, final JavaRunner javaRunner ); String toString(); }
@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.determineCachingName( file, "defaultBSN" ) ); verify( m_builder, m_bundleContext, m_config ); } @Test public void determineCacheNameWithValidManifestWithoutVersion() throws Exception { replay( m_builder, m_bundleContext, m_config ); PlatformImpl platform = new PlatformImpl( m_builder ); File file = FileUtils.getFileFromClasspath( "platform/bundle1.jar" ); assertEquals( "bundle2_0.0.0.jar", platform.determineCachingName( file, "defaultBSN" ) ); verify( m_builder, m_bundleContext, m_config ); } @Test public void determineCacheNameWithValidManifestWithVersion() throws Exception { replay( m_builder, m_bundleContext, m_config ); PlatformImpl platform = new PlatformImpl( m_builder ); File file = FileUtils.getFileFromClasspath( "platform/bundleWithVersion.jar" ); assertEquals( "bundle2_1.2.3.jar", platform.determineCachingName( file, "defaultBSN" ) ); verify( m_builder, m_bundleContext, m_config ); } @Test public void determineCacheNameWithBDNWithSemicolon() throws Exception { replay( m_builder, m_bundleContext, m_config ); PlatformImpl platform = new PlatformImpl( m_builder ); File file = FileUtils.getFileFromClasspath( "platform/bundleWithSemicolon.jar" ); assertEquals( "bundleWithSemicolon_0.0.0.jar", platform.determineCachingName( file, "defaultBSN" ) ); verify( m_builder, m_bundleContext, m_config ); }
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 ConfigurationImpl( configURL ); new Run().start( commandLine, config, new OptionResolverImpl( commandLine, config ), runner ); } Run(); static void main( final String... args ); static void main( final JavaRunner runner, final String... args ); static Log getLogger(); static void start( final JavaRunner runner, final String... args ); void start( final CommandLine commandLine, final Configuration config, final OptionResolver resolver ); void start( final CommandLine commandLine, final Configuration config, final OptionResolver resolver, final JavaRunner runner ); }
@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( CommandLine.class ), null, createMock( OptionResolver.class ) ); } @Test( expected = IllegalArgumentException.class ) public void startWithNullResolver() { new Run().start( createMock( CommandLine.class ), createMock( Configuration.class ), null ); } @Test public void startFlow() { m_recorder.record( "cleanup()" ); m_recorder.record( "installServices()" ); m_recorder.record( "installHandlers()" ); m_recorder.record( "installScanners()" ); m_recorder.record( "installBundles()" ); m_recorder.record( "createJavaRunner()" ); m_recorder.record( "installPlatform()" ); m_recorder.record( "determineSystemFiles()" ); replay( m_commandLine, m_config, m_recorder, m_resolver, m_bundleContext ); new Run() { @Override void cleanup( final OptionResolver resolver ) { m_recorder.record( "cleanup()" ); } @Override void installHandlers( final Context context ) { m_recorder.record( "installHandlers()" ); } @Override ProvisionService installScanners( final Context context ) { m_recorder.record( "installScanners()" ); return m_provisionService; } @Override Platform installPlatform( final Context context ) { m_recorder.record( "installPlatform()" ); return m_platform; } @Override void installBundles( final ProvisionService provisionService, final ProvisionSchemaResolver schemaResolver, final Context context ) { m_recorder.record( "installBundles()" ); } @Override void installServices( final Context context ) { m_recorder.record( "installServices()" ); } @Override JavaRunner createJavaRunner( final OptionResolver resolver ) { m_recorder.record( "createJavaRunner()" ); return null; } @Override List<SystemFileReference> determineSystemFiles( Context context ) { m_recorder.record( "determineSystemFiles()" ); return Collections.emptyList(); } }.start( m_commandLine, m_config, m_resolver, null ); verify( m_commandLine, m_config, m_recorder, m_resolver, m_bundleContext ); } @Test( expected = ConfigurationException.class ) public void startWithInvalidHandlers() { expect( m_resolver.get( "clean" ) ).andReturn( null ); expect( m_resolver.get( "executor" ) ).andReturn( null ); expect( m_resolver.get( "services" ) ).andReturn( null ); expect( m_resolver.get( "handlers" ) ).andReturn( "handler.1" ); expect( m_config.getProperty( "handler.service" ) ).andReturn( "handler.service.Activator" ); expect( m_config.getProperty( "handler.1" ) ).andReturn( null ); m_recorder.record( "handler.service.Activator" ); replay( m_commandLine, m_config, m_resolver, m_recorder, m_bundleContext ); new Run() { @Override BundleContext createActivator( final String handlerName, final String activatorName, final Context context ) { m_recorder.record( activatorName ); return m_bundleContext; } }.start( m_commandLine, m_config, m_resolver ); verify( m_commandLine, m_config, m_resolver, m_recorder, m_bundleContext ); }
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 createPackageListNONE() throws Exception { assertEquals( "System packages", "", new ExecutionEnvironment( "NONE" ).getSystemPackages() ); } @Test public void createPackageListLetterCase() throws Exception { assertEquals( "System packages", "javax.microedition.io,javax.microedition.pki,javax.security.auth.x500", new ExecutionEnvironment( "cdc-1.1/foundation-1.1" ).getSystemPackages() ); } @Test public void createPackageListWithMoreEEs() throws Exception { assertEquals( "System packages", "system.package.1,system.package.2,system.package.3", new ExecutionEnvironment( FileUtils.getFileFromClasspath( "platform/systemPackages.profile" ).toURL().toExternalForm() + "," + FileUtils.getFileFromClasspath( "platform/systemPackages2.profile" ).toURL().toExternalForm() ).getSystemPackages() ); }
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 = new URL( urlSpec ); } return set( ServiceConstants.CONFIG_DEFINITION_URL, url ); } return get( ServiceConstants.CONFIG_DEFINITION_URL ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }
@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 ConfigurationImpl( propertyResolver ); assertEquals( "Definition URL", new URL( "file:definition.xml" ), config.getDefinitionURL() ); verify( propertyResolver ); } @Test( expected = MalformedURLException.class ) public void getMalformedDefinitionURL() throws MalformedURLException { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.definitionURL" ) ).andReturn( "xxx:definition.xml" ); replay( propertyResolver ); new ConfigurationImpl( propertyResolver ).getDefinitionURL(); verify( propertyResolver ); } @Test public void getNotConfiguredDefinitionURL() throws MalformedURLException { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.definitionURL" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Definition URL", null, config.getDefinitionURL() ); verify( propertyResolver ); }
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; } return set( ServiceConstants.CONFIG_WORKING_DIRECTORY, workDir ); } return get( ServiceConstants.CONFIG_WORKING_DIRECTORY ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }
@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 ConfigurationImpl( propertyResolver ); assertEquals( "Working directory", "myWorkingDirectory", config.getWorkingDirectory() ); verify( propertyResolver ); } @Test public void getDefualtWorkingDirectory() throws MalformedURLException { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.workingDirectory" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Default working directory", "runner", config.getWorkingDirectory() ); verify( propertyResolver ); }
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.CONFIG_SYSTEM_PACKAGES ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }
@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 ); assertEquals( "System packages", "systemPackages", config.getSystemPackages() ); verify( 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.getProperty( "java.version" ).substring( 0, 3 ); } return set( ServiceConstants.CONFIG_EXECUTION_ENV, javaVersion ); } return get( ServiceConstants.CONFIG_EXECUTION_ENV ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }
@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( "Execution environment", "some-ee", config.getExecutionEnvironment() ); verify( propertyResolver ); }
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 == null ) { try { javaHome = System.getenv( "JAVA_HOME" ); } catch( Error e ) { } if( javaHome == null ) { javaHome = System.getProperty( "java.home" ); } } } return set( ServiceConstants.CONFIG_JAVA_HOME, javaHome ); } return get( ServiceConstants.CONFIG_JAVA_HOME ); } ConfigurationImpl( final PropertyResolver propertyResolver ); URL getDefinitionURL(); String getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }
@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( "Java home", "javaHome", config.getJavaHome() ); verify( propertyResolver ); }
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.synchronizedMap( new HashMap<ServiceReference, PlatformImpl>() ); trackPlatformBuilders(); registerManagedService(); LOGGER.debug( "Platform extender started" ); } Activator(); void start( final BundleContext bundleContext ); void stop( final BundleContext bundleContext ); }
@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() ), notNull(), (Dictionary) notNull() ) ).andReturn( null ); expect( context.createFilter( "(objectClass=" + PlatformBuilder.class.getName() + ")" ) ).andReturn( createMock( Filter.class ) ); context.addServiceListener( (ServiceListener) notNull(), eq( "(objectClass=" + PlatformBuilder.class.getName() + ")" ) ); expect( context.getServiceReferences( eq( PlatformBuilder.class.getName() ), (String) isNull() ) ).andReturn( null ); replay( context ); new Activator().start( context ); verify( context ); } @Test public void registerPlatformBuilder() throws Exception { final PlatformBuilder builder = createMock( PlatformBuilder.class ); BundleContext context = createMock( BundleContext.class ); Filter filter = createMock( Filter.class ); ServiceReference reference = createMock( ServiceReference.class ); final Platform platform = createMock( Platform.class ); expect( context.registerService( eq( ManagedService.class.getName() ), notNull(), (Dictionary) notNull() ) ).andReturn( null ); expect( context.createFilter( "(objectClass=" + PlatformBuilder.class.getName() + ")" ) ).andReturn( filter ); Capture<ServiceListener> listenerCapture = new Capture<ServiceListener>(); context.addServiceListener( capture( listenerCapture ), (String) notNull() ); expect( context.getServiceReferences( PlatformBuilder.class.getName(), null ) ).andReturn( null ); expect( context.getService( reference ) ).andReturn( builder ); expect( reference.getPropertyKeys() ).andReturn( null ); expect( context.registerService( eq( Platform.class.getName() ), eq( platform ), (Dictionary) notNull() ) ).andReturn( null ); replay( builder, context, filter, reference, platform ); new Activator() { @Override Platform createPlatform( final PlatformBuilder platformBuilder ) { assertEquals( "Platform builder", builder, platformBuilder ); return platform; } }.start( context ); listenerCapture.getCaptured().serviceChanged( new ServiceEvent( ServiceEvent.REGISTERED, reference ) ); verify( builder, context, filter, reference, platform ); }
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 getWorkingDirectory(); String[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }
@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 ); assertEquals( "Platform start level", Integer.valueOf( 10 ), config.getProfileStartLevel() ); verify( propertyResolver ); } @Test public void getDefaultProfileStartLevel() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.profileStartLevel" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Platform start level", Integer.valueOf( 1 ), config.getProfileStartLevel() ); verify( propertyResolver ); } @Test public void getDefaultProfileStartLevelIfOptionIsInvalid() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.profileStartLevel" ) ).andReturn( "invalid" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Platform start level", Integer.valueOf( 1 ), config.getProfileStartLevel() ); verify( propertyResolver ); }
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[] getVMOptions(); String[] getEnvOptions(); String getClasspath(); String getSystemPackages(); String getExecutionEnvironment(); String getJavaHome(); Boolean usePersistedState(); Boolean startConsole(); Boolean isOverwrite(); String getProfiles(); String getFrameworkProfile(); Integer getProfileStartLevel(); Integer getStartLevel(); Integer getBundleStartLevel(); Boolean isOverwriteUserBundles(); Boolean isOverwriteSystemBundles(); Boolean isDebugClassLoading(); Boolean isDownloadFeedback(); String getBootDelegation(); Boolean isAutoWrap(); Boolean keepOriginalUrls(); Boolean validateBundles(); Boolean skipInvalidBundles(); Boolean useAbsoluteFilePaths(); String getProperty( final String name ); }
@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( "Platform start level", Integer.valueOf( 10 ), config.getStartLevel() ); verify( propertyResolver ); } @Test public void getDefaultStartLevel() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.startLevel" ) ).andReturn( null ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Platform start level", Integer.valueOf( 6 ), config.getStartLevel() ); verify( propertyResolver ); } @Test public void getDefaultStartLevelIfOptionIsInvalid() { PropertyResolver propertyResolver = createMock( PropertyResolver.class ); expect( propertyResolver.get( "org.ops4j.pax.runner.platform.startLevel" ) ).andReturn( "invalid" ); replay( propertyResolver ); Configuration config = new ConfigurationImpl( propertyResolver ); assertEquals( "Platform start level", Integer.valueOf( 6 ), config.getStartLevel() ); verify( propertyResolver ); }