method2testcases
stringlengths 118
6.63k
|
---|
### Question:
AvUtil extends GpCoreUtil { public static String fixBrokenBgColor(String oldHtml) { return oldHtml.replaceAll("color\\s?=\\s?[\",']([0-9,a-f,A-F]{6})[\",']", "#$1"); } static String fixBrokenBgColor(String oldHtml); static boolean fixBrokenBgColor(File oldHtml); }### Answer:
@Test public void testFixBrokenBgColor(){ String oldHtml = "<html> <head> </head> <body bgcolor=\"ffe07a\"> <p><img height=\"298\" src=\"images/n4_java_vulkan_semeru_rauch_lava.jpg\" align=\"top\" width=\"447\">" + "</p><p><font size=\"+1\">Eruption des Vulkans Semeru auf der indonesischen Insel Java, 2004 </font><br><a href=\"browser: "licence</a> M. Rietze </p></body></html>"; asserFixed(oldHtml, "#ffe07a"); asserFixed("bgcolor='blue'", "blue"); asserFixed("bgcolor='#0000DD'", "'#0000DD'"); asserFixed("bgcolor='ffe07a'", "#ffe07a"); asserFixed("color='ffe07a'", "#ffe07a"); asserFixed("bgcolor='FFE07A'", "#FFE07A"); } |
### Question:
AVSwingUtil extends GpCoreUtil { public static File createLocalCopyFromURL(final Component owner, final URL url, String title, final String postFix) throws IOException { if (!url.toString().contains("jar:") && (url.toString().contains("file"))) { LOGGER.debug("Not copying the URL to temp file because we are local and not in a JAR."); return DataUtilities.urlToFile(url); } if (cachedLocalCopiedFiles.containsKey(url)) { File fileInTemp = cachedLocalCopiedFiles.get(url); if (fileInTemp.exists() && fileInTemp.length() > 0) { return fileInTemp; } else { cachedLocalCopiedFiles.remove(url); } } if (title == null) title = ""; final File localTempFile = File.createTempFile(ATLAS_TEMP_FILE_BASE_ID + IOUtil.cleanFilename(title), postFix); new AtlasSwingWorker<Void>(owner) { @Override protected Void doInBackground() throws Exception { FileUtils.copyURLToFile(url, localTempFile); localTempFile.deleteOnExit(); String msg = "downloaded to " + localTempFile; LOGGER.debug(msg); return null; } }.executeModalNoEx(); cachedLocalCopiedFiles.put(url, localTempFile.getCanonicalFile()); return localTempFile.getCanonicalFile(); } static JColorChooser getJcolorChooser(); static Color showColorChooser(final Component component,
final String title, final Color initialColor); final static void showMessageDialog(final Component owner,
final String message); static boolean askOKCancel(final Component owner,
final String question); static File createLocalCopyFromURL(final Component owner,
final URL url, String title, final String postFix); static void copyHTMLInfoFiles(
final AtlasStatusDialogInterface statusDialog, final File file,
final AtlasConfig ac, final File targetDir, final Logger log); static Exception launchPDFViewer(final Component owner, URL url,
String title); static void initEPSG(Component parent); static Exception lauchHTMLviewer(final Component owner, final URL url); static void lauchHTMLviewer(final Component owner, final URI uri); static Exception showImageAsHtmlPopup(final Component owner, final URL url, AtlasConfig ac); static File getLocalCopy(DpEntry<? extends ChartStyle> dpe,
Component owner); static final URL getUrl(DpEntry<?> dpe, Component comp); static final URL getUrl(DpEntry dpe,
AtlasStatusDialogInterface statusDialog); static void exportTo(DpEntry<? extends ChartStyle> dpe,
File targetDir, Component owner); static File selectExportDir(Component owner, AtlasConfig atlasConfig); static Object runWaiting(Component owner,
final RunnableFuture<Object> runnable); final static float HEADING_FONT_SIZE; }### Answer:
@Test public void testCreateLocalCopyFromURLRecoversIfTheFileIsDeleted() throws IOException { if (!TestingUtil.INTERACTIVE) return; URL url = new URL("http: assertNotNull(url); File file = AVSwingUtil .createLocalCopyFromURL(null, url, "test", "tif"); assertTrue(file.exists()); file.delete(); assertFalse(file.exists()); file = AVSwingUtil.createLocalCopyFromURL(null, url, "test", "tif"); assertTrue(file.exists()); } |
### Question:
JNLPSwingUtil extends JNLPUtil { public static void loadPartAndCreateDialogForIt( AtlasStatusDialogInterface asg, final String... parts) { try { if (GraphicsEnvironment.isHeadless()) { loadPart(parts, new NoGuiDownloadServiceListener()); return; } boolean edt = SwingUtilities.isEventDispatchThread(); LOGGER.debug("loadPartAndCreateDialogForIt(String[] parts) EDT:" + edt); if (asg == null) { LOGGER.debug( "loadPartAndCreateDialogForIt has been called with null AtlasStatusDialog", new RuntimeException( "loadPartAndCreateDialogForIt has been called with null AtlasStatusDialog")); asg = new AtlasStatusDialog( null, SwingUtil .R("AtlasStatusDialog.jnlp.generalDownload.Title"), SwingUtil .R("AtlasStatusDialog.jnlp.generalDownload.Desc")); } final AtlasStatusDialogInterface finalRefToStatusDialog = asg; final AtlasSwingWorker<Void> asw = new AtlasSwingWorker<Void>( finalRefToStatusDialog) { @Override protected Void doInBackground() throws Exception { loadPart(parts, finalRefToStatusDialog); return null; } }; if (edt) { LOGGER.debug(" starting a AtlasSwingWorker (null) to download on edt"); asw.executeModal(); } else { LOGGER.debug(" starting a AtlasSwingWorker (null) to download not on edt, via Invoke AndWait"); org.geotools.resources.SwingUtilities .invokeAndWait(new Runnable() { @Override public void run() { try { asw.executeModal(); } catch (CancellationException e) { LOGGER.error( "Ex on AtlasStwingWorker for loadPartAndCreateDialogForIt", e); } catch (InterruptedException e) { LOGGER.error( "Ex on AtlasStwingWorker for loadPartAndCreateDialogForIt", e); } catch (ExecutionException e) { LOGGER.error( "Ex on AtlasStwingWorker for loadPartAndCreateDialogForIt", e); } } }); } } catch (Throwable e) { throw new RuntimeException(e); } } static void loadPart(String[] parts,
DownloadServiceListener serviceListener); static void loadPartAndCreateDialogForIt(
AtlasStatusDialogInterface asg, final String... parts); }### Answer:
@Test public void testLoadPartEvenHeadless() throws IOException { if (TestingUtil.isInteractive()) { JNLPSwingUtil.loadPartAndCreateDialogForIt(null, "a"); AtlasStatusDialog myAsg = new AtlasStatusDialog(null, "my","my"); JNLPSwingUtil.loadPartAndCreateDialogForIt(myAsg, "a"); } } |
### Question:
DpLayerVectorFeatureSourceShapefileEd extends
DpLayerVectorFeatureSourceShapefile implements DpEditableInterface { private void parseGeocommonsReadme(URL geocommonsReadmeURL, int phase) { try { InputStream openStream = geocommonsReadmeURL.openStream(); try { InputStreamReader inStream = new InputStreamReader(openStream); try { BufferedReader inReader = new BufferedReader(inStream); try { String title = ""; while (title.trim().isEmpty()) { title = inReader.readLine(); } if (phase == 1) setTitle(new Translation(title)); String desc = ""; String oneLine = ""; while (!oneLine.startsWith("Attributes:")) { oneLine = inReader.readLine(); if (oneLine != null) oneLine = oneLine.trim(); if (!oneLine.isEmpty() && !oneLine.startsWith("Attributes:")) desc += oneLine + " "; } if (phase == 1) setDesc(new Translation(desc)); if (phase != 2) return; String attLine = ""; while (attLine != null) { attLine = inReader.readLine(); attLine = attLine.trim(); if (attLine.contains(":")) { String[] split = attLine.split(":"); String attName = split[0].trim(); String attDesc = split[1].trim(); try { if (attDesc.contains(" - ")) { String[] split2 = attDesc.split(" - "); if (split2[0].trim().equals( split2[1].trim())) attDesc = split2[0].trim(); } } catch (Exception e) { LOGGER.warn( "While parsing GeoCommons README", e); } NameImpl findBestMatchingAttribute = FeatureUtil .findBestMatchingAttribute(getSchema(), attName); if (findBestMatchingAttribute == null) continue; AttributeMetadataImpl amd = getAttributeMetaDataMap() .get(findBestMatchingAttribute); if (amd != null) { amd.setTitle(new Translation(attDesc)); } } } } finally { inReader.close(); } } finally { inStream.close(); } } finally { openStream.close(); } } catch (Exception e) { if (e instanceof FileNotFoundException && e.getMessage().contains("README")) { } else { LOGGER.warn("Parsing GeoComons README failed, probably not in GeoCommons format"); } } } DpLayerVectorFeatureSourceShapefileEd(AtlasConfig ac, URL url,
Component owner); @Override File getSldFile(); @Override void setSldFile(File sldFile); @Override void copyFiles(URL urlToShape, Component owner, File targetDir,
AtlasStatusDialogInterface status); AtlasConfigEditable getAce(); }### Answer:
@Test public void testParseGeocommonsReadme() { } |
### Question:
UniqueValuesAddGUI extends CancellableDialogAdapter { public UniqueValuesAddGUI(Component owner, final UniqueValuesRulesListInterface<VALUETYPE> rulesList) { super(owner); this.rulesList = rulesList; initialize(); String title = ASUtil.R("UniqueValuesRuleList.AddAllValues.SearchingMsg"); final AtlasStatusDialog statusDialog = new AtlasStatusDialog(owner, title, title); AtlasSwingWorker<Set<VALUETYPE>> findUniques = new AtlasSwingWorker<Set<VALUETYPE>>(statusDialog) { @Override protected Set<VALUETYPE> doInBackground() throws Exception { return rulesList.getAllUniqueValuesThatAreNotYetIncluded(); } }; try { Set<VALUETYPE> uniqueValues = findUniques.executeModal(); if (uniqueValues.size() == 0) AVSwingUtil.showMessageDialog(UniqueValuesAddGUI.this, ASUtil.R("UniqueValues.NothingToAdd")); DefaultListModel defaultListModel = new DefaultListModel(); for (VALUETYPE uv : uniqueValues) { defaultListModel.addElement(uv); } getJListValues().setModel(defaultListModel); SwingUtil.setRelativeFramePosition(UniqueValuesAddGUI.this, owner, SwingUtil.BOUNDS_OUTER, SwingUtil.NORTHEAST); } catch (CancellationException e) { dispose(); return; } catch (Exception e) { ExceptionDialog.show(e); dispose(); return; } } UniqueValuesAddGUI(Component owner, final UniqueValuesRulesListInterface<VALUETYPE> rulesList); @Override void cancel(); @Override boolean okClose(); }### Answer:
@Test public void testUniqueValuesAddGUI() throws Throwable { final UniqueValuesRuleList rl = new RuleListFactory( GTTestingUtil.TestDatasetsVector.kreise.getStyledFS()) .createUniqueValuesRulesList(true); if (TestingUtil.INTERACTIVE) { UniqueValuesAddGUI dialog = new UniqueValuesAddGUI(null, rl); TestingUtil.testGui(dialog, 1); } } |
### Question:
SymbolSelectorGUI extends AtlasDialog { public SymbolSelectorGUI(Component owner, AtlasStylerVector asv, String title, final SingleRuleList singleSymbolRuleList) { super(owner); if (asv == null) throw new IllegalStateException("asv may not be null here!"); this.asv = asv; if (title != null) setTitle(title); else setTitle(DIALOG_TITLE); this.singleSymbolRuleList = singleSymbolRuleList; initialize(); } SymbolSelectorGUI(Component owner, AtlasStylerVector asv,
String title, final SingleRuleList singleSymbolRuleList); static final String PROPERTY_CANCEL_CHANGES; static final String PROPERTY_CLOSED; }### Answer:
@Test public void testSymbolSelectorGUI() throws Throwable { if (!TestingUtil.isInteractive()) return; AtlasStylerVector asv = AsTestingUtil .getAtlasStyler(TestDatasetsVector.polygonSnow); SinglePolygonSymbolRuleList singleSymbolRuleList = RuleListFactory .createSinglePolygonSymbolRulesList(new Translation( "test with defaults"), true); asv.addRulesList(singleSymbolRuleList); PolygonSymbolizer ps = (PolygonSymbolizer) singleSymbolRuleList.getSymbolizers().get(0); ps.setFill(StylingUtil.STYLE_BUILDER.createFill()); ps.getFill().setGraphicFill(StylingUtil.STYLE_BUILDER.createGraphic()); ps.getFill().getGraphicFill().setSize(StylingUtil.ff.literal(5.0)); assertEquals(5., singleSymbolRuleList.getSizeBiggest(), 0.0); SymbolSelectorGUI ssg = new SymbolSelectorGUI(null, asv, "", singleSymbolRuleList); JComboBox jComboBoxSize = ssg.getJComboBoxSize(); jComboBoxSize.setSelectedIndex(10); System.out.println(StylingUtil.sldToString(asv.getStyle())); assertEquals(10., singleSymbolRuleList.getSizeBiggest(), 0.0); } |
### Question:
FeatureClassificationGUI extends ClassificationGUI { private AtlasStylerVector getAtlasStyler() { return (AtlasStylerVector) atlasStyler; } FeatureClassificationGUI(Component owner,
FeatureClassification classifier, AtlasStylerVector atlasStyler,
String title); FeatureClassification getClassifier(); }### Answer:
@Test public void testShowGuiWithoutValueAttribute() throws Throwable { if (!hasGui()) return; AtlasStylerVector asv = AsTestingUtil .getAtlasStyler(TestDatasetsVector.countryShp); FeatureClassification classifier = new FeatureClassification( asv.getStyledFeatures()); ClassificationGUI gui = new FeatureClassificationGUI(null, classifier, asv, "junit test vector classification"); TestingUtil.testGui(gui); }
@Test public void testShowGui() throws Throwable { if (!hasGui()) return; AtlasStylerVector asv = AsTestingUtil .getAtlasStyler(TestDatasetsVector.countryShp); FeatureClassification classifier = new FeatureClassification( asv.getStyledFeatures()); classifier.setValue_field_name(FeatureUtil.getNumericalFieldNames( asv.getStyledFeatures().getSchema()).get(0)); ClassificationGUI gui = new FeatureClassificationGUI(null, classifier, asv, "junit test vector classification"); TestingUtil.testGui(gui); } |
### Question:
TextLabelingClassLanguageSelectorDialog extends
CancellableDialogAdapter { public TextLabelingClassLanguageSelectorDialog(Component parentGui, TextRuleList rulesList) { super(parentGui, ASUtil .R("TextSymbolizerClass.CreateALanguageDefault.DialogTitle")); this.rulesList = rulesList; lcb = new LanguagesComboBox(AtlasStylerVector.getLanguages(), rulesList.getDefaultLanguages()); setContentPane(new JPanel(new MigLayout("wrap 1, w 400"))); getContentPane() .add(new JLabel( ASUtil.R("TextSymbolizerClass.CreateALanguageDefault.Explanation")), ""); getContentPane().add(lcb, "w 300, center"); getContentPane().add(getOkButton(), "split 2, tag ok"); getContentPane().add(getCancelButton(), "tag cancel"); pack(); SwingUtil.setRelativeFramePosition(this, parentGui, 0.5, 0.5); } TextLabelingClassLanguageSelectorDialog(Component parentGui,
TextRuleList rulesList); @Override boolean close(); @Override void cancel(); String getSelectedLanguage(); }### Answer:
@Test public void testTextLabelingClassLanguageSelectorDialog() throws Throwable { if (!hasGui()) return; TextRuleList textRulesList = new RuleListFactory( GTTestingUtil.TestDatasetsVector.countryShp.getStyledFS()) .createTextRulesList(true); TextLabelingClassLanguageSelectorDialog d = new TextLabelingClassLanguageSelectorDialog( null, textRulesList); d.setVisible(true); d.pack(); TestingUtil.testGui(d, 100); } |
### Question:
LineSymbolEditGUI extends AbstractStyleEditGUI { public LineSymbolEditGUI(final AtlasStylerVector asv, final org.geotools.styling.LineSymbolizer symbolizer) { super(asv); this.symbolizer = symbolizer; initialize(); } LineSymbolEditGUI(final AtlasStylerVector asv, final org.geotools.styling.LineSymbolizer symbolizer); }### Answer:
@Test public void testLineSymbolEditGUI() throws Throwable { if (!TestingUtil.isInteractive()) return; LineSymbolEditGUI lineSymbolEditGUI = new LineSymbolEditGUI( AsTestingUtil.getAtlasStyler(TestDatasetsVector.countryShp), ps); TestingUtil.testGui(lineSymbolEditGUI); } |
### Question:
PolygonSymbolEditGUI extends AbstractStyleEditGUI { public PolygonSymbolEditGUI(final AtlasStylerVector asv, final org.geotools.styling.PolygonSymbolizer symbolizer) { super(asv); this.symbolizer = symbolizer; initialize(); } PolygonSymbolEditGUI(final AtlasStylerVector asv,
final org.geotools.styling.PolygonSymbolizer symbolizer); }### Answer:
@Test public void testPolygonSymbolEditGUI() throws Throwable { if (!TestingUtil.isInteractive()) return; ps.setFill(null); ps.setStroke(null); PolygonSymbolEditGUI polygonSymbolEditGUI = new PolygonSymbolEditGUI(AsTestingUtil.getAtlasStyler(TestDatasetsVector.countryShp),ps); TestingUtil.testGui(polygonSymbolEditGUI); } |
### Question:
AtlasStylerPane extends JSplitPane implements ClosableSubwindows { public AtlasStylerPane(StylerDialog stylerDialog) { this.asd = stylerDialog; this.atlasStyler = stylerDialog.getAtlasStyler(); initialize(); atlasStyler.setQuite(true); { for (AbstractRulesList ruleList : atlasStyler.getRuleLists()) { createEditorComponent(ruleList); } } getRulesListsListTablePanel().getRulesListTable().getSelectionModel() .addListSelectionListener(listenToSelectionInTable); if (getRulesListsListTablePanel().getRulesListTable().getSelectedRow() != -1) { int s1 = getRulesListsListTablePanel().getRulesListTable() .getSelectedRow(); getRulesListsListTablePanel().getRulesListTable() .getSelectionModel().clearSelection(); getRulesListsListTablePanel().getRulesListTable() .getSelectionModel().addSelectionInterval(s1, s1); } atlasStyler.setQuite(false); } AtlasStylerPane(StylerDialog stylerDialog); void changeEditorComponent(JComponent newComponent); void changeEditorComponent(AbstractRulesList ruleList); JComponent createEditorComponent(AbstractRulesList ruleList); void dispose(); }### Answer:
@Test public void testAtlasStylerPane() throws Throwable { if (!TestingUtil.hasGui()) return; StylerDialog asd = new StylerDialog(null, atlasStylerPolygon, null); TestingUtil.testGui(asd); } |
### Question:
AddRulesListDialog extends AtlasDialog implements Cancellable { public AddRulesListDialog(Component owner, AtlasStyler atlasStyler) { super(owner, ASUtil.R("AddRulesListDialog.title", atlasStyler.getTitle())); this.owner = owner; this.atlasStyler = atlasStyler; jComboBoxRuleListType = new RulesListJComboBox(atlasStyler); jComboBoxRuleListType.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateImage(); } }); initGui(); } AddRulesListDialog(Component owner, AtlasStyler atlasStyler); @Override void cancel(); @Override boolean close(); }### Answer:
@Test public void testAddRulesListDialog() throws Throwable { if (!TestingUtil.isInteractive()) return; AtlasStylerVector as = AsTestingUtil .getAtlasStyler(TestDatasetsVector.countryShp); AddRulesListDialog addRulesListDialog = new AddRulesListDialog(null, as); TestingUtil.testGui(addRulesListDialog); } |
### Question:
DpEntryFactory { public static DpEntry create(AtlasConfigEditable ace, File file, Component owner) throws AtlasImportException { for (DpEntryTesterInterface test : testers) { if (test.test(owner, file)) return test.create(ace, file, owner); } return null; } private DpEntryFactory(); static DpEntry create(AtlasConfigEditable ace, File file,
Component owner); static boolean test(File file, Component owner); static final FileFilter FILEFILTER_ALL_DPE_IMPORTABLE; final static List<DpEntryTesterInterface> testers; }### Answer:
@Test public void testCreate() throws IOException, URISyntaxException { } |
### Question:
TextSymbolizerEditGUI extends AbstractStyleEditGUI { public JComboBox getJComboBoxFont() { if (jComboBoxFont == null) { jComboBoxFont = new JComboBox(); List<Literal>[] fontFamilies = asv.getAvailableFonts(); jComboBoxFont.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel proto = (JLabel) super.getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); ArrayList<Literal> itemValue = (ArrayList<Literal>) value; proto.setText(itemValue.get(0).toString()); return proto; } }); jComboBoxFont.setModel(new DefaultComboBoxModel(fontFamilies)); jComboBoxFont.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { ArrayList<Literal> fontExpressions = (ArrayList<Literal>) jComboBoxFont .getSelectedItem(); rulesList.getSymbolizer().getFont().getFamily().clear(); rulesList.getSymbolizer().getFont().getFamily() .addAll(fontExpressions); rulesList.fireEvents(new RuleChangedEvent( "The FontFamiliy changed to " + fontExpressions.toString(), rulesList)); } } }); SwingUtil.addMouseWheelForCombobox(jComboBoxFont); } return jComboBoxFont; } TextSymbolizerEditGUI(TextRuleList rulesList,
AtlasStylerVector atlasStyler,
FeatureCollection<SimpleFeatureType, SimpleFeature> previewFeatures); JComboBox getJComboBoxFont(); void updateGui(final TextSymbolizer symbolizer); static final String[] FONT_STYLES; static final String[] FONT_WEIGHTS; static final Double[] SIZES; }### Answer:
@Test public void testGetFontComboBox() throws IOException { TextSymbolizerEditGUI textSymbolizerEditGUI = new TextSymbolizerEditGUI( tr, atlasStyler, STYLED_FS.getFeatureCollection()); JComboBox jComboBoxFont = textSymbolizerEditGUI.getJComboBoxFont(); assertEquals("default number of fonts is 5", 5, jComboBoxFont.getItemCount()); }
@Test public void testGetFontComboBox2() throws IOException { List<Font> fonts = new ArrayList<Font>(); atlasStyler.setFonts(fonts); TextSymbolizerEditGUI textSymbolizerEditGUI = new TextSymbolizerEditGUI( tr, atlasStyler, TestDatasetsVector.countryShp.getFeatureCollection()); JComboBox jComboBoxFont = textSymbolizerEditGUI.getJComboBoxFont(); assertEquals("default number of fonts is 5", 5, jComboBoxFont.getItemCount()); } |
### Question:
GraphicEditGUI extends AbstractStyleEditGUI { public GraphicEditGUI(final AtlasStylerVector asv, final Graphic graphic_, GeometryForm geomForm) { super(asv); this.geometryForm = geomForm; if (graphic_ != null) { this.graphic = graphic_; } else { this.graphic = StylingUtil.STYLE_BUILDER.createGraphic(); firePropertyChange(PROPERTY_UPDATED, null, null); } final int countGraphicalSymbols = graphic.graphicalSymbols().size(); if (countGraphicalSymbols == 0) { graphic.graphicalSymbols().add( StylingUtil.STYLE_BUILDER.createMark(MARKTYPE.square .toWellKnownName())); } else if (countGraphicalSymbols > 1) { LOGGER.warn("The Graphic " + graphic + " contains more than one graphical symbols. Only the first one will be kept."); GraphicalSymbol firstGraphicalSymbol = graphic.graphicalSymbols() .get(0); graphic.graphicalSymbols().clear(); graphic.graphicalSymbols().add(firstGraphicalSymbol); } initialize(); } GraphicEditGUI(final AtlasStylerVector asv, final Graphic graphic_,
GeometryForm geomForm); }### Answer:
@Test public void testGraphicEditGUI() throws Throwable { if (!TestingUtil.isInteractive()) return; Graphic g = StylingUtil.STYLE_BUILDER.createGraphic(); GraphicEditGUI graphicEditGUI = new GraphicEditGUI( AsTestingUtil.getAtlasStyler(TestDatasetsVector.countryShp), g, GeometryForm.POINT); TestingUtil.testGui(graphicEditGUI, 220); } |
### Question:
SVGSelector extends CancellableDialogAdapter { public void changeURL(URL newUrl) { url = newUrl; LOGGER.debug("Changing " + this.getClass().getSimpleName() + " URL to " + url.getFile()); jList = null; rescan(false); jScrollPane1.setViewportView(getJList()); jTextFieldURL.setText(url.getFile()); jButtonUp.setEnabled(!url.toString().equals( FreeMapSymbols.SVG_URL + "/")); } SVGSelector(Window owner, GeometryForm geomForm,
ExternalGraphic[] preSelection); @Override void cancel(); void changeURL(URL newUrl); static final String PROPERTY_UPDATED; }### Answer:
@Test public void testSvgSelectorGui() throws Throwable { if (!TestingUtil.hasGui()) return; SVGSelector svgSelector = new SVGSelector(null, GeometryForm.POLYGON, null); svgSelector.changeURL(new URL(FreeMapSymbols.SVG_URL + "/" + "osm")); TestingUtil.testGui(svgSelector,600); } |
### Question:
GPProps { protected static void init(final String propertiesFilename, final String appDirname) { GpUtil.initGpLogging(); GPProps.propertiesFilename = propertiesFilename; GPProps.appDirname = appDirname; try { final FileInputStream inStream = new FileInputStream( getPropertiesFile()); try { properties.load(inStream); } finally { inStream.close(); } } catch (final Exception e) { LOGGER.error(e); ExceptionDialog .show(null, e,"Cannot save properties","<html>The properties file is not accessible. <br />Please check the permissions for <b>"+getPropertiesFile().getAbsolutePath()+"</b> to permanently keep your Geopublisher configuration.</html>"); } upgrade(); } static Properties getProperties(); static String get(final Keys key); static String get(final Keys key, final String def); static boolean getBoolean(final Keys key); static boolean getBoolean(Keys key, boolean defaultValue); static Integer getInt(final Keys key, final Integer def); static void resetProperties(final Component guiOwner); static final void set(final Keys key, final Boolean value); static final void set(final Keys key, final Integer value); static final void set(final Keys key, final String value); static void store(); static void upgrade(); static final String PROPERTIES_FILENAME; static final String PROPERTIES_FOLDER; }### Answer:
@Test public void testInit() { GPProps.init(GPProps.PROPERTIES_FILENAME, GPProps.PROPERTIES_FOLDER); } |
### Question:
GpUtil { public static void initBugReporting() { ExceptionDialog.setMailDestinationAddress("[email protected]"); ExceptionDialog.setSmtpMailer(bugReportMailer); ExceptionDialog.addAdditionalAppInfo(ReleaseUtil .getVersionInfo(GpUtil.class)); } static void initGpLogging(); static void initBugReporting(); static Set<Locale> getAvailableLocales(); static String R(String key, Object... values); static String R(final String key, Locale reqLanguage,
final Object... values); final static String getRandomID(String prefix); static void writeCpg(DpLayerVectorFeatureSource dpe); static File chooseFileOpenFallback(Component parent,
File startFolder, String title, FileExtensionFilter... filters); static void checkAndResetTmpDir(String path); static final FileExtensionFilter IMAGE_FILE_FILTER; static final FileExtensionFilter GIS_FILE_FILTER; static final Mailer bugReportMailer; static final IOFileFilter FontsFilesFilter; static final MbDecimalFormatter MbDecimalFormatter; }### Answer:
@Test public void testSendGPBugReport_WithAddInfos() { GpUtil.initBugReporting(); assertEquals(3, ExceptionDialog.getAdditionalAppInfo().size()); for (Object o : ExceptionDialog.getAdditionalAppInfo()) { System.out.println(o.toString()); } } |
### Question:
GpUtil { public static void initGpLogging() throws FactoryConfigurationError { if (Logger.getRootLogger().getAllAppenders().hasMoreElements()) return; DOMConfigurator.configure(GPProps.class .getResource("/geopublishing_log4j.xml")); Logger.getRootLogger().addAppender( Logger.getLogger("dummy").getAppender("gpFileLogger")); String logLevelStr = GPProps.get(Keys.logLevel); if (logLevelStr != null) { Logger.getRootLogger().setLevel(Level.toLevel(logLevelStr)); } initBugReporting(); } static void initGpLogging(); static void initBugReporting(); static Set<Locale> getAvailableLocales(); static String R(String key, Object... values); static String R(final String key, Locale reqLanguage,
final Object... values); final static String getRandomID(String prefix); static void writeCpg(DpLayerVectorFeatureSource dpe); static File chooseFileOpenFallback(Component parent,
File startFolder, String title, FileExtensionFilter... filters); static void checkAndResetTmpDir(String path); static final FileExtensionFilter IMAGE_FILE_FILTER; static final FileExtensionFilter GIS_FILE_FILTER; static final Mailer bugReportMailer; static final IOFileFilter FontsFilesFilter; static final MbDecimalFormatter MbDecimalFormatter; }### Answer:
@Test @Ignore public void testInitGpLogging() { GpUtil.initGpLogging(); assertEquals(2, countRootLoggers()); GpUtil.initGpLogging(); assertEquals(2, countRootLoggers()); } |
### Question:
AMLExporter { protected Node exportFonts(Document document) { final Element fontsElement = document.createElementNS(AMLUtil.AMLURI, AMLUtil.TAG_FONTS); File fontsDir = getAce().getFontsDir(); Collection<File> listFiles = FileUtils.listFiles(fontsDir, GpUtil.FontsFilesFilter, FilterUtil.BlacklistedFoldersFilter); for (File f : listFiles) { String relPath = f.getAbsolutePath().substring( fontsDir.getAbsolutePath().length() + 1); try { Font.createFont(Font.TRUETYPE_FONT, f); final Element fontElement = document.createElementNS( AMLUtil.AMLURI, AMLUtil.TAG_FONT); fontElement.setAttribute(AMLUtil.ATT_FONT_FILENAME, relPath); fontsElement.appendChild(fontElement); } catch (Exception e) { LOGGER.info("Not exporting a reference to broken font " + relPath + " in " + fontsDir, e); } } return fontsElement; } AMLExporter(final AtlasConfigEditable ace); File writeBuildxml(File targetDir, String atlasBaseName); boolean saveAtlasConfigEditable(); boolean saveAtlasConfigEditable(
final AtlasStatusDialogInterface statusWindow); void setExportMode(boolean exportMode); boolean isExportMode(); void setAtlasXml(File atlasXml); File getAtlasXml(); AtlasConfigEditable getAce(); final static public String ATLASBASENAME_TAG_IN_BUILDXML; }### Answer:
@Test public void testFonts() throws AtlasException, FactoryException, TransformException, SAXException, IOException, ParserConfigurationException, TransformerException { final DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); Document document = null; document = factory.newDocumentBuilder().newDocument(); Node fontsE = exportFonts(document); int length = fontsE.getChildNodes().getLength(); assertEquals(1, length); Node namedItem = fontsE.getChildNodes().item(0).getAttributes() .getNamedItem(AMLUtil.ATT_FONT_FILENAME); assertEquals("futura_book.ttf", namedItem.getTextContent()); } |
### Question:
AMLExporter { public File writeBuildxml(File targetDir, String atlasBaseName) { if (atlasBaseName == null || atlasBaseName.equals(AtlasConfig.DEFAULTBASENAME) || atlasBaseName.equals("null")) { LOGGER.info("Not writing a build.xml for automatic publishing, because the basename is " + atlasBaseName + ". Please change it."); return null; } if (atlasBaseName.endsWith("/")) { atlasBaseName = atlasBaseName.substring(0, atlasBaseName.length() - 1); } String resLoc = "/autoPublish/build.xml"; URL templateBuildXml = GpUtil.class.getResource(resLoc); if (templateBuildXml == null) { LOGGER.error("Could not find " + resLoc + ". build.xml has not been created!"); return null; } String templString = IOUtil.readURLasString(templateBuildXml); String buildXmlContent = templString.replaceAll( Pattern.quote(ATLASBASENAME_TAG_IN_BUILDXML), atlasBaseName); targetDir.mkdirs(); File buildFile = new File(targetDir, "build.xml"); if (buildFile.exists()) { String existing; try { existing = IOUtil.readFileAsString(buildFile); if (buildXmlContent.equals(existing)) return buildFile; } catch (IOException e) { LOGGER.warn("Error reading existing build.xml, it will be recreated..."); } if (!buildFile.delete()) { LOGGER.error("Could not delete exitsing " + buildFile.getAbsolutePath() + ", to update it."); } } try { FileWriter fw = new FileWriter(buildFile); fw.write(buildXmlContent); fw.flush(); fw.close(); } catch (Exception e) { LOGGER.error( "Could not write build.xml for automatic publishing on http: e); return null; } return buildFile; } AMLExporter(final AtlasConfigEditable ace); File writeBuildxml(File targetDir, String atlasBaseName); boolean saveAtlasConfigEditable(); boolean saveAtlasConfigEditable(
final AtlasStatusDialogInterface statusWindow); void setExportMode(boolean exportMode); boolean isExportMode(); void setAtlasXml(File atlasXml); File getAtlasXml(); AtlasConfigEditable getAce(); final static public String ATLASBASENAME_TAG_IN_BUILDXML; }### Answer:
@Test public void testWriteBuildxml() throws AtlasException, FactoryException, TransformException, SAXException, IOException, ParserConfigurationException, TransformerException { File newTempDir = TestingUtil.getNewTempDir(); getAce().setBaseName(AtlasConfig.DEFAULTBASENAME); File created = writeBuildxml(newTempDir, getAce().getBaseName()); assertNull(created); getAce().setBaseName( AtlasConfig.DEFAULTBASENAME + System.currentTimeMillis()); created = writeBuildxml(newTempDir, getAce().getBaseName()); assertNotNull(created); assertTrue(created.exists()); created = writeBuildxml(newTempDir, getAce().getBaseName() + "/"); assertNotNull(created); assertTrue(created.exists()); FileUtils.deleteDirectory(newTempDir); } |
### Question:
ASProps { protected static void init(String propertiesFilename, String appDirname) { ASProps.propertiesFilename = propertiesFilename; ASProps.appDirname = appDirname; try { properties.load(new FileInputStream(getPropertiesFile())); } catch (FileNotFoundException e) { } catch (IOException e) { LOGGER.error(e); } } static final String get(Keys key); static boolean get(Keys key, boolean def); static String get(Keys key, String def); static Integer getInt(Keys key, Integer def); static Component getOwner(); static void resetProperties(); static final void set(Keys key, Integer value); static final void set(Keys key, String value); static void setOwner(Window owner); static void store(); static final String DEFAULT_CHARSET_NAME; static final String PROPERTIES_FILENAME; static final String PROPERTIES_FOLDER; }### Answer:
@Test public void testInit() { ASProps.init(ASProps.PROPERTIES_FILENAME, ASProps.PROPERTIES_FOLDER); } |
### Question:
FeatureClassification extends Classification { public StyledFeaturesInterface<?> getStyledFeatures() { return styledFeatures; } FeatureClassification(final StyledFeaturesInterface<?> styledFeatures); FeatureClassification(
final StyledFeaturesInterface<?> styledFeatures,
final String value_field_name); FeatureClassification(StyledFeaturesInterface<?> styledFeatures,
final String value_field_name, final String normalizer_field_name); @Override BufferedImage createHistogramImage(boolean showMean, boolean showSd,
int histogramBins, String label_xachsis); ComboBoxModel createNormalizationFieldsComboBoxModel(); @Override void dispose(); String getNormalizer_field_name(); @Override synchronized DynamicBin1D getStatistics(); StyledFeaturesInterface<?> getStyledFeatures(); String getValue_field_name(); ComboBoxModel getValueFieldsComboBoxModel(); void onFilterChanged(); void setNormalizer_field_name(String normalizer_field_name); void setStyledFeatures(StyledFeaturesInterface<?> styledFeatures); void setValue_field_name(final String value_field_name); void setCacheEnabled(boolean cacheEnabled); boolean isCacheEnabled(); static final String NORMALIZE_NULL_VALUE_IN_COMBOBOX; }### Answer:
@Test public void testNoDataValueviaAMD() throws IOException, InterruptedException { FeatureClassification clfcn = new FeatureClassification(new StyledFS( featureSource_polygon), "SQKM_CNTRY"); clfcn.getStyledFeatures().getAttributeMetaDataMap().get("SQKM_CNTRY") .addNodataValue(0.0); clfcn.setRecalcAutomatically(false); clfcn.setMethod(CLASSIFICATION_METHOD.EI); clfcn.setNumClasses(4); clfcn.calculateClassLimitsBlocking(); assertTrue(testBreaks(clfcn.getClassLimits(), 1.668, 4212986.250999999, 8425970.833999999, 1.2638955416999998E7, 1.685194E7)); } |
### Question:
TextRuleList extends AbstractRulesList { public static Filter classLanguageFilter(String lang) { if (lang == null) lang = XMapPane.ENV_LANG_DEFAULT; Expression exEnv = ff.function("env", ff.literal(XMapPane.ENV_LANG), ff.literal(XMapPane.ENV_LANG_DEFAULT)); Filter filter = ff.equals(ff.literal(lang), exEnv); return filter; } TextRuleList(StyledFeaturesInterface<?> styledFeatures,
boolean withDefaults); TextRuleList(StyledFeaturesInterface<?> styledFeatures,
GeometryForm geometryForm, boolean withDefaults); static Filter classLanguageFilter(String lang); int addClass(TextSymbolizer ts, String ruleName, Filter filter,
boolean enabled, String lang, Double minScale, Double maxScale); int addDefaultClass(); int addDefaultClass(String lang); int countClasses(); boolean existsClass(Filter filter, String lang); Filter getClassFilter(int index); String getClassLang(int index); TextSymbolizer getClassSymbolizer(int index); ArrayList<String> getDefaultLanguages(); @Deprecated String getRuleName(); String getRuleName(int index); List<String> getRuleNames(); @Override List<Rule> getRules(); @Deprecated int getSelIdx(); StyledFeaturesInterface<?> getStyledFeatures(); @Deprecated TextSymbolizer getSymbolizer(); List<TextSymbolizer> getSymbolizers(); boolean hasDefault(); void importClassesFromStyle(RulesListInterface symbRL,
Component owner); @Override void importRules(List<Rule> rules); Boolean isClassEnabled(int index); @Override void parseMetaInfoString(String metaInfoString, FeatureTypeStyle fts); void removeClass(int idx); void removeClassEnabled(int classIdx); void removeClassMaxScale(int classIdx); void removeClassMinScale(int classIdx); void setClassEnabled(int index, boolean b); void setClassFilter(int index, Filter filter); void setClassMaxScale(int index, Double maxValue); void setClassMinMaxScales(int index, Double minValue, Double maxValue); void setClassMinScale(int index, Double minValue); void setRuleNames(List<String> ruleNames); @Deprecated void setSelIdx(int selIdx); void setSymbolizers(List<TextSymbolizer> symbolizers); static final String DEFAULT_CLASS_RULENAME; static final Filter DEFAULT_FILTER_ALL_OTHERS; static final PropertyIsEqualTo oldClassesDisabledFilter; static final PropertyIsEqualTo oldClassesEnabledFilter; }### Answer:
@Test public void testLanguageFilterEnvFunction() throws IOException { Filter filter = TextRuleList.classLanguageFilter("de"); System.out.println(filter); assertEquals("[ de = env([LANG], [XX]) ]", filter.toString()); FeatureCollection<SimpleFeatureType, SimpleFeature> testFeatures = TestDatasetsVector.arabicInHeader .getFeatureCollection(); Iterator<SimpleFeature> it = testFeatures.iterator(); try { SimpleFeature f = it.next(); EnvFunction.setLocalValue("LANG", "de"); assertTrue(filter.evaluate(f)); EnvFunction.setLocalValue("LANG", "en"); assertFalse(filter.evaluate(f)); } finally { testFeatures.close(it); } } |
### Question:
TextRuleList extends AbstractRulesList { public boolean existsClass(Filter filter, String lang) { for (int i = 0; i < countClasses(); i++) { if (getClassLang(i) == null && lang != null) continue; if (getClassLang(i) != null && !getClassLang(i).equals(lang)) continue; if (filter != null && getClassFilter(i).toString().equals(filter.toString())) return true; } return false; } TextRuleList(StyledFeaturesInterface<?> styledFeatures,
boolean withDefaults); TextRuleList(StyledFeaturesInterface<?> styledFeatures,
GeometryForm geometryForm, boolean withDefaults); static Filter classLanguageFilter(String lang); int addClass(TextSymbolizer ts, String ruleName, Filter filter,
boolean enabled, String lang, Double minScale, Double maxScale); int addDefaultClass(); int addDefaultClass(String lang); int countClasses(); boolean existsClass(Filter filter, String lang); Filter getClassFilter(int index); String getClassLang(int index); TextSymbolizer getClassSymbolizer(int index); ArrayList<String> getDefaultLanguages(); @Deprecated String getRuleName(); String getRuleName(int index); List<String> getRuleNames(); @Override List<Rule> getRules(); @Deprecated int getSelIdx(); StyledFeaturesInterface<?> getStyledFeatures(); @Deprecated TextSymbolizer getSymbolizer(); List<TextSymbolizer> getSymbolizers(); boolean hasDefault(); void importClassesFromStyle(RulesListInterface symbRL,
Component owner); @Override void importRules(List<Rule> rules); Boolean isClassEnabled(int index); @Override void parseMetaInfoString(String metaInfoString, FeatureTypeStyle fts); void removeClass(int idx); void removeClassEnabled(int classIdx); void removeClassMaxScale(int classIdx); void removeClassMinScale(int classIdx); void setClassEnabled(int index, boolean b); void setClassFilter(int index, Filter filter); void setClassMaxScale(int index, Double maxValue); void setClassMinMaxScales(int index, Double minValue, Double maxValue); void setClassMinScale(int index, Double minValue); void setRuleNames(List<String> ruleNames); @Deprecated void setSelIdx(int selIdx); void setSymbolizers(List<TextSymbolizer> symbolizers); static final String DEFAULT_CLASS_RULENAME; static final Filter DEFAULT_FILTER_ALL_OTHERS; static final PropertyIsEqualTo oldClassesDisabledFilter; static final PropertyIsEqualTo oldClassesEnabledFilter; }### Answer:
@Test public void testExistsClass() throws IOException, CQLException { TextRuleList trl = new TextRuleList( TestDatasetsVector.arabicInHeader.getStyledFS(), false); trl.setEnabled(true); trl.addDefaultClass(); trl.addDefaultClass("de"); trl.addClass(StylingUtil.STYLE_BUILDER.createTextSymbolizer(), "testRuleName_DE", ECQL.toFilter("SURFACE>2000"), true, "de", null, null); assertFalse(trl.existsClass(ECQL.toFilter("1=5"), "de")); assertFalse(trl.existsClass(ECQL.toFilter("1=5"), null)); assertFalse(trl.existsClass(ECQL.toFilter("1=5"), null)); assertFalse(trl.existsClass(ECQL.toFilter("SURFACE>2000"), null)); assertTrue(trl.existsClass(ECQL.toFilter("SURFACE>2000"), "de")); assertTrue(trl .existsClass(TextRuleList.DEFAULT_FILTER_ALL_OTHERS, null)); } |
### Question:
RasterRulesList_DistinctValues extends RasterRulesListColormap implements UniqueValuesRulesListInterface<Double> { @Override public void importColorMap(ColorMap cm) { QuantileBin1D ops = new QuantileBin1D(1.); for (ColorMapEntry cme : cm.getColorMapEntries()) { importValuesLabelsQuantitiesColors(cme); ops.add(getOpacities().get(getOpacities().size() - 1)); } if (ops.median() >= 0 && ops.median() < 1.) setOpacity(ops.median()); else setOpacity(1.); } RasterRulesList_DistinctValues(StyledRasterInterface<?> styledRaster); @Override void applyPalette(JComponent parentGui); @Override void importColorMap(ColorMap cm); Integer addAllValues(AtlasSwingWorker<Integer> sw); @Override boolean addUniqueValue(final Double uniqueValue); Set<Double> getAllUniqueValuesThatAreNotYetIncluded(); void move(int row, int delta); @Override void applyOpacity(); }### Answer:
@Test public void testColorMapImport1() { ColorMap cm = StylingUtil.STYLE_BUILDER.createColorMap(new String[] {"A","B","C"}, new double[] {1,2,3}, new Color[]{Color.red, Color.blue, Color.green}, ColorMap.TYPE_VALUES); RasterRulesList_DistinctValues rl = new RasterRulesList_DistinctValues(styledRaster); rl.importColorMap(cm); assertEquals(3,rl.getValues().size()); assertEquals(3,rl.getLabels().size()); assertEquals(3,rl.getColors().size()); assertEquals(3,rl.getOpacities().size()); assertEquals(3,rl.getNumClasses()); assertEquals(Color.red, rl.getColors().get(0)); assertEquals("C", rl.getLabels().get(2).toString()); testExportAndImport(rl, new RasterRulesList_DistinctValues( styledRaster)); RasterLegendData rld = StyledLayerUtil.generateRasterLegendData(rl.getColorMap(), true,null); assertEquals(3,rld.size()); assertEquals("A",rld.get(1.).toString()); assertEquals("B",rld.get(2.).toString()); assertEquals("C",rld.get(3.).toString()); } |
### Question:
RasterRulesListColormap extends RasterRulesList { @Override public void importRules(List<Rule> rules) { pushQuite(); try { if (rules.size() > 1) { LOGGER.warn("Importing a " + this.getClass().getSimpleName() + " with " + rules.size() + " rules"); } Rule rule = rules.get(0); RasterSymbolizer rs = (RasterSymbolizer) rule.symbolizers().get(0); { ChannelSelection channelSelection = rs.getChannelSelection(); if (channelSelection != null) { SelectedChannelType grayChannel = channelSelection .getGrayChannel(); if (grayChannel != null) { band = Integer.valueOf(grayChannel.getChannelName()) - 1; } } } ColorMap cm = rs.getColorMap(); importColorMap(cm); org.opengis.filter.Filter filter = rule.getFilter(); filter = parseAbstractRlSettings(filter); } finally { popQuite(); } } RasterRulesListColormap(RulesListType rlt,
StyledRasterInterface<?> styledRaster, int colorMapType); @Override String extendMetaInfoString(); ColorMap getColorMap(); ArrayList<Color> getColors(); ArrayList<Translation> getLabels(); int getNumClasses(); int getNumClassesVisible(); ArrayList<Double> getOpacities(); BrewerPalette getPalette(); @Override final List<Rule> getRules(); ArrayList<Double> getValues(); @Override void importRules(List<Rule> rules); abstract void importColorMap(ColorMap cm); void add(Double value, Double opacity, Color color, Translation label); void set(int idx, Double value, Double opacity, Color color,
Translation label); void setOrAdd(int idx, Double value, Double opacity, Color color,
Translation label); @Override void parseMetaInfoString(String metaInfoString, FeatureTypeStyle fts); void removeAll(); void removeIdx(int index); void setOpacity(int rowIndex, Double newOp); void setPalette(BrewerPalette palette); void reset(); abstract void applyPalette(JComponent parentGui); void setBand(int band); int getBand(); @Override /** * Caclulates the overall opacity of this RulesList as the median iof all opacities. */ Double getOpacity(); }### Answer:
@Test public void testImportRules() { } |
### Question:
BooleanConverter extends DefaultObjectConverter<Boolean> { @Override public String toString(Boolean object, ConverterContext context) { if (Boolean.FALSE.equals(object)) { return getFalse(); } else if (Boolean.TRUE.equals(object)) { return getTrue(); } else { return getNull(); } } BooleanConverter(); @Override String toString(Boolean object, ConverterContext context); @Override Boolean fromString(String string, ConverterContext context); }### Answer:
@Test public void testToString() throws Exception { Assert.assertEquals("True", _converter.toString(true)); Assert.assertEquals("False", _converter.toString(false)); } |
### Question:
BooleanConverter extends DefaultObjectConverter<Boolean> { @Override public Boolean fromString(String string, ConverterContext context) { if (string.equalsIgnoreCase(getTrue())) { return Boolean.TRUE; } else if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; } else if (string.equalsIgnoreCase(getFalse())) { return Boolean.FALSE; } else if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; } else { return null; } } BooleanConverter(); @Override String toString(Boolean object, ConverterContext context); @Override Boolean fromString(String string, ConverterContext context); }### Answer:
@Test public void testFromString() throws Exception { Assert.assertEquals(Boolean.TRUE, _converter.fromString("true")); Assert.assertEquals(Boolean.TRUE, _converter.fromString("True")); Assert.assertEquals(Boolean.FALSE, _converter.fromString("false")); Assert.assertEquals(Boolean.FALSE, _converter.fromString("False")); } |
### Question:
LocalDateConverter extends TemporalAccessConverter<LocalDate> { synchronized public LocalDate fromString(String string, String pattern) { return LocalDate.from(DateTimeFormatter.ofPattern(pattern).parse(string)); } LocalDateConverter(); synchronized LocalDate fromString(String string, String pattern); @Override synchronized LocalDate fromString(String string, ConverterContext context); }### Answer:
@Test public void testFromString() throws Exception { Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("Jan 1, 2000")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("1/1/00")); Assert.assertEquals(LocalDate.of(2003, 1, 2), _converter.fromString("01/02/03")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("1/1/2000")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("January 1, 2000")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("Jan 01, 2000")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("January 01, 2000")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("2000-01-01")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("00-01-01")); Assert.assertEquals(LocalDate.of(2003, 2, 1), _converter.fromString("03-02-01")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("20000101")); Assert.assertEquals(LocalDate.of(2000, 1, 1), _converter.fromString("1-Jan-2000")); } |
### Question:
PercentConverter extends DoubleConverter { @Override public Double fromString(String string, ConverterContext context) { Number number = numberFromString(string, context); if (number == null) { number = Double.parseDouble(string); } if (string != null && !string.trim().endsWith("%") && number != null) { number = number.doubleValue() / 100; } return number != null ? number.doubleValue() : null; } PercentConverter(); PercentConverter(Locale locale); PercentConverter(NumberFormat format); @Override Double fromString(String string, ConverterContext context); static final ConverterContext CONTEXT; }### Answer:
@Test public void testFromString() throws Exception { Assert.assertEquals(0.5, _converter.fromString("50%"), 0.001); Assert.assertEquals(0.5, _converter.fromString("50"), 0.001); Assert.assertEquals(0.005, _converter.fromString("0.5"), 0.001); } |
### Question:
DecorationPane extends StackPane implements DecorationSupport { public Parent getContent() { return _content; } DecorationPane(); DecorationPane(Parent content); Parent getContent(); void setContent(Parent content); @Override void positionInArea(Node child, double areaX, double areaY, double areaWidth, double areaHeight, double areaBaselineOffset, HPos hAlignment, VPos vAlignment); }### Answer:
@Test public void loadFXMLWithExplicitContent() throws Exception { URL resource = DecorationPaneTest.class.getClassLoader().getResource("jidefx/scene/control/decoration/DecorationPaneTestExplicitContent.fxml"); FXMLLoader loader = new FXMLLoader(resource); loader.load(); DecorationPaneTestController controller = loader.getController(); assertNotNull(controller.decorationPane); assertNotNull(controller.content); assertEquals(controller.content, controller.decorationPane.getContent()); }
@Test public void loadFXMLWithImplicitContent() throws Exception { URL resource = DecorationPaneTest.class.getClassLoader().getResource("jidefx/scene/control/decoration/DecorationPaneTestImplicitContent.fxml"); FXMLLoader loader = new FXMLLoader(resource); loader.load(); DecorationPaneTestController controller = loader.getController(); assertNotNull(controller.decorationPane); assertNotNull(controller.content); assertEquals(controller.content, controller.decorationPane.getContent()); } |
### Question:
HelloWorld { public void setPhrase( String phrase ) throws IllegalArgumentException { if( phrase == null ) { throw new IllegalArgumentException( "Phrase may not be null " ); } this.phrase = phrase; } String getPhrase(); void setPhrase( String phrase ); String getName(); void setName( String name ); String say(); }### Answer:
@Test public void givenHelloWorldWhenSetInvalidPhraseThenThrowException() { try { helloWorld.setPhrase( null ); fail( "Should not be allowed to set phrase to null" ); } catch( IllegalArgumentException e ) { } } |
### Question:
QueryBuilderFactoryImpl implements QueryBuilderFactory { @Override public <T> QueryBuilder<T> newQueryBuilder( final Class<T> resultType ) { NotQueryableException.throwIfNotQueryable( resultType ); final ServiceReference<EntityFinder> serviceReference; try { serviceReference = finder.findService( EntityFinder.class ); return new QueryBuilderImpl<>( serviceReference.get(), resultType, null ); } catch( NoSuchServiceTypeException e ) { return new QueryBuilderImpl<>( null, resultType, null ); } } QueryBuilderFactoryImpl( ServiceFinder finder ); @Override QueryBuilder<T> newQueryBuilder( final Class<T> resultType ); }### Answer:
@Test public void givenWhereQueryWhenWhereClauseLimitsToRangeExpectLimitedResult() { final QueryBuilder<TestComposite> qb = queryBuilderFactory.newQueryBuilder( TestComposite.class ); TestComposite template = templateFor( TestComposite.class ); Query<TestComposite> query = qb.where( and( ge( template.b(), 3 ), lt( template.b(), 5 ) ) ).newQuery( composites ); verifyOrder( query, "34" ); }
@Test public void givenPlainQueryWhenFindEntityExpectFirstEntityReturned() { Query<TestComposite> query = queryBuilderFactory.newQueryBuilder( TestComposite.class ).newQuery( composites ); assertThat( query.find().a().get(), equalTo( "A" ) ); assertThat( query.count(), equalTo( 6L ) ); }
@Test public void givenPlainQueryWhenOrderByFirstPropertyExpectOrderedResult() { Query<TestComposite> query = queryBuilderFactory.newQueryBuilder( TestComposite.class ).newQuery( composites ); TestComposite template = templateFor( TestComposite.class ); query.orderBy( orderBy( template.a() ) ); verifyOrder( query, "612345" ); }
@Test public void givenPlainQueryWhenOrderBySecondPropertyExpectOrderedResult() { Query<TestComposite> query = queryBuilderFactory.newQueryBuilder( TestComposite.class ).newQuery( composites ); TestComposite template = templateFor( TestComposite.class ); query.orderBy( orderBy( template.b() ) ); verifyOrder( query, "123456" ); }
@Test public void givenPlainQueryWhenOrderByTwoPropertiesExpectOrderedResult() { Query<TestComposite> query = queryBuilderFactory.newQueryBuilder( TestComposite.class ).newQuery( composites ); TestComposite template = templateFor( TestComposite.class ); query.orderBy( orderBy( template.a() ), orderBy( template.b() ) ); verifyOrder( query, "162345" ); }
@Test public void givenPlainQueryWhenMaxedResultExpectLimitedResult() { Query<TestComposite> query = queryBuilderFactory.newQueryBuilder( TestComposite.class ).newQuery( composites ); query.maxResults( 5 ); verifyOrder( query, "62345" ); }
@Test public void givenPlainQueryWhenFirstResultIsBeyondFirstElementExpectLimitedResult() { Query<TestComposite> query = queryBuilderFactory.newQueryBuilder( TestComposite.class ).newQuery( composites ); query.firstResult( 2 ); verifyOrder( query, "3451" ); }
@Test public void givenPlainQueryWhenFindEntityExpectFirstEntityReturned() { Query<TestComposite> query = queryBuilderFactory.newQueryBuilder( TestComposite.class ).newQuery( composites ); assertEquals( "A", query.find().a().get() ); assertEquals( 6, query.count() ); } |
### Question:
UsageGraph { public List<K> resolveOrder() throws BindingException { if( resolved == null ) { buildUsageGraph(); resolved = new LinkedList<>(); for( K item : data ) { int pos = resolved.size(); for( K entry : resolved ) { if( transitiveUse( entry, item ) ) { pos = resolved.indexOf( entry ); break; } } resolved.add( pos, item ); } } return resolved; } UsageGraph( Collection<K> data, Use<K> use, boolean allowCyclic ); boolean transitiveUse( K source, K other ); void invalidate(); List<K> resolveOrder(); }### Answer:
@Test public void whenAskingForDependencyGivenThatGraphContainsCyclicDepThenDetectTheError() throws Exception { Thing thing1 = new Thing(); Thing thing2 = new Thing(); Thing thing3 = new Thing(); Thing thing4 = new Thing(); Thing thing5 = new Thing(); Thing thing6 = new Thing(); Thing thing7 = new Thing(); thing1.uses.add( thing3 ); thing2.uses.add( thing3 ); thing3.uses.add( thing4 ); thing4.uses.add( thing5 ); thing5.uses.add( thing1 ); thing1.uses.add( thing6 ); thing7.uses.add( thing1 ); thing7.uses.add( thing2 ); thing7.uses.add( thing4 ); List<Thing> data = new ArrayList<Thing>(); data.add( thing7 ); data.add( thing4 ); data.add( thing1 ); data.add( thing3 ); data.add( thing6 ); data.add( thing5 ); data.add( thing2 ); randomize( data ); UsageGraph<Thing> deps = new UsageGraph<Thing>( data, new Userator(), false ); try { List<Thing> resolved = deps.resolveOrder(); fail( "Cyclic Dependency Not Detected." ); } catch( BindingException e ) { } }
@Test public void whenAskingForDependencyGivenThatGraphContainsCyclicDepThenDetectTheError() throws Exception { Thing thing1 = new Thing(); Thing thing2 = new Thing(); Thing thing3 = new Thing(); Thing thing4 = new Thing(); Thing thing5 = new Thing(); Thing thing6 = new Thing(); Thing thing7 = new Thing(); thing1.uses.add( thing3 ); thing2.uses.add( thing3 ); thing3.uses.add( thing4 ); thing4.uses.add( thing5 ); thing5.uses.add( thing1 ); thing1.uses.add( thing6 ); thing7.uses.add( thing1 ); thing7.uses.add( thing2 ); thing7.uses.add( thing4 ); List<Thing> data = new ArrayList<Thing>(); data.add( thing7 ); data.add( thing4 ); data.add( thing1 ); data.add( thing3 ); data.add( thing6 ); data.add( thing5 ); data.add( thing2 ); randomize( data ); UsageGraph<Thing> deps = new UsageGraph<Thing>( data, new Userator(), false ); try { List<Thing> resolved = deps.resolveOrder(); Assert.fail( "Cyclic Dependency Not Detected." ); } catch( BindingException e ) { } } |
### Question:
UsageGraph { public boolean transitiveUse( K source, K other ) throws BindingException { if( transitive == null ) { buildUsageGraph(); } return transitive.containsKey( source ) && transitive.get( source ).contains( other ); } UsageGraph( Collection<K> data, Use<K> use, boolean allowCyclic ); boolean transitiveUse( K source, K other ); void invalidate(); List<K> resolveOrder(); }### Answer:
@Test public void whenAskingForResolveOrderGivenThatGraphContainsCyclicDepThenDetectTheError() throws Exception { Thing thing1 = new Thing(); Thing thing2 = new Thing(); Thing thing3 = new Thing(); Thing thing4 = new Thing(); Thing thing5 = new Thing(); Thing thing6 = new Thing(); Thing thing7 = new Thing(); thing1.uses.add( thing3 ); thing2.uses.add( thing3 ); thing3.uses.add( thing4 ); thing4.uses.add( thing5 ); thing5.uses.add( thing1 ); thing1.uses.add( thing6 ); thing7.uses.add( thing1 ); thing7.uses.add( thing2 ); thing7.uses.add( thing4 ); List<Thing> data = new ArrayList<Thing>(); data.add( thing7 ); data.add( thing4 ); data.add( thing1 ); data.add( thing3 ); data.add( thing6 ); data.add( thing5 ); data.add( thing2 ); randomize( data ); UsageGraph<Thing> deps = new UsageGraph<Thing>( data, new Userator(), false ); try { assertThat( deps.transitiveUse( thing1, thing3 ), is( true ) ); fail( "Cyclic Dependency Not Detected." ); } catch( BindingException e ) { } }
@Test public void whenAskingForResolveOrderGivenThatGraphContainsCyclicDepThenDetectTheError() throws Exception { Thing thing1 = new Thing(); Thing thing2 = new Thing(); Thing thing3 = new Thing(); Thing thing4 = new Thing(); Thing thing5 = new Thing(); Thing thing6 = new Thing(); Thing thing7 = new Thing(); thing1.uses.add( thing3 ); thing2.uses.add( thing3 ); thing3.uses.add( thing4 ); thing4.uses.add( thing5 ); thing5.uses.add( thing1 ); thing1.uses.add( thing6 ); thing7.uses.add( thing1 ); thing7.uses.add( thing2 ); thing7.uses.add( thing4 ); List<Thing> data = new ArrayList<Thing>(); data.add( thing7 ); data.add( thing4 ); data.add( thing1 ); data.add( thing3 ); data.add( thing6 ); data.add( thing5 ); data.add( thing2 ); randomize( data ); UsageGraph<Thing> deps = new UsageGraph<Thing>( data, new Userator(), false ); try { assertTrue( deps.transitiveUse( thing1, thing3 ) ); Assert.fail( "Cyclic Dependency Not Detected." ); } catch( BindingException e ) { } } |
### Question:
ValueBuilderTemplate { public T newInstance( ModuleDescriptor module ) { ValueBuilder<T> builder = module.instance().newValueBuilder( type ); build( builder.prototype() ); return builder.newInstance(); } protected ValueBuilderTemplate( Class<T> type ); T newInstance( ModuleDescriptor module ); }### Answer:
@Test public void testTemplate() { new TestBuilder( "Rickard" ).newInstance( module ); }
@Test public void testAnonymousTemplate() { new ValueBuilderTemplate<TestValue>( TestValue.class ) { @Override protected void build( TestValue prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module ); } |
### Question:
Classes { public static Stream<? extends Type> interfacesOf( Stream<? extends Type> types ) { return types.flatMap( INTERFACES_OF ); } private Classes(); static Type typeOf( AccessibleObject from ); static Stream<Type> typesOf( Stream<? extends Type> types ); static Stream<? extends Type> typesOf( Type type ); static Stream<? extends Type> interfacesOf( Stream<? extends Type> types ); static Stream<? extends Type> interfacesOf( Type type ); static Stream<Class<?>> classHierarchy( Class<?> type ); static Type wrapperClass( Type type ); static Predicate<Class<?>> isAssignableFrom( final Class<?> clazz ); static Predicate<Object> instanceOf( final Class<?> clazz ); static Predicate<Class<?>> hasModifier( final int classModifier ); static Function<Type, Stream<T>> forClassHierarchy( final Function<Class<?>, Stream<T>> function ); static Function<Type, Stream<T>> forTypes( final Function<Type, Stream<T>> function ); @SuppressWarnings( "raw" ) static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String simpleGenericNameOf( Type type ); @SuppressWarnings( "UnusedDeclaration" ) static AnnotationType findAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Predicate<Member> memberNamed( final String name ); @SuppressWarnings( "raw" ) static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); @SuppressWarnings( "raw" ) static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static Predicate<ModelDescriptor> modelTypeSpecification( final String className ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> exactTypeSpecification( final Class type ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> assignableTypeSpecification( final Class<?> type ); @SuppressWarnings( "raw" ) static String toString( Stream<? extends Class> types ); static Function<Type, String> toClassName(); static final Function<Type, Class<?>> RAW_CLASS; }### Answer:
@Test public void givenClassWithInterfacesWhenInterfacesOfThenGetCorrectSet() { assertThat( "one interface returned", interfacesOf( A.class ).count(), equalTo( 1L ) ); assertThat( "two interface returned", interfacesOf( B.class ).count(), equalTo( 2L ) ); assertThat( "tree interface returned", interfacesOf( C.class ).count(), equalTo( 4L ) ); }
@Test public void givenClassesWithInterfacesWhenGetInterfacesWithMethodsThenGetCorrectSet() { assertThat( "one interface returned", interfacesOf( C.class ).filter( Methods.HAS_METHODS ) .count(), equalTo( 1L ) ); boolean isIn = interfacesOf( C.class ).filter( Methods.HAS_METHODS ) .anyMatch( B.class::equals ); assertThat( "correct interface returned", isIn, is( true ) ); } |
### Question:
Classes { @SuppressWarnings( "raw" ) public static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ) { Set<Class<?>> newSet = new LinkedHashSet<>(); for( Class type : interfaces ) { if( type.isInterface() && type.getDeclaredMethods().length > 0 ) { newSet.add( type ); } } return newSet; } private Classes(); static Type typeOf( AccessibleObject from ); static Stream<Type> typesOf( Stream<? extends Type> types ); static Stream<? extends Type> typesOf( Type type ); static Stream<? extends Type> interfacesOf( Stream<? extends Type> types ); static Stream<? extends Type> interfacesOf( Type type ); static Stream<Class<?>> classHierarchy( Class<?> type ); static Type wrapperClass( Type type ); static Predicate<Class<?>> isAssignableFrom( final Class<?> clazz ); static Predicate<Object> instanceOf( final Class<?> clazz ); static Predicate<Class<?>> hasModifier( final int classModifier ); static Function<Type, Stream<T>> forClassHierarchy( final Function<Class<?>, Stream<T>> function ); static Function<Type, Stream<T>> forTypes( final Function<Type, Stream<T>> function ); @SuppressWarnings( "raw" ) static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String simpleGenericNameOf( Type type ); @SuppressWarnings( "UnusedDeclaration" ) static AnnotationType findAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Predicate<Member> memberNamed( final String name ); @SuppressWarnings( "raw" ) static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); @SuppressWarnings( "raw" ) static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static Predicate<ModelDescriptor> modelTypeSpecification( final String className ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> exactTypeSpecification( final Class type ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> assignableTypeSpecification( final Class<?> type ); @SuppressWarnings( "raw" ) static String toString( Stream<? extends Class> types ); static Function<Type, String> toClassName(); static final Function<Type, Class<?>> RAW_CLASS; }### Answer:
@Test public void givenClassWithInterfacesWhenGetInterfacesWithMethodsThenGetCorrectSet() { HashSet<Class<?>> interfaces = new HashSet<Class<?>>(); interfaces.add( B.class ); Set<Class<?>> types = interfacesWithMethods( interfaces ); assertThat( "one interface returned", types.size(), equalTo( 1 ) ); assertThat( "correct interface returned", types.contains( B.class ), is( true ) ); } |
### Question:
Classes { @SuppressWarnings( "raw" ) public static String toURI( final Class clazz ) throws NullPointerException { return toURI( clazz.getName() ); } private Classes(); static Type typeOf( AccessibleObject from ); static Stream<Type> typesOf( Stream<? extends Type> types ); static Stream<? extends Type> typesOf( Type type ); static Stream<? extends Type> interfacesOf( Stream<? extends Type> types ); static Stream<? extends Type> interfacesOf( Type type ); static Stream<Class<?>> classHierarchy( Class<?> type ); static Type wrapperClass( Type type ); static Predicate<Class<?>> isAssignableFrom( final Class<?> clazz ); static Predicate<Object> instanceOf( final Class<?> clazz ); static Predicate<Class<?>> hasModifier( final int classModifier ); static Function<Type, Stream<T>> forClassHierarchy( final Function<Class<?>, Stream<T>> function ); static Function<Type, Stream<T>> forTypes( final Function<Type, Stream<T>> function ); @SuppressWarnings( "raw" ) static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String simpleGenericNameOf( Type type ); @SuppressWarnings( "UnusedDeclaration" ) static AnnotationType findAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Predicate<Member> memberNamed( final String name ); @SuppressWarnings( "raw" ) static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); @SuppressWarnings( "raw" ) static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static Predicate<ModelDescriptor> modelTypeSpecification( final String className ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> exactTypeSpecification( final Class type ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> assignableTypeSpecification( final Class<?> type ); @SuppressWarnings( "raw" ) static String toString( Stream<? extends Class> types ); static Function<Type, String> toClassName(); static final Function<Type, Class<?>> RAW_CLASS; }### Answer:
@Test public void givenClassNameWhenToUriThenUriIsReturned() { assertThat( "URI is correct", Classes.toURI( A.class ), equalTo( "urn:polygene:type:org.apache.polygene.api.util.ClassesTest-A" ) ); } |
### Question:
Classes { public static String toClassName( String uri ) throws NullPointerException { uri = uri.substring( "urn:polygene:type:".length() ); uri = denormalizeURIToClass( uri ); return uri; } private Classes(); static Type typeOf( AccessibleObject from ); static Stream<Type> typesOf( Stream<? extends Type> types ); static Stream<? extends Type> typesOf( Type type ); static Stream<? extends Type> interfacesOf( Stream<? extends Type> types ); static Stream<? extends Type> interfacesOf( Type type ); static Stream<Class<?>> classHierarchy( Class<?> type ); static Type wrapperClass( Type type ); static Predicate<Class<?>> isAssignableFrom( final Class<?> clazz ); static Predicate<Object> instanceOf( final Class<?> clazz ); static Predicate<Class<?>> hasModifier( final int classModifier ); static Function<Type, Stream<T>> forClassHierarchy( final Function<Class<?>, Stream<T>> function ); static Function<Type, Stream<T>> forTypes( final Function<Type, Stream<T>> function ); @SuppressWarnings( "raw" ) static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String simpleGenericNameOf( Type type ); @SuppressWarnings( "UnusedDeclaration" ) static AnnotationType findAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Predicate<Member> memberNamed( final String name ); @SuppressWarnings( "raw" ) static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); @SuppressWarnings( "raw" ) static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static Predicate<ModelDescriptor> modelTypeSpecification( final String className ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> exactTypeSpecification( final Class type ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> assignableTypeSpecification( final Class<?> type ); @SuppressWarnings( "raw" ) static String toString( Stream<? extends Class> types ); static Function<Type, String> toClassName(); static final Function<Type, Class<?>> RAW_CLASS; }### Answer:
@Test public void givenUriWhenToClassNameThenClassNameIsReturned() { assertThat( "Class name is correct", Classes.toClassName( "urn:polygene:type:org.apache.polygene.api.util.ClassesTest-A" ), equalTo( "org.apache.polygene.api.util.ClassesTest$A" ) ); } |
### Question:
HelloWorld { public void setName( String name ) throws IllegalArgumentException { if( name == null ) { throw new IllegalArgumentException( "Name may not be null " ); } this.name = name; } String getPhrase(); void setPhrase( String phrase ); String getName(); void setName( String name ); String say(); }### Answer:
@Test public void givenHelloWorldWhenSetInvalidNameThenThrowException() { try { helloWorld.setName( null ); fail( "Should not be allowed to set name to null" ); } catch( IllegalArgumentException e ) { } } |
### Question:
Classes { @SuppressWarnings( "raw" ) public static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ) { Type type = resolveTypeVariable( name, declaringClass, new HashMap<>(), topClass ); if( type == null ) { type = Object.class; } return type; } private Classes(); static Type typeOf( AccessibleObject from ); static Stream<Type> typesOf( Stream<? extends Type> types ); static Stream<? extends Type> typesOf( Type type ); static Stream<? extends Type> interfacesOf( Stream<? extends Type> types ); static Stream<? extends Type> interfacesOf( Type type ); static Stream<Class<?>> classHierarchy( Class<?> type ); static Type wrapperClass( Type type ); static Predicate<Class<?>> isAssignableFrom( final Class<?> clazz ); static Predicate<Object> instanceOf( final Class<?> clazz ); static Predicate<Class<?>> hasModifier( final int classModifier ); static Function<Type, Stream<T>> forClassHierarchy( final Function<Class<?>, Stream<T>> function ); static Function<Type, Stream<T>> forTypes( final Function<Type, Stream<T>> function ); @SuppressWarnings( "raw" ) static Set<Class<?>> interfacesWithMethods( Set<Class<?>> interfaces ); static String simpleGenericNameOf( Type type ); @SuppressWarnings( "UnusedDeclaration" ) static AnnotationType findAnnotationOfTypeOrAnyOfSuperTypes( Class<?> type, Class<AnnotationType> annotationClass ); static Predicate<Member> memberNamed( final String name ); @SuppressWarnings( "raw" ) static Type resolveTypeVariable( TypeVariable name, Class declaringClass, Class topClass ); @SuppressWarnings( "raw" ) static String toURI( final Class clazz ); static String toURI( String className ); static String toClassName( String uri ); static String normalizeClassToURI( String className ); static String denormalizeURIToClass( String uriPart ); static Predicate<ModelDescriptor> modelTypeSpecification( final String className ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> exactTypeSpecification( final Class type ); @SuppressWarnings( "raw" ) static Predicate<ModelDescriptor> assignableTypeSpecification( final Class<?> type ); @SuppressWarnings( "raw" ) static String toString( Stream<? extends Class> types ); static Function<Type, String> toClassName(); static final Function<Type, Class<?>> RAW_CLASS; }### Answer:
@Test public void givenTypeVariableWhenResolveThenResolved() { for( Method method : Type1.class.getMethods() ) { Type type = method.getGenericReturnType(); TypeVariable typeVariable = (TypeVariable) type; Type resolvedType = Classes.resolveTypeVariable( typeVariable, method.getDeclaringClass(), Type1.class ); System.out.println( type + "=" + resolvedType ); switch( method.getName() ) { case "type": assertThat( resolvedType, equalTo( String.class ) ); break; case "type1": assertThat( resolvedType, equalTo( String.class ) ); break; case "type2": assertThat( resolvedType, equalTo( Long.class ) ); break; } } } |
### Question:
Collectors { public static <T> Collector<T, ?, T> single() throws IllegalArgumentException { Supplier<T> thrower = () -> { throw new IllegalArgumentException( "No or more than one element in stream" ); }; return java.util.stream.Collectors.collectingAndThen( java.util.stream.Collectors.reducing( ( a, b ) -> null ), optional -> optional.orElseGet( thrower ) ); } private Collectors(); static Collector<T, ?, T> single(); static Collector<T, ?, Optional<T>> singleOrEmpty(); static Collector<T, ?, Map<K, U>> toMap(); static Collector<T, ?, M> toMap( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); static Collector<T, ?, Map<K, U>> toMapWithNullValues(); static Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); }### Answer:
@Test public void single() { assertThat( Stream.of( 1L ).collect( Collectors.single() ), is( 1L ) ); try { Stream.of().collect( Collectors.single() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} try { Stream.of( 1, 1 ).collect( Collectors.single() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} try { Stream.of( 1, 1, 1 ).collect( Collectors.single() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} } |
### Question:
Collectors { public static <T> Collector<T, ?, Optional<T>> singleOrEmpty() { return java.util.stream.Collectors.reducing( ( left, right ) -> { if( left != null && right != null ) { throw new IllegalArgumentException( "More than one element in stream" ); } if( left != null ) { return left; } return right; } ); } private Collectors(); static Collector<T, ?, T> single(); static Collector<T, ?, Optional<T>> singleOrEmpty(); static Collector<T, ?, Map<K, U>> toMap(); static Collector<T, ?, M> toMap( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); static Collector<T, ?, Map<K, U>> toMapWithNullValues(); static Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); }### Answer:
@Test public void singleOrEmpty() { assertThat( Stream.of().collect( Collectors.singleOrEmpty() ), equalTo( Optional.empty() ) ); assertThat( Stream.of( 1 ).collect( Collectors.singleOrEmpty() ), equalTo( Optional.of( 1 ) ) ); try { Stream.of( 1, 1 ).collect( Collectors.singleOrEmpty() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} try { Stream.of( 1, 1, 1 ).collect( Collectors.singleOrEmpty() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} }
@Test public void singleOrEmpty() { assertEquals( Optional.empty(), Stream.of().collect( Collectors.singleOrEmpty() ) ); assertEquals( Optional.of( 1 ), Stream.of( 1 ).collect( Collectors.singleOrEmpty() ) ); try { Stream.of( 1, 1 ).collect( Collectors.singleOrEmpty() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} try { Stream.of( 1, 1, 1 ).collect( Collectors.singleOrEmpty() ); fail( "Should have failed" ); } catch( IllegalArgumentException ex ) {} } |
### Question:
Collectors { public static <T extends Map.Entry<K, U>, K, U> Collector<T, ?, Map<K, U>> toMap() { return toMap( Map.Entry::getKey, Map.Entry::getValue, HashMap::new ); } private Collectors(); static Collector<T, ?, T> single(); static Collector<T, ?, Optional<T>> singleOrEmpty(); static Collector<T, ?, Map<K, U>> toMap(); static Collector<T, ?, M> toMap( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); static Collector<T, ?, Map<K, U>> toMapWithNullValues(); static Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); }### Answer:
@Test public void toMap() { Map<String, String> input = new LinkedHashMap<>(); input.put( "foo", "bar" ); input.put( "bazar", "cathedral" ); Map<String, String> output = input.entrySet().stream().collect( Collectors.toMap() ); assertThat( output.get( "foo" ), equalTo( "bar" ) ); assertThat( output.get( "bazar" ), equalTo( "cathedral" ) ); }
@Test public void toMapRejectNullValues() { Map<String, String> input = new LinkedHashMap<>(); input.put( "foo", "bar" ); input.put( "bazar", null ); try { input.entrySet().stream().collect( Collectors.toMap() ); fail( "Should have failed, that's the default Map::merge behaviour" ); } catch( NullPointerException expected ) {} } |
### Question:
Collectors { public static <T extends Map.Entry<K, U>, K, U> Collector<T, ?, Map<K, U>> toMapWithNullValues() { return toMapWithNullValues( Map.Entry::getKey, Map.Entry::getValue, HashMap::new ); } private Collectors(); static Collector<T, ?, T> single(); static Collector<T, ?, Optional<T>> singleOrEmpty(); static Collector<T, ?, Map<K, U>> toMap(); static Collector<T, ?, M> toMap( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMap( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); static Collector<T, ?, Map<K, U>> toMapWithNullValues(); static Collector<T, ?, M> toMapWithNullValues( Supplier<M> mapSupplier ); static Collector<T, ?, M> toMapWithNullValues( Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
Supplier<M> mapSupplier ); }### Answer:
@Test public void toMapWithNullValues() { Map<String, String> input = new LinkedHashMap<>(); input.put( "foo", "bar" ); input.put( "bazar", null ); Map<String, String> output = input.entrySet().stream().collect( Collectors.toMapWithNullValues() ); assertThat( output.get( "foo" ), equalTo( "bar" ) ); assertThat( output.get( "bazar" ), nullValue() ); } |
### Question:
UnitOfWorkTemplate { @SuppressWarnings( "unchecked" ) public RESULT withModule( Module module ) throws ThrowableType, UnitOfWorkCompletionException { int loop = 0; ThrowableType ex = null; do { UnitOfWork uow = module.unitOfWorkFactory().newUnitOfWork( usecase ); try { RESULT result = withUnitOfWork( uow ); if( complete ) { try { uow.complete(); return result; } catch( ConcurrentEntityModificationException e ) { ex = (ThrowableType) e; } } } catch( Throwable e ) { ex = (ThrowableType) e; } finally { uow.discard(); } } while( loop++ < retries ); throw ex; } protected UnitOfWorkTemplate(); protected UnitOfWorkTemplate( int retries, boolean complete ); protected UnitOfWorkTemplate( Usecase usecase, int retries, boolean complete ); @SuppressWarnings( "unchecked" ) RESULT withModule( Module module ); }### Answer:
@Test public void testTemplate() throws UnitOfWorkCompletionException { new UnitOfWorkTemplate<Void, RuntimeException>() { @Override protected Void withUnitOfWork( UnitOfWork uow ) throws RuntimeException { new EntityBuilderTemplate<TestEntity>( TestEntity.class ) { @Override protected void build( TestEntity prototype ) { prototype.name().set( "Rickard" ); } }.newInstance( module.instance() ); return null; } }.withModule( module.instance() ); } |
### Question:
HasTypesCollectors { public static <T extends HasTypes> Collector<T, ?, List<T>> matchingTypes( T hasTypes ) { return hasTypesToListCollector( hasTypes, new HasAssignableFromType<>( hasTypes ) ); } private HasTypesCollectors(); static Collector<T, ?, Optional<T>> matchingType( T hasTypes ); static Collector<T, ?, Optional<T>> closestType( T hasTypes ); static Collector<T, ?, List<T>> matchingTypes( T hasTypes ); static Collector<T, ?, List<T>> closestTypes( T hasTypes ); static Collector<T, ?, Optional<T>> matchingType( Type type ); static Collector<T, ?, Optional<T>> closestType( Type type ); static Collector<T, ?, List<T>> matchingTypes( Type type ); static Collector<T, ?, List<T>> closestTypes( Type type ); }### Answer:
@Test public void selectMatchingTypes() { List<ValueType> valueTypes = Arrays.asList( ValueType.of( String.class ), ValueType.of( Integer.class ), ValueType.of( Number.class ) ); List<ValueType> number = valueTypes.stream().collect( HasTypesCollectors.matchingTypes( Number.class ) ); assertThat( number.size(), is( 2 ) ); assertThat( number.get( 0 ), equalTo( ValueType.of( Number.class ) ) ); assertThat( number.get( 1 ), equalTo( ValueType.of( Integer.class ) ) ); List<ValueType> integer = valueTypes.stream().collect( HasTypesCollectors.matchingTypes( Integer.class ) ); assertThat( integer.size(), is( 1 ) ); assertThat( integer.get( 0 ), equalTo( ValueType.of( Integer.class ) ) ); }
@Test public void selectMatchingValueTypes() { List<ValueType> valueTypes = Arrays.asList( ValueType.of( String.class ), ValueType.of( Number.class, Integer.class ), ValueType.of( Integer.class ), ValueType.of( Number.class ) ); List<ValueType> number = valueTypes.stream() .collect( HasTypesCollectors.matchingTypes( ValueType.of( Number.class ) ) ); System.out.println( number ); assertThat( number.size(), is( 2 ) ); assertThat( number.get( 0 ), equalTo( ValueType.of( Number.class ) ) ); assertThat( number.get( 1 ), equalTo( ValueType.of( Number.class, Integer.class ) ) ); List<ValueType> integer = valueTypes.stream() .collect( HasTypesCollectors.matchingTypes( ValueType.of( Integer.class ) ) ); assertThat( integer.size(), is( 2 ) ); assertThat( integer.get( 0 ), equalTo( ValueType.of( Integer.class ) ) ); assertThat( integer.get( 1 ), equalTo( ValueType.of( Number.class, Integer.class ) ) ); List<ValueType> both = valueTypes.stream() .collect( HasTypesCollectors.matchingTypes( ValueType.of( Number.class, Integer.class ) ) ); assertThat( both.size(), is( 1 ) ); assertThat( both.get( 0 ), equalTo( ValueType.of( Number.class, Integer.class ) ) ); } |
### Question:
HasTypesCollectors { public static <T extends HasTypes> Collector<T, ?, List<T>> closestTypes( T hasTypes ) { return hasTypesToListCollector( hasTypes, new HasAssignableToType<>( hasTypes ) ); } private HasTypesCollectors(); static Collector<T, ?, Optional<T>> matchingType( T hasTypes ); static Collector<T, ?, Optional<T>> closestType( T hasTypes ); static Collector<T, ?, List<T>> matchingTypes( T hasTypes ); static Collector<T, ?, List<T>> closestTypes( T hasTypes ); static Collector<T, ?, Optional<T>> matchingType( Type type ); static Collector<T, ?, Optional<T>> closestType( Type type ); static Collector<T, ?, List<T>> matchingTypes( Type type ); static Collector<T, ?, List<T>> closestTypes( Type type ); }### Answer:
@Test public void selectClosestValueTypes() { List<ValueType> list = new ArrayList<ValueType>() {{ add( ValueType.of( String.class ) ); add( ValueType.of( Identity.class ) ); }}; List<ValueType> result = list.stream() .collect( HasTypesCollectors.closestTypes( StringIdentity.class ) ); assertThat( result.size(), is( 1 ) ); assertThat( result.get( 0 ), equalTo( ValueType.of( Identity.class ) ) ); } |
### Question:
QualifiedName implements Comparable<QualifiedName> { public String type() { return typeName.normalized(); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromFQN( String fullQualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); @Override int compareTo( QualifiedName other ); boolean isOriginatingFrom( Class<?> mixinType ); }### Answer:
@Test public void testQualifiedNameWithDollar() { assertThat( "Name containing dollar is modified", new QualifiedName( TypeName.nameOf( "Test$Test" ), "satisfiedBy" ).type(), equalTo( "Test-Test" ) ); } |
### Question:
QualifiedName implements Comparable<QualifiedName> { public static QualifiedName fromFQN( String fullQualifiedName ) { Objects.requireNonNull( fullQualifiedName, "qualifiedName" ); int idx = fullQualifiedName.lastIndexOf( ":" ); if( idx == -1 ) { throw new IllegalArgumentException( "Name '" + fullQualifiedName + "' is not a qualified name" ); } final String type = fullQualifiedName.substring( 0, idx ); final String name = fullQualifiedName.substring( idx + 1 ); return new QualifiedName( TypeName.nameOf( type ), name ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromFQN( String fullQualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); @Override int compareTo( QualifiedName other ); boolean isOriginatingFrom( Class<?> mixinType ); }### Answer:
@Test public void nonNullArguments4() { assertThrows( NullPointerException.class, () -> QualifiedName.fromFQN( null ) ); } |
### Question:
QualifiedName implements Comparable<QualifiedName> { public static QualifiedName fromAccessor( AccessibleObject method ) { Objects.requireNonNull( method, "method" ); return fromClass( ( (Member) method ).getDeclaringClass(), ( (Member) method ).getName() ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromFQN( String fullQualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); @Override int compareTo( QualifiedName other ); boolean isOriginatingFrom( Class<?> mixinType ); }### Answer:
@Test public void nonNullArguments5() { assertThrows( NullPointerException.class, () -> QualifiedName.fromAccessor( null ) ); } |
### Question:
QualifiedName implements Comparable<QualifiedName> { public static QualifiedName fromClass( Class type, String name ) { return new QualifiedName( TypeName.nameOf( type ), name ); } QualifiedName( TypeName typeName, String name ); static QualifiedName fromAccessor( AccessibleObject method ); static QualifiedName fromClass( Class type, String name ); static QualifiedName fromName( String type, String name ); static QualifiedName fromFQN( String fullQualifiedName ); String type(); String name(); String toURI(); String toNamespace(); @Override String toString(); @Override boolean equals( Object o ); @Override int hashCode(); @Override int compareTo( QualifiedName other ); boolean isOriginatingFrom( Class<?> mixinType ); }### Answer:
@Test public void nonNullArguments6() { assertThrows( NullPointerException.class, () -> QualifiedName.fromClass( null, "satisfiedBy" ) ); }
@Test public void nonNullArguments7() { assertThrows( NullPointerException.class, () -> QualifiedName.fromClass( null, null ) ); } |
### Question:
ScriptMixin implements InvocationHandler, ScriptReloadable, ScriptRedirect, ScriptAttributes, ScriptAttributes.All { @Override public Object invoke( Object proxy, Method method, Object[] objects ) throws Throwable { Object result = ( (Invocable) engine ).invokeFunction( method.getName(), objects ); return castInvocationResult( method.getReturnType(), result ); } ScriptMixin( @Structure PolygeneSPI spi,
@This Object thisComposite,
@State StateHolder state,
@Structure Layer layer,
@Structure Module module,
@Structure Application application ); @Override Object invoke( Object proxy, Method method, Object[] objects ); @Override void reloadScript(); @Override void setStdOut( Writer writer ); @Override void setStdErr( Writer writer ); @Override void setStdIn( Reader reader ); @Override Object getAttribute( String name ); @Override Object getEngineAttribute( String name ); @Override Object getGlobalAttribute( String name ); @Override void setEngineAttribute( String name, Object value ); @Override void setGlobalAttribute( String name, Object value ); }### Answer:
@Test public void testInvoke() throws Throwable { DomainType domain1 = transientBuilderFactory.newTransient( DomainType.class ); assertThat(domain1.do1("her message"), equalTo("[her message]") ); } |
### Question:
EntityTypeSerializer { public EntityTypeSerializer() { dataTypes.put( String.class.getName(), XMLSchema.STRING ); dataTypes.put( Integer.class.getName(), XMLSchema.INT ); dataTypes.put( Boolean.class.getName(), XMLSchema.BOOLEAN ); dataTypes.put( Byte.class.getName(), XMLSchema.BYTE ); dataTypes.put( BigDecimal.class.getName(), XMLSchema.DECIMAL ); dataTypes.put( Double.class.getName(), XMLSchema.DOUBLE ); dataTypes.put( Long.class.getName(), XMLSchema.LONG ); dataTypes.put( Short.class.getName(), XMLSchema.SHORT ); dataTypes.put( Instant.class.getName(), XMLSchema.LONG ); dataTypes.put( OffsetDateTime.class.getName(), XMLSchema.DATETIME ); dataTypes.put( ZonedDateTime.class.getName(), XMLSchema.DATETIME ); dataTypes.put( LocalDateTime.class.getName(), XMLSchema.DATETIME ); dataTypes.put( LocalDate.class.getName(), XMLSchema.DATE ); dataTypes.put( LocalTime.class.getName(), XMLSchema.TIME ); dataTypes.put( Duration.class.getName(), XMLSchema.DURATION ); dataTypes.put( Period.class.getName(), XMLSchema.DURATION ); } EntityTypeSerializer(); Iterable<Statement> serialize( final EntityDescriptor entityDescriptor ); }### Answer:
@Test public void testEntityTypeSerializer() throws RDFHandlerException { EntityDescriptor entityDescriptor = module.entityDescriptor(TestEntity.class.getName()); Iterable<Statement> graph = serializer.serialize( entityDescriptor ); String[] prefixes = new String[]{ "rdf", "dc", " vc", "polygene" }; String[] namespaces = new String[]{ Rdfs.RDF, DcRdf.NAMESPACE, "http: new RdfXmlSerializer().serialize( graph, new PrintWriter( System.out ), prefixes, namespaces ); } |
### Question:
SendMail { public void sendSimpleMail(String subject, String to, String context) { SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); simpleMailMessage.setFrom(from); simpleMailMessage.setTo(to); simpleMailMessage.setSubject(subject); simpleMailMessage.setText(context); try { javaMailSender.send(simpleMailMessage); log.info("sucessss:{}", from); } catch (Exception e) { log.info("error:{}", from); } } void sendSimpleMail(String subject, String to, String context); void sendFileMail(String subject, String to, String context, String filepath); void sendHtmlMail(String subject, String to, String context); void sendtemplateHtmlMail(String subject, String to, String name); void sendstaticMail(String subject, String to, String context, String filepath, String fileid); }### Answer:
@Test public void hello() throws Exception { sendMail.sendSimpleMail("aaaa","[email protected]","sdas"); } |
### Question:
SendMail { public void sendtemplateHtmlMail(String subject, String to, String name) { MimeMessage mimeMessage = javaMailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); helper.setSubject(subject); helper.setTo(to); helper.setFrom(from); String filepath = "C:\\Users\\Administrator\\Desktop\\ocly.png"; FileSystemResource resource = new FileSystemResource(new File(filepath)); String filename = filepath.substring(filepath.lastIndexOf(File.separator)); helper.addAttachment(filename, resource); Context context = new Context(); context.setVariable("name", name); String templateHtml = templateEngine.process("emailTemplate", context); log.info("来看看模板长啥样 {}",templateHtml); helper.setText(templateHtml, true); helper.addInline("ocly", resource); javaMailSender.send(mimeMessage); log.info("模板邮件发送成功"); } catch (MessagingException e) { log.error("模板邮件发送失败"); } } void sendSimpleMail(String subject, String to, String context); void sendFileMail(String subject, String to, String context, String filepath); void sendHtmlMail(String subject, String to, String context); void sendtemplateHtmlMail(String subject, String to, String name); void sendstaticMail(String subject, String to, String context, String filepath, String fileid); }### Answer:
@Test public void hellomaiTemplate() throws Exception { sendMail.sendtemplateHtmlMail("你好,模板邮件加附件加图片","[email protected]","Bocly"); } |
### Question:
ObservationPoint implements AsyncGeolocate.MLSLocationGetterCallback { public void setCounts(MLSJSONObject ichnaeaQueryObj) { mCellCount = ichnaeaQueryObj.getCellCount(); mWifiCount = ichnaeaQueryObj.getWifiCount(); } ObservationPoint(Location pointGPS); ObservationPoint(String provider, Coordinate pointGPS, int wifis, int cells/*, long timestamp*/); void setMLSQuery(StumblerBundle stumbleBundle); void setCounts(MLSJSONObject ichnaeaQueryObj); void fetchMLS(boolean isWifiConnected, boolean isWifiAvailable); boolean needsToFetchMLS(); void setMLSResponseLocation(Location location); Coordinate getGPSCoordinate(); Coordinate getMLSCoordinate(); void setMLSCoordinate(Coordinate c); void errorMLSResponse(boolean stopRequesting); final Location pointGPS; public Coordinate pointMLS; public int mWifiCount; public int mCellCount; public int mTrackSegment; }### Answer:
@Test public void testSetCounts() { Location mockLocation = new Location(LocationManager.GPS_PROVIDER); { StumblerBundle bundle = new StumblerBundle(mockLocation); testObservationCounts(bundle, 0, 0); for (String bssid : new String[]{"01:23:45:67:89:ab", "23:45:67:89:ab:cd"}) { ScanResult scanResult = createScanResult(bssid, "", 0, 0, 0); bundle.addWifiData(bssid, scanResult); } testObservationCounts(bundle, 0, 2); CellInfo cellInfo = createLteCellInfo(208, 1, 12345, CellInfo.UNKNOWN_CID, 2, 31, 1); bundle.addCellData(cellInfo.getCellIdentity(), cellInfo); testObservationCounts(bundle, 1, 2); } { StumblerBundle bundle = new StumblerBundle(mockLocation); CellInfo cellInfo = createLteCellInfo(208, 1, 12345, CellInfo.UNKNOWN_CID, 2, 31, 1); bundle.addCellData(cellInfo.getCellIdentity(), cellInfo); testObservationCounts(bundle, 1, 0); } } |
### Question:
MapFragment extends android.support.v4.app.Fragment implements MetricsView.IMapLayerToggleListener { public void mapNetworkConnectionChanged() { FragmentActivity activity = getActivity(); if (activity == null) { return; } if (activity.getFilesDir() == null) { showMapNotAvailableMessage(NoMapAvailableMessage.eNoMapDueToNoAccessibleStorage); return; } getUrlAndInit(); final ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo info = cm.getActiveNetworkInfo(); final boolean hasNetwork = (info != null) && info.isConnected(); final boolean hasWifi = (info != null) && (info.getType() == ConnectivityManager.TYPE_WIFI); NoMapAvailableMessage message = hasNetwork ? NoMapAvailableMessage.eHideNoMapMessage : NoMapAvailableMessage.eNoMapDueToNoInternet; showMapNotAvailableMessage(message); setHighBandwidthMap(hasNetwork, hasWifi); } @Override View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState); MainApp getApplication(); void mapNetworkConnectionChanged(); void setZoomButtonsVisible(boolean visible); @SuppressLint("NewApi") void dimToolbar(); void toggleScanning(MenuItem menuItem); void setUserPositionAt(Location location); void updateGPSInfo(int satellites, int fixes); @Override void onResume(); @Override void onSaveInstanceState(Bundle bundle); @Override void onPause(); @Override void onDestroy(); void formatTextView(int textViewId, int stringId, Object... args); void formatTextView(int textViewId, String str, Object... args); void newMLSPoint(ObservationPoint point); void newObservationPoint(ObservationPoint point); @Override void setShowMLS(boolean isOn); void showMapNotAvailableMessage(NoMapAvailableMessage noMapAvailableMessage); void showPausedDueToNoMotionMessage(boolean show); void stop(); static final int LOWEST_UNLIMITED_ZOOM; }### Answer:
@Test @Config(shadows = {CustomShadowConnectivityManager.class}) public void testMapNetworkConnectionChanged() { MapFragment mapFragment = spy(MapFragment.class); doNothing().when(mapFragment).doOnCreateView(any(Bundle.class)); doNothing().when(mapFragment).getUrlAndInit(); doNothing().when(mapFragment).setHighBandwidthMap(Mockito.anyBoolean(), Mockito.anyBoolean()); doNothing().when(mapFragment).doOnResume(); startFragment(mapFragment); mapFragment.mapNetworkConnectionChanged(); verify(mapFragment).showMapNotAvailableMessage(MapFragment.NoMapAvailableMessage.eNoMapDueToNoInternet); verify(mapFragment).setHighBandwidthMap(false, false); } |
### Question:
SerializableTile { public byte[] getTileData() { return (tData == null)? new byte[0] : tData; } SerializableTile(File sTileFile); SerializableTile(byte[] tileBytes, String etag); static String bytesToHex(byte[] bytes); byte[] getTileData(); void setTileData(byte[] tileData); void clearHeaders(); Map<String, String> getHeaders(); void setHeaders(Map<String, String> h); boolean saveFile(File aFile); boolean saveFile(); boolean fromFile(File file); long getCacheControl(); String getHeader(String k); void setHeader(String k, String v); String getEtag(); static final long CACHE_TILE_MS; }### Answer:
@Test public void testLoadTileMissingFile() throws IOException { File temp = File.createTempFile("temp", ".txt"); String path = temp.getAbsolutePath(); temp.delete(); SerializableTile newTile = new SerializableTile(new File(path)); assertEquals(0, newTile.getTileData().length); }
@Test public void testLoadTileValidHeaderNoData() throws IOException { File temp = File.createTempFile("temp", ".txt"); FileOutputStream fos = new FileOutputStream(temp); byte[] tileData = {(byte) 0xde, (byte) 0xca, (byte) 0xfb, (byte) 0xad}; fos.write(tileData); fos.flush(); fos.close(); assertTrue(temp.exists()); SerializableTile newTile = new SerializableTile(temp); assertEquals(0, newTile.getTileData().length); assertFalse(temp.exists()); }
@Test public void testLoadTileInvalidPayload() throws IOException { File temp = File.createTempFile("temp", ".txt"); FileOutputStream fos = new FileOutputStream(temp); byte[] tileData = {(byte) 0xde, (byte) 0xca, (byte) 0xfb, (byte) 0xad, (byte) 0xaf, (byte) 0xad, (byte) 0xaf, (byte) 0xad, (byte) 0xaf, (byte) 0xad, (byte) 0xaf, (byte) 0xad, (byte) 0xaf, (byte) 0xad }; fos.write(tileData); fos.flush(); fos.close(); assertTrue(temp.exists()); SerializableTile newTile = new SerializableTile(temp); assertEquals(0, newTile.getTileData().length); assertFalse(temp.exists()); } |
### Question:
DateConverterUtils { public static Date convert2Date(LocalDate localDate) { if (localDate == null) { return null; } return convert2Date(localDate.atStartOfDay()); } private DateConverterUtils(); static Date convert2Date(LocalDate localDate); static Date convert2Date(LocalDateTime localDateTime); static LocalDateTime convert2LocalDateTime(Date date); static LocalDate convert2LocalDate(Date date); static long convert2Timestamp(LocalDateTime localDateTime); }### Answer:
@Test public void shouldBeNull_whenInputLocalDateIsNull_ofConvert2Date() { LocalDate input = null; Date output = DateConverterUtils.convert2Date(input); Date expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenInputLocalDateIs20170101T010101_ofConvert2Date() { LocalDate input = createLocalDate("2017-01-01T01:01:01"); Date output = DateConverterUtils.convert2Date(input); Date expected = createDate("2017-01-01T00:00:00"); assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenInputLocalDateTimeIsNull_ofConvert2Date() { LocalDateTime input = null; Date output = DateConverterUtils.convert2Date(input); Date expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenInputLocalDateTimeIs20170101T010101_ofConvert2Date() { LocalDateTime input = createLocalDateTime("2017-01-01T01:01:01"); Date output = DateConverterUtils.convert2Date(input); Date expected = createDate("2017-01-01T01:01:01"); assertThat(output).isEqualTo(expected); } |
### Question:
Base64Utils { public static String encode(byte[] data) { if (data == null) { return null; } return Base64.getEncoder().encodeToString(data); } private Base64Utils(); static String encode(byte[] data); static String encode(String data); static String decode(byte[] data); static String decode(String data); }### Answer:
@Test public void shouldBeOk_whenEncodeHelloString() { String input = "hello"; String output = Base64Utils.encode(input); String expected = "aGVsbG8="; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenEncodeHelloByte() { byte[] input = "hello".getBytes(); String output = Base64Utils.encode(input); String expected = "aGVsbG8="; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenEncodeNullString() { String input = null; String output = Base64Utils.encode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenEncodeNullByte() { byte[] input = null; String output = Base64Utils.encode(input); String expected = null; assertThat(output).isEqualTo(expected); } |
### Question:
Base64Utils { public static String decode(byte[] data) { if (data == null) { return null; } try { return new String(Base64.getDecoder().decode(data)); } catch (IllegalArgumentException ex) { return null; } } private Base64Utils(); static String encode(byte[] data); static String encode(String data); static String decode(byte[] data); static String decode(String data); }### Answer:
@Test public void shouldBeNull_whenDecodeNullString() { String input = null; String output = Base64Utils.decode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenDecodeNullByte() { byte[] input = null; String output = Base64Utils.decode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenDecodeInvalidString() { String input = "aGVsbG8=xxxx"; String output = Base64Utils.decode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNull_whenDecodeInvalidByte() { byte[] input = "aGVsbG8=xxxx".getBytes(); String output = Base64Utils.decode(input); String expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenDecodeHelloString() { String input = "aGVsbG8="; String output = Base64Utils.decode(input); String expected = "hello"; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenDecodeHelloByte() { byte[] input = "aGVsbG8=".getBytes(); String output = Base64Utils.decode(input); String expected = "hello"; assertThat(output).isEqualTo(expected); } |
### Question:
CookieSpecBuilder { public String build() { List<String> builder = new ArrayList<>(); builder.add(String.format("%s=%s", getKey(), getValue())); if (hasText(getPath())) { builder.add(String.format("Path=%s", getPath())); } if (Objects.equals(Boolean.TRUE, getHttpOnly())) { builder.add("HttpOnly"); } if (hasText(getSameSite())) { builder.add(String.format("SameSite=%s", getSameSite())); } if (Objects.equals(Boolean.TRUE, getSecure())) { builder.add("Secure"); } if (getMaxAge() > 0) { builder.add(String.format("Max-Age=%s", getMaxAge())); } if (getExpires() != null) { builder.add(String.format("Expires=%s", makeExpires())); } return builder.stream().collect(Collectors.joining("; ")); } CookieSpecBuilder(String key, String value); CookieSpecBuilder setPath(String path); CookieSpecBuilder setHttpOnly(Boolean httpOnly); CookieSpecBuilder setSameSite(String s); CookieSpecBuilder sameSiteStrict(); CookieSpecBuilder setSecure(Boolean s); CookieSpecBuilder setExpires(LocalDateTime expires); CookieSpecBuilder setMaxAge(int maxAge); String build(); String getKey(); String getValue(); String getPath(); Boolean getHttpOnly(); String getSameSite(); Boolean getSecure(); LocalDateTime getExpires(); int getMaxAge(); }### Answer:
@Test public void shouldBeOk_whenHaveOnlyKeyValue() { String output = new CookieSpecBuilder("X-CSRF-Token", "xyz").build(); String expected = "X-CSRF-Token=xyz; Path=/; HttpOnly"; assertThat(output).isEqualTo(expected); } |
### Question:
QuerystringBuilder { public String build() { return getParams().entrySet() .stream() .map(param -> param.getKey() + "=" + encode(param.getValue())) .collect(Collectors.joining("&")); } QuerystringBuilder addParameter(String name, String value); String build(); }### Answer:
@Test public void shouldBeEmptyString_whenEmptyParameter() { QuerystringBuilder input = new QuerystringBuilder(); String output = input.build(); String expected = ""; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUUIDGenerator implements UUIDGenerator { @Override public String generate() { return UUID.randomUUID().toString(); } @Override String generate(); }### Answer:
@Test public void test() { String output = generator.generate(); int expected = 36; assertThat(output.length()).isEqualTo(expected); } |
### Question:
DefaultIdGenerator implements IdGenerator { @Override public String generate() { return ObjectId.get().toString(); } @Override String generate(); }### Answer:
@Test public void test() { String output = generator.generate(); int expected = 24; assertThat(output.length()).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities().stream() .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeSingleElement() { Collection<? extends GrantedAuthority> output = userDetails.getAuthorities(); int expected = 1; assertThat(output.size()).isEqualTo(expected); assertThat(output.iterator().next().getAuthority()).isEqualTo("admin"); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean isAccountNonExpired() { return true; } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeTrue_whenIsAccountNonExpired() { boolean output = userDetails.isAccountNonExpired(); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean isAccountNonLocked() { return true; } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeTrue_whenIsAccountNonLocked() { boolean output = userDetails.isAccountNonLocked(); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean isCredentialsNonExpired() { return true; } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeTrue_whenIsCredentialsNonExpired() { boolean output = userDetails.isCredentialsNonExpired(); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean isEnabled() { return true; } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeTrue_whenIsEnabled() { boolean output = userDetails.isEnabled(); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public int hashCode() { int hash = 5; return 89 * hash + Objects.hashCode(this.username); } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeMinus1405401465_whenCallHashCode() { int output = userDetails.hashCode(); int expected = -1405401465; assertThat(output).isEqualTo(expected); } |
### Question:
DefaultUserDetails implements UserDetails { @Override public boolean equals(Object obj) { return ObjectEquals.of(this) .equals(obj, (orgin, other) -> Objects.equals(orgin.getUsername(), other.getUsername())); } @Override Collection<? extends GrantedAuthority> getAuthorities(); @Override String getPassword(); @Override String getUsername(); @Override boolean isAccountNonExpired(); @Override boolean isAccountNonLocked(); @Override boolean isCredentialsNonExpired(); @Override boolean isEnabled(); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeFalse_whenNotEqualsUsername() { UserDetails obj = DefaultUserDetails.builder() .username("admin") .build(); boolean output = userDetails.equals(obj); boolean expected = false; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeTrue_whenEqualsUsername() { UserDetails obj = DefaultUserDetails.builder() .username("jittagornp") .build(); boolean output = userDetails.equals(obj); boolean expected = true; assertThat(output).isEqualTo(expected); } |
### Question:
SHA384Hashing extends AbstractHashing { @Override public String hash(byte[] data) { try { if (isEmpty(data)) { return null; } MessageDigest digest = MessageDigest.getInstance("SHA-384"); return new String(Hex.encode(digest.digest(data))); } catch (NoSuchAlgorithmException ex) { LOG.warn(null, ex); return null; } } @Override String hash(byte[] data); }### Answer:
@Test public void hashHelloWorld() { byte[] input = "Hello World".getBytes(); String output = hashing.hash(input); String expected = "99514329186b2f6ae4a1329e7ee6c610a729636335174ac6b740f9028396fcc803d0e93863a7c3d90f86beee782f4f3f"; assertThat(output).isEqualTo(expected); }
@Test public void hashPublicKey() throws IOException { try (InputStream inputStream = getClass().getResourceAsStream("/key/public-key.pub")) { byte[] input = IOUtils.toByteArray(inputStream); String output = hashing.hash(input); String expected = "0eea0c8acf694a8bf86e5c11873bd9aa1b4ab630d27b0ee434c885e4e0d198936ee10770f306f66d8eb618daa584972a"; assertThat(output).isEqualTo(expected); } } |
### Question:
ShortHashing extends AbstractHashing { @Override public String hash(byte[] data) { return subString(hashing.hash(data)); } ShortHashing(Hashing hashing, int length); @Override String hash(byte[] data); }### Answer:
@Test public void sholdBe32Characters() { String input = "Hello World"; String output = shortHashing.hash(input.getBytes()); System.out.println("output => " + output); assertTrue(shortHashing.matches(input.getBytes(), output)); } |
### Question:
CustomSession implements ExpiringSession, Serializable { @Override public int getMaxInactiveIntervalInSeconds() { return this.maxInactiveInterval; } CustomSession(); CustomSession(int maxInactiveInterval); void setMaxInactiveInterval(int interval); @Override void setMaxInactiveIntervalInSeconds(int interval); @Override int getMaxInactiveIntervalInSeconds(); @Override boolean isExpired(); @Override @SuppressWarnings("unchecked") T getAttribute(String attributeName); @Override Set<String> getAttributeNames(); Map<String, Object> getAttributes(); @Override void setAttribute(String attributeName, Object attributeValue); @Override void removeAttribute(String attributeName); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void maxInactiveIntervalShouldBe1800_whenNewInstance() { CustomSession session = new CustomSession(); int maxInactiveInterval = session.getMaxInactiveIntervalInSeconds(); int expected = 1800; assertThat(maxInactiveInterval).isEqualTo(expected); } |
### Question:
CustomSession implements ExpiringSession, Serializable { public Map<String, Object> getAttributes() { return new HashMap<>(this.attributes); } CustomSession(); CustomSession(int maxInactiveInterval); void setMaxInactiveInterval(int interval); @Override void setMaxInactiveIntervalInSeconds(int interval); @Override int getMaxInactiveIntervalInSeconds(); @Override boolean isExpired(); @Override @SuppressWarnings("unchecked") T getAttribute(String attributeName); @Override Set<String> getAttributeNames(); Map<String, Object> getAttributes(); @Override void setAttribute(String attributeName, Object attributeValue); @Override void removeAttribute(String attributeName); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void attributesShouldBeEmpty_whenNewInstance() { CustomSession session = new CustomSession(); Map<String, Object> attributes = session.getAttributes(); Map<String, Object> empty = new HashMap<>(); assertThat(attributes).isEqualTo(empty); } |
### Question:
CustomSession implements ExpiringSession, Serializable { @Override public boolean isExpired() { return isExpired(convert2Timestamp(now())); } CustomSession(); CustomSession(int maxInactiveInterval); void setMaxInactiveInterval(int interval); @Override void setMaxInactiveIntervalInSeconds(int interval); @Override int getMaxInactiveIntervalInSeconds(); @Override boolean isExpired(); @Override @SuppressWarnings("unchecked") T getAttribute(String attributeName); @Override Set<String> getAttributeNames(); Map<String, Object> getAttributes(); @Override void setAttribute(String attributeName, Object attributeValue); @Override void removeAttribute(String attributeName); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void shouldBeNotExpire_whenNewInstance() { CustomSession session = new CustomSession(); boolean output = session.isExpired(); boolean expected = false; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeNotExpire_whenMaxInactiveIntervalIsNegativeValue() { CustomSession session = new CustomSession(-1); boolean output = session.isExpired(); boolean expected = false; assertThat(output).isEqualTo(expected); } |
### Question:
DateConverterUtils { public static LocalDate convert2LocalDate(Date date) { if (date == null) { return null; } return convert2LocalDateTime(date).toLocalDate(); } private DateConverterUtils(); static Date convert2Date(LocalDate localDate); static Date convert2Date(LocalDateTime localDateTime); static LocalDateTime convert2LocalDateTime(Date date); static LocalDate convert2LocalDate(Date date); static long convert2Timestamp(LocalDateTime localDateTime); }### Answer:
@Test public void shouldBeNull_whenInputDateIsNull_ofConvert2LocalDate() { Date input = null; LocalDate output = DateConverterUtils.convert2LocalDate(input); LocalDate expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenInputDateIs20170101T010101_ofConvert2LocalDate() { Date input = createDate("2017-01-01T01:01:01"); LocalDate output = DateConverterUtils.convert2LocalDate(input); LocalDate expected = createLocalDate("2017-01-01T00:00:00"); assertThat(output).isEqualTo(expected); } |
### Question:
DateConverterUtils { public static LocalDateTime convert2LocalDateTime(Date date) { if (date == null) { return null; } return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } private DateConverterUtils(); static Date convert2Date(LocalDate localDate); static Date convert2Date(LocalDateTime localDateTime); static LocalDateTime convert2LocalDateTime(Date date); static LocalDate convert2LocalDate(Date date); static long convert2Timestamp(LocalDateTime localDateTime); }### Answer:
@Test public void shouldBeNull_whenInputDateIsNull_ofConvert2LocalDateTime() { Date input = null; LocalDateTime output = DateConverterUtils.convert2LocalDateTime(input); LocalDateTime expected = null; assertThat(output).isEqualTo(expected); }
@Test public void shouldBeOk_whenInputDateIs20170101T010101_ofConvert2LocalDateTime() { Date input = createDate("2017-01-01T01:01:01"); LocalDateTime output = DateConverterUtils.convert2LocalDateTime(input); LocalDateTime expected = createLocalDateTime("2017-01-01T01:01:01"); assertThat(output).isEqualTo(expected); } |
### Question:
ProductService { public void classicalDelete(Long id) { authService.checkAccess(); System.out.println("Delete Product."); } void insert(Product product); void classicalDelete(Long id); void baseAopDelete(Long id); @AdminOnly void annoAopDelete(Long id); }### Answer:
@Test(expected = Exception.class) public void classicalDelete() throws Exception { CurrentUserHolder.set("frank"); productService.classicalDelete(1L); } |
### Question:
ProductService { public void baseAopDelete(Long id) { System.out.println("Delete Product."); } void insert(Product product); void classicalDelete(Long id); void baseAopDelete(Long id); @AdminOnly void annoAopDelete(Long id); }### Answer:
@Test public void baseAopDelete() throws Exception { CurrentUserHolder.set("frank"); productService.baseAopDelete(1L); } |
### Question:
ProductService { @AdminOnly public void annoAopDelete(Long id) { System.out.println("Delete Product."); } void insert(Product product); void classicalDelete(Long id); void baseAopDelete(Long id); @AdminOnly void annoAopDelete(Long id); }### Answer:
@Test(expected = Exception.class) public void annoAopDelete() throws Exception { CurrentUserHolder.set("frank"); productService.baseAopDelete(1L); } |
### Question:
CaseStudy { public static void demonstrate() { String code = "The code"; Course course = Courses.findByCode(code); Lecturer lecturer = course.getLecturer(); String name = lecturer.getName(); System.out.println(name); } static void demonstrate(); }### Answer:
@Test public void demonstrateTest() { CaseStudy.demonstrate(); String expected = String.format("The lecturer%s", System.lineSeparator()); String obtained = out.toString(); assertEquals(obtained, expected); } |
### Question:
App { public static double mean(List<Double> numbers) { double sum = 0; for (double f : numbers) { sum += f; } return sum / numbers.size(); } static void main(String[] args); static List<Double> compute(); static List<Double> loadFromFile(String filepath); static double mean(List<Double> numbers); static double std(List<Double> numbers, double mean); static List<Double> normalize(List<Double> numbers, double mean, double std); static void writeToFile(List<Double> numbers); }### Answer:
@Test public void meanWithNegatives() { List<Double> numbers = Arrays.asList(-1d,1d); double mean = App.mean(numbers); assertEquals(0, mean, 0); }
@Test public void zeroMean() { List<Double> zeroes = Arrays.asList(0d,0d,0d,0d); double mean = App.mean(zeroes); assertEquals(0, mean, 0); } |
### Question:
App { public static double std(List<Double> numbers, double mean) { double sumSquare = 0; for (double f : numbers) { double diff = f - mean; sumSquare += diff * diff; } return Math.sqrt(sumSquare / numbers.size()); } static void main(String[] args); static List<Double> compute(); static List<Double> loadFromFile(String filepath); static double mean(List<Double> numbers); static double std(List<Double> numbers, double mean); static List<Double> normalize(List<Double> numbers, double mean, double std); static void writeToFile(List<Double> numbers); }### Answer:
@Test public void zeroStd() { List<Double> zeroes = Arrays.asList(0d,0d,0d,0d); double std = App.std(zeroes, 0); assertEquals(0, std, 0); } |
### Question:
App { public static List<Double> compute() throws FileNotFoundException { File file = new File("data"); List<Double> normalized = new ArrayList<>(); Scanner scanner = new Scanner(file); List<Double> numbers = new ArrayList<>(); while (scanner.hasNextDouble()) { double number = scanner.nextDouble(); numbers.add(number); } double sum = 0; for (double f : numbers) { sum += f; } double mean = sum / numbers.size(); double sumSquare = 0; for (double f : numbers) { double diff = f - mean; sumSquare += diff * diff; } double std = Math.sqrt(sumSquare / numbers.size()); for (double f : numbers) { normalized.add((f - mean) / std); } System.out.println(normalized); try { FileWriter fw = new FileWriter("output"); for (double n : normalized) { fw.write(Double.toString(n)); fw.write("\n"); } fw.close(); } catch (Exception e) { System.out.println("Error writing output file"); } System.out.println("Wrote output file."); scanner.close(); return normalized; } static void main(String[] args); static List<Double> compute(); }### Answer:
@Test public void computeYieldsCorrectResult() throws FileNotFoundException { List<Double> normalized = App.compute(); List<Double> expected = Arrays.asList( -1.5666989036012806, -1.2185435916898848, -0.8703882797784892, -0.5222329678670935, -0.17407765595569785, 0.17407765595569785, 0.5222329678670935, 0.8703882797784892, 1.2185435916898848, 1.5666989036012806 ); assertEquals(expected, normalized); } |
### Question:
RecursiveFibonacci { @Requires("0 <= n") @Ensures("0 <= result") public int apply(int n) { if (0 == n || 1 == n) { return n; } else { return apply(n - 1) + apply(n - 2); } } @Requires("0 <= n") @Ensures("0 <= result") int apply(int n); }### Answer:
@Test(expected = PreconditionError.class) public void fibOnNegativeFails() { RecursiveFibonacci fib = new RecursiveFibonacci(); fib.apply(-1); }
@Test public void fibOf4() { RecursiveFibonacci fib = new RecursiveFibonacci(); assertEquals(3, fib.apply(4)); } |
### Question:
App { public String getGreeting() { return "Hello world."; } String getGreeting(); static void main(String[] args); }### Answer:
@Test void appHasAGreeting() { App classUnderTest = new App(); assertNotNull(classUnderTest.getGreeting(), "app should have a greeting"); }
@Test public void testAppHasAGreeting() { App classUnderTest = new App(); assertNotNull("app should have a greeting", classUnderTest.getGreeting()); } |
### Question:
Loan { public static Loan createTermLoan(double commitment, int riskTaking, Date maturity){ return new Loan(null, commitment, 0.00, riskTaking, maturity, null); } private Loan(CapitalStrategy capitalStrategy, double commitment, double outstanding, int riskTaking, Date maturity, Date expiry); static Loan createTermLoan(double commitment, int riskTaking, Date maturity); static Loan createRevolverLoan(double commitment, double outstanding, int customerRating, Date maturity, Date expiry); static Loan createRevolverLoan(double commitment, int customerRating, Date maturity, Date expiry); static Loan createRCTLLoan(CapitalStrategy capitalStrategy, double commitment, int riskTaking, Date maturity, Date expiry); }### Answer:
@Test public void testTermLoanNoPayments() { Loan termLoan = Loan.createTermLoan(2.0, 1, Date.from(Instant.now())); assertNotNull(termLoan); System.out.println("Test term loan"); } |
### Question:
Loan { public static Loan createRevolverLoan(double commitment, double outstanding, int customerRating, Date maturity, Date expiry){ return new Loan(null, commitment, outstanding, customerRating, maturity, expiry); } private Loan(CapitalStrategy capitalStrategy, double commitment, double outstanding, int riskTaking, Date maturity, Date expiry); static Loan createTermLoan(double commitment, int riskTaking, Date maturity); static Loan createRevolverLoan(double commitment, double outstanding, int customerRating, Date maturity, Date expiry); static Loan createRevolverLoan(double commitment, int customerRating, Date maturity, Date expiry); static Loan createRCTLLoan(CapitalStrategy capitalStrategy, double commitment, int riskTaking, Date maturity, Date expiry); }### Answer:
@Test public void testRevolverLoan() { Loan revolverLoan = Loan.createRevolverLoan(2.0, 1.0, 1, Date.from(Instant.now()), Date.from(Instant.now())); assertNotNull(revolverLoan); System.out.println("Test revolver loan"); } |
### Question:
App { public static List<Double> compute() throws FileNotFoundException { List<Double> numbers = loadFromFile("data"); double mean = mean(numbers); double std = std(numbers, mean); List<Double> normalized = normalize(numbers, mean, std); System.out.println(normalized); writeToFile(normalized); return normalized; } static void main(String[] args); static List<Double> compute(); static List<Double> loadFromFile(String filepath); static double mean(List<Double> numbers); static double std(List<Double> numbers, double mean); static List<Double> normalize(List<Double> numbers, double mean, double std); static void writeToFile(List<Double> numbers); }### Answer:
@Test public void computeYieldsCorrectResult() throws FileNotFoundException { List<Double> normalized = App.compute(); List<Double> expected = Arrays.asList( -1.5666989036012806, -1.2185435916898848, -0.8703882797784892, -0.5222329678670935, -0.17407765595569785, 0.17407765595569785, 0.5222329678670935, 0.8703882797784892, 1.2185435916898848, 1.5666989036012806 ); assertEquals(expected, normalized); } |
### Question:
App { public static List<Double> loadFromFile(String filepath) throws FileNotFoundException { File file = new File(filepath); Scanner scanner = new Scanner(file); List<Double> numbers = new ArrayList<>(); while (scanner.hasNextDouble()) { double number = scanner.nextDouble(); numbers.add(number); } scanner.close(); return numbers; } static void main(String[] args); static List<Double> compute(); static List<Double> loadFromFile(String filepath); static double mean(List<Double> numbers); static double std(List<Double> numbers, double mean); static List<Double> normalize(List<Double> numbers, double mean, double std); static void writeToFile(List<Double> numbers); }### Answer:
@Test public void loadCorrectFile() throws FileNotFoundException { List<Double> expected = Arrays.asList(1d,2d,3d,4d,5d,6d,7d,8d,9d,10d); List<Double> loaded = App.loadFromFile("data"); assertEquals(expected, loaded); }
@Test public void loadWrongFileThrows() throws FileNotFoundException { assertThrows(FileNotFoundException.class, () -> { App.loadFromFile("loremipsum"); }); } |
### Question:
Utils { public static AudioStream getHighestQualityAudio(List<AudioStream> audioStreams) { int highestQualityIndex = 0; for (int i = 1; i < audioStreams.size(); i++) { AudioStream audioStream = audioStreams.get(i); if (audioStream.avgBitrate > audioStreams.get(highestQualityIndex).avgBitrate) highestQualityIndex = i; } return audioStreams.get(highestQualityIndex); } static int getDefaultResolution(String defaultResolution, String preferredFormat, List<VideoStream> videoStreams); static int getDefaultResolution(Context context, List<VideoStream> videoStreams); static int getPopupDefaultResolution(Context context, List<VideoStream> videoStreams); static int getPreferredAudioFormat(Context context, List<AudioStream> audioStreams); static AudioStream getHighestQualityAudio(List<AudioStream> audioStreams); static ArrayList<VideoStream> getSortedStreamVideosList(Context context, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder); static ArrayList<VideoStream> getSortedStreamVideosList(MediaFormat preferredFormat, boolean showHigherResolutions, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder); static void sortStreamList(List<VideoStream> videoStreams, final boolean ascendingOrder); }### Answer:
@Test public void getHighestQualityAudioTest() throws Exception { assertEquals(320, Utils.getHighestQualityAudio(audioStreamsTestList).avgBitrate); } |
### Question:
Utils { public static ArrayList<VideoStream> getSortedStreamVideosList(Context context, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder) { boolean showHigherResolutions = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.show_higher_resolutions_key), false); String preferredFormatString = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.preferred_video_format_key), context.getString(R.string.preferred_video_format_default)); MediaFormat preferredFormat = MediaFormat.WEBM; switch (preferredFormatString) { case "WebM": preferredFormat = MediaFormat.WEBM; break; case "MPEG-4": preferredFormat = MediaFormat.MPEG_4; break; case "3GPP": preferredFormat = MediaFormat.v3GPP; break; default: break; } return getSortedStreamVideosList(preferredFormat, showHigherResolutions, videoStreams, videoOnlyStreams, ascendingOrder); } static int getDefaultResolution(String defaultResolution, String preferredFormat, List<VideoStream> videoStreams); static int getDefaultResolution(Context context, List<VideoStream> videoStreams); static int getPopupDefaultResolution(Context context, List<VideoStream> videoStreams); static int getPreferredAudioFormat(Context context, List<AudioStream> audioStreams); static AudioStream getHighestQualityAudio(List<AudioStream> audioStreams); static ArrayList<VideoStream> getSortedStreamVideosList(Context context, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder); static ArrayList<VideoStream> getSortedStreamVideosList(MediaFormat preferredFormat, boolean showHigherResolutions, List<VideoStream> videoStreams, List<VideoStream> videoOnlyStreams, boolean ascendingOrder); static void sortStreamList(List<VideoStream> videoStreams, final boolean ascendingOrder); }### Answer:
@Test public void getSortedStreamVideosListTest() throws Exception { List<VideoStream> result = Utils.getSortedStreamVideosList(MediaFormat.MPEG_4, true, videoStreamsTestList, videoOnlyStreamsTestList, true); List<String> expected = Arrays.asList("144p", "240p", "360p", "480p", "720p", "720p60", "1080p", "1080p60", "1440p60", "2160p", "2160p60"); assertEquals(result.size(), expected.size()); for (int i = 0; i < result.size(); i++) { assertEquals(result.get(i).resolution, expected.get(i)); } result = Utils.getSortedStreamVideosList(MediaFormat.MPEG_4, true, videoStreamsTestList, videoOnlyStreamsTestList, false); expected = Arrays.asList("2160p60", "2160p", "1440p60", "1080p60", "1080p", "720p60", "720p", "480p", "360p", "240p", "144p"); assertEquals(result.size(), expected.size()); for (int i = 0; i < result.size(); i++) assertEquals(result.get(i).resolution, expected.get(i)); result = Utils.getSortedStreamVideosList(MediaFormat.MPEG_4, false, videoStreamsTestList, videoOnlyStreamsTestList, false); expected = Arrays.asList("1080p60", "1080p", "720p60", "720p", "480p", "360p", "240p", "144p"); assertEquals(result.size(), expected.size()); for (int i = 0; i < result.size(); i++) assertEquals(result.get(i).resolution, expected.get(i)); } |
### Question:
OpenJp2ImageWriter extends ImageWriter { @Override public ImageWriteParam getDefaultWriteParam() { return new OpenJp2ImageWriteParam(); } protected OpenJp2ImageWriter(ImageWriterSpi originatingProvider, OpenJpeg lib); @Override void setOutput(Object output); @Override ImageWriteParam getDefaultWriteParam(); @Override IIOMetadata getDefaultStreamMetadata(ImageWriteParam param); @Override IIOMetadata getDefaultImageMetadata(ImageTypeSpecifier imageType, ImageWriteParam param); @Override IIOMetadata convertStreamMetadata(IIOMetadata inData, ImageWriteParam param); @Override IIOMetadata convertImageMetadata(
IIOMetadata inData, ImageTypeSpecifier imageType, ImageWriteParam param); @Override void write(IIOMetadata streamMetadata, IIOImage image, ImageWriteParam param); }### Answer:
@Test void writeLosslessUntiled() throws Exception { OpenJp2ImageWriteParam param = (OpenJp2ImageWriteParam) writer.getDefaultWriteParam(); compressAndCompare("lenna_defaults.jp2", param); }
@Test void writeLossyUntiledDefaultQuality() throws Exception { OpenJp2ImageWriteParam param = (OpenJp2ImageWriteParam) writer.getDefaultWriteParam(); param.setCompressionType("lossy"); compressAndCompare("lenna_lossy.jp2", param); }
@Test void writeLossyUntiledCustomQuality() throws Exception { OpenJp2ImageWriteParam param = (OpenJp2ImageWriteParam) writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(0.9f); compressAndCompare("lenna_lossy_r10.jp2", param); }
@Test void writeLossyTiledCustomQuality() throws Exception { OpenJp2ImageWriteParam param = (OpenJp2ImageWriteParam) writer.getDefaultWriteParam(); param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); param.setCompressionQuality(0.9f); param.setTilingMode(ImageWriteParam.MODE_EXPLICIT); param.setTiling(128, 128, 0, 0); compressAndCompare("lenna_tiled_lossy_r10.jp2", param); } |
### Question:
TurboJpegImageReader extends ImageReader { @Override public BufferedImage read(int imageIndex, ImageReadParam param) throws IOException { checkIndex(imageIndex); ByteBuffer data = jpegData; try { int rotation = 0; Rectangle region = null; Rectangle extraCrop = null; if (param instanceof TurboJpegImageReadParam) { rotation = ((TurboJpegImageReadParam) param).getRotationDegree(); } if (param != null && param.getSourceRegion() != null) { region = param.getSourceRegion(); if (!isRegionFullImage(imageIndex, region)) { scaleRegion(imageIndex, region); extraCrop = adjustRegion(info.getMCUSize(), region, rotation); } else { region = null; } } if (region != null && (region.x + region.width > getWidth(0) || region.y + region.height > getHeight(0))) { throw new IllegalArgumentException( String.format( "Selected region (%dx%d+%d+%d) exceeds the image boundaries (%dx%d).", region.width, region.height, region.x, region.y, getWidth(imageIndex), getWidth(imageIndex))); } if (region != null || rotation != 0) { data = lib.transform(data.array(), info, region, rotation); } Info transformedInfo = lib.getInfo(data.array()); BufferedImage img = lib.decode( data.array(), transformedInfo, transformedInfo.getAvailableSizes().get(imageIndex)); if (extraCrop != null) { adjustExtraCrop(imageIndex, transformedInfo, extraCrop); img = img.getSubimage(extraCrop.x, extraCrop.y, extraCrop.width, extraCrop.height); } return img; } catch (TurboJpegException e) { throw new IOException(e); } } protected TurboJpegImageReader(ImageReaderSpi originatingProvider, TurboJpeg lib); @Override void setInput(Object input, boolean seekForwardOnly, boolean ignoreMetadata); @Override ImageReadParam getDefaultReadParam(); @Override int getNumImages(boolean allowSearch); @Override int getWidth(int imageIndex); @Override int getHeight(int imageIndex); @Override Iterator<ImageTypeSpecifier> getImageTypes(int imageIndex); @Override BufferedImage read(int imageIndex, ImageReadParam param); @Override IIOMetadata getStreamMetadata(); @Override IIOMetadata getImageMetadata(int imageIndex); }### Answer:
@Test public void testRead() throws IOException { ImageReader reader = getReader("rgb.jpg"); BufferedImage img = reader.read(0, null); assertThat(img).hasDimensions(512, 512); }
@Test public void testReadScaled() throws IOException { BufferedImage img = getReader("rgb.jpg").read(2, null); assertThat(img).hasDimensions(384, 384); } |
### Question:
Table { Table(LSql lSql, String sqlSchemaAndTableName) { this.lSql = lSql; this.sqlSchemaAndTableName = sqlSchemaAndTableName; fetchMeta(); if (logger.isDebugEnabled()) { StringBuilder msg = new StringBuilder("Read schema for table '" + this.sqlSchemaAndTableName + "':\n"); for (Column column : columns.values()) { msg.append(" ").append(column).append("\n"); } logger.debug(msg.toString()); } } Table(LSql lSql, String sqlSchemaAndTableName); Table(LSql lSql,
String sqlSchemaName,
String sqlTableName,
String primaryKeyColumn); LSql getlSql(); String getSqlSchemaAndTableName(); String getSchemaName(); String getTableName(); Optional<String> getPrimaryKeyColumn(); Optional<Class<?>> getPrimaryKeyType(); Map<String, Column> getColumns(); @Nullable synchronized Column column(String columnName); @Deprecated PojoTable<T> withPojo(Class<T> pojoClass); void enableRevisionSupport(); void enableRevisionSupport(String revisionColumnName); Optional<Column> getRevisionColumn(); Optional<Object> insert(Row row); Optional<Object> insert(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void update(Row row); void update(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void updateWhere(Row values, Row where); void updateWhere(Row values, Row where, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); Optional<?> save(Row row); Optional<?> save(Row row, RowSerializer<Row> rowSerializer, RowDeserializer<Row> rowDeserializer); void delete(Object id); void delete(Object id, RowDeserializer<Row> rowDeserializer); void delete(Row row); void delete(Row row, RowDeserializer<Row> rowDeserializer); Optional<LinkedRow> load(Object id); Optional<LinkedRow> load(Object id, RowDeserializer<Row> rowDeserializer); @Deprecated LinkedRow newLinkedRow(); LinkedRow newLinkedRow(Object... keyVals); LinkedRow newLinkedRow(Map<String, Object> data); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer:
@Test(expectedExceptions = IllegalArgumentException.class) public void failOnWrongTableName() { createTable("CREATE TABLE namenamenamenamename (id_pk INTEGER PRIMARY KEY, age INT)"); lSql.table("wrongwrongwrongwrongwrong"); }
@Test public void fetchMetaWithRecursiveFkTable() { createTable("CREATE TABLE table1 (id SERIAL PRIMARY KEY, ref INT REFERENCES table1(id))"); lSql.table("table1"); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.