src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
Const { public static String escapeSQL( String content ) { if ( Utils.isEmpty( content ) ) { return content; } return StringEscapeUtils.escapeSql( content ); } static double round( double f, int places ); static double round( double f, int places, int roundingMode ); static BigDecimal round( BigDecimal f, int places, ...
@Test public void testEscapeSQL() { assertEquals( "SELECT ''Let''s rock!'' FROM dual", Const.escapeSQL( "SELECT 'Let's rock!' FROM dual" ) ); }
Const { public static String removeCRLF( String in ) { if ( ( in != null ) && ( in.length() > 0 ) ) { int inLen = in.length(), posn = 0; char[] tmp = new char[ inLen ]; char ch; for ( int i = 0; i < inLen; i++ ) { ch = in.charAt( i ); if ( ( ch != '\n' && ch != '\r' ) ) { tmp[posn] = ch; posn++; } } return new String( ...
@Test public void testRemoveCRLF() { assertEquals( "foo\tbar", Const.removeCRLF( "foo\r\n\tbar" ) ); assertEquals( "", Const.removeCRLF( "" ) ); assertEquals( "", Const.removeCRLF( null ) ); assertEquals( "", Const.removeCRLF( "\r\n" ) ); assertEquals( "This is a test of the emergency broadcast system", Const.removeCRL...
Const { public static String removeCR( String in ) { return removeChar( in, '\n' ); } static double round( double f, int places ); static double round( double f, int places, int roundingMode ); static BigDecimal round( BigDecimal f, int places, int roundingMode ); static long round( long f, int places, int roundingMod...
@Test public void testRemoveCR() { assertEquals( "foo\r\tbar", Const.removeCR( "foo\r\n\tbar" ) ); assertEquals( "", Const.removeCR( "" ) ); assertEquals( "", Const.removeCR( null ) ); assertEquals( "", Const.removeCR( "\n" ) ); assertEquals( "\r", Const.removeCR( "\n\r\n" ) ); assertEquals( "This \ris \ra test \rof \r...
Const { public static String removeLF( String in ) { return removeChar( in, '\r' ); } static double round( double f, int places ); static double round( double f, int places, int roundingMode ); static BigDecimal round( BigDecimal f, int places, int roundingMode ); static long round( long f, int places, int roundingMod...
@Test public void testRemoveLF() { assertEquals( "foo\n\tbar", Const.removeLF( "foo\r\n\tbar" ) ); assertEquals( "", Const.removeLF( "" ) ); assertEquals( "", Const.removeLF( null ) ); assertEquals( "", Const.removeLF( "\r" ) ); assertEquals( "\n", Const.removeLF( "\r\n\r" ) ); assertEquals( "This \nis a \ntest of \nth...
Const { public static String removeTAB( String in ) { return removeChar( in, '\t' ); } static double round( double f, int places ); static double round( double f, int places, int roundingMode ); static BigDecimal round( BigDecimal f, int places, int roundingMode ); static long round( long f, int places, int roundingMo...
@Test public void testRemoveTAB() { assertEquals( "foo\r\nbar", Const.removeTAB( "foo\r\n\tbar" ) ); assertEquals( "", Const.removeTAB( "" ) ); assertEquals( "", Const.removeTAB( null ) ); assertEquals( "", Const.removeTAB( "\t" ) ); assertEquals( "\r", Const.removeTAB( "\t\r\t" ) ); assertEquals( "Thisisatest", Const....
Const { public static Date addTimeToDate( Date input, String time, String DateFormat ) throws Exception { if ( Utils.isEmpty( time ) ) { return input; } if ( input == null ) { return null; } String dateformatString = NVL( DateFormat, "HH:mm:ss" ); int t = decodeTime( time, dateformatString ); return new Date( input.get...
@Test public void testAddTimeToDate() throws Exception { final Date date = new Date( 1447252914241L ); assertNull( Const.addTimeToDate( null, null, null ) ); assertEquals( date, Const.addTimeToDate( date, null, null ) ); assertEquals( 1447256637241L, Const.addTimeToDate( date, "01:02:03", "HH:mm:ss" ).getTime() ); }
Const { public static int getOccurenceString( String string, String searchFor ) { if ( string == null || string.length() == 0 ) { return 0; } int counter = 0; int len = searchFor.length(); if ( len > 0 ) { int start = string.indexOf( searchFor ); while ( start != -1 ) { counter++; start = string.indexOf( searchFor, sta...
@Test public void testGetOccurenceString() { assertEquals( 0, Const.getOccurenceString( "", "" ) ); assertEquals( 0, Const.getOccurenceString( "foo bar bazfoo", "cat" ) ); assertEquals( 2, Const.getOccurenceString( "foo bar bazfoo", "foo" ) ); }
Const { public static String[] GetAvailableFontNames() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font[] fonts = ge.getAllFonts(); String[] FontName = new String[fonts.length]; for ( int i = 0; i < fonts.length; i++ ) { FontName[i] = fonts[i].getFontName(); } return FontName; } stati...
@Test public void testGetAvailableFontNames() { assertTrue( Const.GetAvailableFontNames().length > 0 ); }
Const { public static String getKettlePropertiesFileHeader() { StringBuilder out = new StringBuilder(); out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line01", BuildVersion .getInstance().getVersion() ) + CR ); out.append( BaseMessages.getString( PKG, "Props.Kettle.Properties.Sample.Line02" ) ...
@Test public void testGetKettlePropertiesFileHeader() { assertFalse( Const.getKettlePropertiesFileHeader().isEmpty() ); }
Const { public static String protectXMLCDATA( String content ) { if ( Utils.isEmpty( content ) ) { return content; } return "<![CDATA[" + content + "]]>"; } static double round( double f, int places ); static double round( double f, int places, int roundingMode ); static BigDecimal round( BigDecimal f, int places, int...
@Test public void testProtectXMLCDATA() { assertEquals( null, Const.protectXMLCDATA( null ) ); assertEquals( "", Const.protectXMLCDATA( "" ) ); assertEquals( "<![CDATA[foo]]>", Const.protectXMLCDATA( "foo" ) ); }
Const { public static int getOcuranceString( String string, String searchFor ) { if ( string == null || string.length() == 0 ) { return 0; } Pattern p = Pattern.compile( searchFor ); Matcher m = p.matcher( string ); int count = 0; while ( m.find() ) { ++count; } return count; } static double round( double f, int place...
@Test public void testGetOcuranceString() { assertEquals( 0, Const.getOcuranceString( "", "" ) ); assertEquals( 0, Const.getOcuranceString( "foo bar bazfoo", "cat" ) ); assertEquals( 2, Const.getOcuranceString( "foo bar bazfoo", "foo" ) ); }
Const { public static String escapeXML( String content ) { if ( Utils.isEmpty( content ) ) { return content; } return StringEscapeUtils.escapeXml( content ); } static double round( double f, int places ); static double round( double f, int places, int roundingMode ); static BigDecimal round( BigDecimal f, int places, ...
@Test public void testEscapeXml() { final String xml = "<xml xmlns:test=\"http: final String escaped = "&lt;xml xmlns:test=&quot;http: assertNull( Const.escapeXml( null ) ); assertEquals( escaped, Const.escapeXml( xml ) ); }
Const { public static String Lpad( String valueToPad, String filler, int size ) { if ( ( size == 0 ) || ( valueToPad == null ) || ( filler == null ) ) { return valueToPad; } int vSize = valueToPad.length(); int fSize = filler.length(); if ( ( vSize >= size ) || ( fSize == 0 ) ) { return valueToPad; } int tgt = ( size -...
@Test public void testLpad() { final String s = "pad me"; assertEquals( s, Const.Lpad( s, "-", 0 ) ); assertEquals( s, Const.Lpad( s, "-", 3 ) ); assertEquals( "--" + s, Const.Lpad( s, "-", 8 ) ); assertEquals( s, Const.Lpad( s, null, 15 ) ); assertEquals( s, Const.Lpad( s, "", 15 ) ); assertEquals( s, Const.Lpad( s, "...
Const { public static String Rpad( String valueToPad, String filler, int size ) { if ( ( size == 0 ) || ( valueToPad == null ) || ( filler == null ) ) { return valueToPad; } int vSize = valueToPad.length(); int fSize = filler.length(); if ( ( vSize >= size ) || ( fSize == 0 ) ) { return valueToPad; } int tgt = ( size -...
@Test public void testRpad() { final String s = "pad me"; assertEquals( s, Const.Rpad( s, "-", 0 ) ); assertEquals( s, Const.Rpad( s, "-", 3 ) ); assertEquals( s + "--", Const.Rpad( s, "-", 8 ) ); assertEquals( s, Const.Rpad( s, null, 15 ) ); assertEquals( s, Const.Rpad( s, "", 15 ) ); assertEquals( s, Const.Rpad( s, "...
Const { public static boolean classIsOrExtends( Class<?> clazz, Class<?> superClass ) { if ( clazz.equals( Object.class ) ) { return false; } return clazz.equals( superClass ) || classIsOrExtends( clazz.getSuperclass(), superClass ); } static double round( double f, int places ); static double round( double f, int pla...
@Test public void testClassIsOrExtends() { assertFalse( Const.classIsOrExtends( Object.class, Object.class ) ); assertTrue( Const.classIsOrExtends( String.class, String.class ) ); assertTrue( Const.classIsOrExtends( ArrayList.class, ArrayList.class ) ); }
XMLFormatter { public static String format( String xml ) { XMLStreamReader rd = null; XMLStreamWriter wr = null; StringWriter result = new StringWriter(); try { rd = INPUT_FACTORY.createXMLStreamReader( new StringReader( xml ) ); wr = OUTPUT_FACTORY.createXMLStreamWriter( result ); StartElementBuffer startElementBuffer...
@Test public void test1() throws Exception { String inXml, expectedXml; try ( InputStream in = XMLFormatterTest.class.getResourceAsStream( "XMLFormatterIn1.xml" ) ) { inXml = IOUtils.toString( in ); } try ( InputStream in = XMLFormatterTest.class.getResourceAsStream( "XMLFormatterExpected1.xml" ) ) { expectedXml = IOUt...
XMLCheck { public static boolean isXMLWellFormed( InputStream is ) throws KettleException { boolean retval = false; try { SAXParserFactory factory = XMLParserFactoryProducer.createSecureSAXParserFactory(); XMLTreeHandler handler = new XMLTreeHandler(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse( is, ...
@Test( expected = KettleException.class ) public void exceptionIsThrownWhenParsingXmlWithBigAmountOfExternalEntities() throws KettleException { final String maliciousXml = "<?xml version=\"1.0\"?>\n" + "<!DOCTYPE lolz [\n" + " <!ENTITY lol \"lol\">\n" + " <!ELEMENT lolz (#PCDATA)>\n" + " <!ENTITY lol1 \"&lol;&lol;&lol;...
KettleVFS { public static boolean startsWithScheme( String vfsFileName ) { FileSystemManager fsManager = getInstance().getFileSystemManager(); boolean found = false; String[] schemes = fsManager.getSchemes(); for ( int i = 0; i < schemes.length; i++ ) { if ( vfsFileName.startsWith( schemes[i] + ":" ) ) { found = true; ...
@Test public void testStartsWithScheme() { String fileName = "zip:file: assertTrue( KettleVFS.startsWithScheme( fileName ) ); fileName = "SavedLinkedres.zip!Calculate median and percentiles using the group by steps.ktr"; assertFalse( KettleVFS.startsWithScheme( fileName ) ); }
SingleRowRowSet extends BaseRowSet implements Comparable<RowSet>, RowSet { @Override public boolean putRow( RowMetaInterface rowMeta, Object[] rowData ) { this.rowMeta = rowMeta; this.row = rowData; return true; } @Override Object[] getRow(); @Override Object[] getRowImmediate(); @Override Object[] getRowWait( long ti...
@Test public void testPutRow() throws Exception { rowSet.putRow( new RowMeta(), row ); assertSame( row, rowSet.getRow() ); }
SingleRowRowSet extends BaseRowSet implements Comparable<RowSet>, RowSet { @Override public boolean putRowWait( RowMetaInterface rowMeta, Object[] rowData, long time, TimeUnit tu ) { return putRow( rowMeta, rowData ); } @Override Object[] getRow(); @Override Object[] getRowImmediate(); @Override Object[] getRowWait( l...
@Test public void testPutRowWait() throws Exception { rowSet.putRowWait( new RowMeta(), row, 1, TimeUnit.SECONDS ); assertSame( row, rowSet.getRowWait( 1, TimeUnit.SECONDS ) ); }
SingleRowRowSet extends BaseRowSet implements Comparable<RowSet>, RowSet { @Override public Object[] getRowImmediate() { return getRow(); } @Override Object[] getRow(); @Override Object[] getRowImmediate(); @Override Object[] getRowWait( long timeout, TimeUnit tu ); @Override boolean putRow( RowMetaInterface rowMeta, ...
@Test public void testGetRowImmediate() throws Exception { rowSet.putRow( new RowMeta(), row ); assertSame( row, rowSet.getRowImmediate() ); }
SingleRowRowSet extends BaseRowSet implements Comparable<RowSet>, RowSet { @Override public int size() { return row == null ? 0 : 1; } @Override Object[] getRow(); @Override Object[] getRowImmediate(); @Override Object[] getRowWait( long timeout, TimeUnit tu ); @Override boolean putRow( RowMetaInterface rowMeta, Objec...
@Test public void testSize() throws Exception { assertEquals( 0, rowSet.size() ); rowSet.putRow( new RowMeta(), row ); assertEquals( 1, rowSet.size() ); rowSet.clear(); assertEquals( 0, rowSet.size() ); }
DateDetector { public static String getRegexpByDateFormat( String dateFormat ) { return getRegexpByDateFormat( dateFormat, null ); } private DateDetector(); static String getRegexpByDateFormat( String dateFormat ); static String getRegexpByDateFormat( String dateFormat, String locale ); static String getDateFormatByRe...
@Test public void testGetRegexpByDateFormat() { assertNull( DateDetector.getRegexpByDateFormat( null ) ); assertEquals( SAMPLE_REGEXP, DateDetector.getRegexpByDateFormat( SAMPLE_DATE_FORMAT ) ); } @Test public void testGetRegexpByDateFormatLocale() { assertNull( DateDetector.getRegexpByDateFormat( null, null ) ); asser...
DateDetector { public static String getDateFormatByRegex( String regex ) { return getDateFormatByRegex( regex, null ); } private DateDetector(); static String getRegexpByDateFormat( String dateFormat ); static String getRegexpByDateFormat( String dateFormat, String locale ); static String getDateFormatByRegex( String ...
@Test public void testGetDateFormatByRegex() { assertNull( DateDetector.getDateFormatByRegex( null ) ); assertEquals( SAMPLE_DATE_FORMAT, DateDetector.getDateFormatByRegex( SAMPLE_REGEXP ) ); } @Test public void testGetDateFormatByRegexLocale() { assertNull( DateDetector.getDateFormatByRegex( null, null ) ); assertNull...
DateDetector { public static Date getDateFromString( String dateString ) throws ParseException { String dateFormat = detectDateFormat( dateString ); if ( dateFormat == null ) { throw new ParseException( "Unknown date format.", 0 ); } return getDateFromStringByFormat( dateString, dateFormat ); } private DateDetector();...
@Test public void testGetDateFromString() throws ParseException { assertEquals( SAMPLE_DATE_US, DateDetector.getDateFromString( SAMPLE_DATE_STRING_US ) ); try { DateDetector.getDateFromString( null ); } catch ( ParseException e ) { } } @Test public void testGetDateFromStringLocale() throws ParseException { assertEquals...
DateDetector { public static Date getDateFromStringByFormat( String dateString, String dateFormat ) throws ParseException { if ( dateFormat == null ) { throw new ParseException( "Unknown date format. Format is null. ", 0 ); } if ( dateString == null ) { throw new ParseException( "Unknown date string. Date string is nul...
@Test public void testGetDateFromStringByFormat() throws ParseException { assertEquals( SAMPLE_DATE, DateDetector.getDateFromStringByFormat( SAMPLE_DATE_STRING, SAMPLE_DATE_FORMAT ) ); try { DateDetector.getDateFromStringByFormat( SAMPLE_DATE_STRING, null ); } catch ( ParseException e ) { } try { DateDetector.getDateFr...
DateDetector { public static String detectDateFormat( String dateString ) { return detectDateFormat( dateString, null ); } private DateDetector(); static String getRegexpByDateFormat( String dateFormat ); static String getRegexpByDateFormat( String dateFormat, String locale ); static String getDateFormatByRegex( Strin...
@Test public void testDetectDateFormat() { assertEquals( SAMPLE_DATE_FORMAT, DateDetector.detectDateFormat( SAMPLE_DATE_STRING, LOCALE_es ) ); assertNull( DateDetector.detectDateFormat( null ) ); }
DateDetector { public static boolean isValidDate( String dateString, String dateFormat ) { try { getDateFromStringByFormat( dateString, dateFormat ); return true; } catch ( ParseException e ) { return false; } } private DateDetector(); static String getRegexpByDateFormat( String dateFormat ); static String getRegexpBy...
@Test public void testIsValidDate() { assertTrue( DateDetector.isValidDate( SAMPLE_DATE_STRING_US ) ); assertFalse( DateDetector.isValidDate( null ) ); assertTrue( DateDetector.isValidDate( SAMPLE_DATE_STRING, SAMPLE_DATE_FORMAT ) ); assertFalse( DateDetector.isValidDate( SAMPLE_DATE_STRING, null ) ); }
DateDetector { public static boolean isValidDateFormatToStringDate( String dateFormat, String dateString ) { String detectedDateFormat = detectDateFormat( dateString ); if ( ( dateFormat != null ) && ( dateFormat.equals( detectedDateFormat ) ) ) { return true; } return false; } private DateDetector(); static String ge...
@Test public void testIsValidDateFormatToStringDate() { assertTrue( DateDetector.isValidDateFormatToStringDate( SAMPLE_DATE_FORMAT_US, SAMPLE_DATE_STRING_US ) ); assertFalse( DateDetector.isValidDateFormatToStringDate( null, SAMPLE_DATE_STRING_US ) ); assertFalse( DateDetector.isValidDateFormatToStringDate( SAMPLE_DATE...
StringEvaluator { public int getCount() { return count; } StringEvaluator(); StringEvaluator( boolean tryTrimming ); StringEvaluator( boolean tryTrimming, List<String> numberFormats, List<String> dateFormats ); StringEvaluator( boolean tryTrimming, String[] numberFormats, String[] dateFormats ); void evaluateString(...
@Test public void testGetCount() { List<String> strings = Arrays.asList( "02/29/2000", "03/29/2000" ); for ( String string : strings ) { evaluator.evaluateString( string ); } assertEquals( strings.size(), evaluator.getCount() ); }
EnvUtil { public static void environmentInit() throws KettleException { if ( Thread.currentThread().getContextClassLoader() == null ) { Thread.currentThread().setContextClassLoader( ClassLoader.getSystemClassLoader() ); } Map<Object, Object> kettleProperties = EnvUtil.readProperties( Const.KETTLE_PROPERTIES ); insertDe...
@Test public void vfsUserDirIsRoot_IsPublishedOnInitialisation() throws Exception { EnvUtil.environmentInit(); assertNotNull( Variables.getADefaultVariableSpace().getVariable( Const.VFS_USER_DIR_IS_ROOT ) ); assertNotNull( System.getProperty( Const.VFS_USER_DIR_IS_ROOT ) ); }
EnvUtil { public static Locale createLocale( String localeCode ) { Locale resultLocale = null; if ( !Utils.isEmpty( localeCode ) ) { StringTokenizer parser = new StringTokenizer( localeCode, "_" ); if ( parser.countTokens() == 2 ) { resultLocale = new Locale( parser.nextToken(), parser.nextToken() ); } else { resultLoc...
@Test public void createLocale_Null() throws Exception { assertNull( EnvUtil.createLocale( null ) ); } @Test public void createLocale_Empty() throws Exception { assertNull( EnvUtil.createLocale( "" ) ); } @Test public void createLocale_SingleCode() throws Exception { assertEquals( Locale.ENGLISH, EnvUtil.createLocale( ...
TemporaryCacheManager { public void cacheSmallBlock(SmallBlock smallBlock) { smallBlockCacheMap.put(smallBlock.getHeader().getHash(), smallBlock); } private TemporaryCacheManager(); static TemporaryCacheManager getInstance(); void cacheSmallBlock(SmallBlock smallBlock); void cacheSmallBlockWithRequest(NulsDigestData r...
@Test public void cacheSmallBlock() { SmallBlock smallBlock = new SmallBlock(); BlockHeader header = new BlockHeader(); NulsDigestData hash = NulsDigestData.calcDigestData("abcdefg".getBytes()); header.setHash(hash); manager.cacheSmallBlock(smallBlock); assertTrue(true); this.getSmallBlock(hash, smallBlock); this.remov...
RoundManager { public MeetingRound getRoundByIndex(long roundIndex) { MeetingRound round = null; for (int i = roundList.size() - 1; i >= 0; i--) { round = roundList.get(i); if (round.getIndex() == roundIndex) { break; } } return round; } RoundManager(Chain chain); MeetingRound getRoundByIndex(long roundIndex); void add...
@Test public void testGetRoundByIndex() { assertNotNull(roundManager); assertNotNull(roundManager.getChain()); long index = 1002L; assertEquals(0, roundManager.getRoundList().size()); MeetingRound round = new MeetingRound(); round.setIndex(index); roundManager.addRound(round); assertEquals(1, roundManager.getRoundList(...
RoundManager { public boolean clearRound(int count) { Lockers.ROUND_LOCK.lock(); boolean doit = false; try { while (roundList.size() > count) { doit = true; roundList.remove(0); } if (doit) { MeetingRound round = roundList.get(0); round.setPreRound(null); } return true; } finally { Lockers.ROUND_LOCK.unlock(); } } Roun...
@Test public void testClearRound() { MeetingRound round = new MeetingRound(); round.setIndex(1l); roundManager.addRound(round); round = new MeetingRound(); round.setIndex(2l); roundManager.addRound(round); round = new MeetingRound(); round.setIndex(3l); roundManager.addRound(round); round = new MeetingRound(); round.se...
RoundManager { public MeetingRound initRound() { MeetingRound currentRound = resetRound(false); if (currentRound.getPreRound() == null) { BlockExtendsData extendsData = null; List<BlockHeader> blockHeaderList = chain.getAllBlockHeaderList(); for (int i = blockHeaderList.size() - 1; i >= 0; i--) { BlockHeader blockHeade...
@Test public void testInitRound() { assertNotNull(roundManager); assertNotNull(roundManager.getChain()); Chain chain = roundManager.getChain(); assertNotNull(chain.getEndBlockHeader()); assert(chain.getAllBlockList().size() > 0); MeetingRound round = roundManager.initRound(); assertNotNull(round); assertEquals(round.ge...
ConsensusTool { public static SmallBlock getSmallBlock(Block block) { SmallBlock smallBlock = new SmallBlock(); smallBlock.setHeader(block.getHeader()); List<NulsDigestData> txHashList = new ArrayList<>(); for (Transaction tx : block.getTxs()) { txHashList.add(tx.getHash()); if (tx.isSystemTx()) { smallBlock.addBaseTx(...
@Test public void testGetSmallBlock() { Block block = createBlock(); SmallBlock smallBlock = ConsensusTool.getSmallBlock(block); assertNotNull(smallBlock); assertEquals(smallBlock.getHeader(), block.getHeader()); assertEquals(smallBlock.getSubTxList().size() , 0); assertEquals(smallBlock.getTxHashList().get(0), block.g...
RandomSeedUtils { public static byte[] createRandomSeed() { BigInteger value = new BigInteger(256, new Random()); byte[] result = value.toByteArray(); if (result.length > 32) { byte[] temp = new byte[32]; System.arraycopy(result, result.length - 32, temp, 0, 32); result = temp; } else if (result.length < 32) { byte[] t...
@Test public void createRandomSeed() { for (int i = 0; i < 1000000; i++) { byte[] result = RandomSeedUtils.createRandomSeed(); assertEquals(result.length, 32); } }
RandomSeedUtils { public static byte[] getLastDigestEightBytes(byte[] bytes) { byte[] hash = Sha256Hash.hashTwice(bytes); byte[] result = new byte[8]; System.arraycopy(hash, bytes.length - 8, result, 0, 8); return result; } static byte[] createRandomSeed(); static byte[] getLastDigestEightBytes(byte[] bytes); static R...
@Test public void getLastDigestEightBytes() { byte[] seed = RandomSeedUtils.createRandomSeed(); byte[] hash = RandomSeedUtils.getLastDigestEightBytes(seed); byte[] hash2 = RandomSeedUtils.getLastDigestEightBytes(seed); assertTrue(ArraysTool.arrayEquals(hash, hash2)); assertEquals(hash.length, 8); }
BlockQueueProvider { public boolean put(BlockContainer blockContainer) { boolean receive = (blockContainer.getStatus() == BlockContainerStatus.RECEIVED); if (receive) { int status = BlockContainerStatus.RECEIVED; checkDownloadService(); if (!downloadService.isDownloadSuccess().isSuccess()) { status = BlockContainerStat...
@Test public void testPut() { assertNotNull(blockQueueProvider); assertEquals(0, blockQueueProvider.size()); Block block = new Block(); boolean result = blockQueueProvider.put(new BlockContainer(block, BlockContainerStatus.RECEIVED)); assertTrue(result); assertEquals(1, blockQueueProvider.size()); }
BlockQueueProvider { public BlockContainer get() { BlockContainer blockContainer = null; if (!downloadBlockQueueHasDestory) { blockContainer = downloadBlockQueue.poll(); } checkDownloadService(); boolean hasDownloadSuccess = downloadService.isDownloadSuccess().isSuccess(); if (blockContainer == null && hasDownloadSucce...
@Test public void testGet() { assertNotNull(blockQueueProvider); assertEquals(0, blockQueueProvider.size()); if(downloadService.isDownloadSuccess().isSuccess()) { downloadService.setDownloadSuccess(false); } Block block = new Block(); boolean result = blockQueueProvider.put(new BlockContainer(block, BlockContainerStatu...
BlockProcessTask implements Runnable { @Override public void run() { Lockers.CHAIN_LOCK.lock(); try { doTask(); } catch (Exception e) { Log.error(e); } catch (Error e) { Log.error(e); } catch (Throwable e) { Log.error(e); } finally { Lockers.CHAIN_LOCK.unlock(); } } BlockProcessTask(BlockProcess blockProcess); @Overrid...
@Test public void testRun() { assertNotNull(blockProcessTask); if(downloadService.isDownloadSuccess().isSuccess()) { downloadService.setDownloadSuccess(false); } ConsensusStatusContext.setConsensusStatus(ConsensusStatus.WAIT_RUNNING); blockProcessTask.run(); assert(!ConsensusStatusContext.isRunning()); downloadService....
ChainContainer implements Cloneable { public MeetingRound getCurrentRound() { return roundManager.getCurrentRound(); } ChainContainer(Chain chain); boolean addBlock(Block block); Result verifyBlock(Block block); Result verifyBlock(Block block, boolean isDownload, boolean isNeedCheckCoinBaseTx); boolean verifyCoinBaseTx...
@Test public void testInit() { assertNotNull(chain); assertNotNull(chainContainer); assertNotNull(chainContainer.getCurrentRound()); assertEquals(chainContainer.getCurrentRound().getMemberCount(), 1); }
TemporaryCacheManager { public boolean cacheTx(Transaction tx) { return txCacheMap.put(tx.getHash(), tx); } private TemporaryCacheManager(); static TemporaryCacheManager getInstance(); void cacheSmallBlock(SmallBlock smallBlock); void cacheSmallBlockWithRequest(NulsDigestData requestHash, SmallBlock smallBlock); Small...
@Test public void cacheTx() { Transaction tx = new CacheTestTx(); tx.setTime(1234567654L); try { tx.setHash(NulsDigestData.calcDigestData(tx.serializeForHash())); } catch (IOException e) { Log.error(e); } manager.cacheTx(tx); assertTrue(true); getTx(tx.getHash(), tx); }
ChainContainer implements Cloneable { public boolean addBlock(Block block) { if (!chain.getEndBlockHeader().getHash().equals(block.getHeader().getPreHash()) || chain.getEndBlockHeader().getHeight() + 1 != block.getHeader().getHeight()) { return false; } List<Agent> agentList = chain.getAgentList(); List<Deposit> deposi...
@Test public void testAddBlock() { Block bestBlock = chainContainer.getBestBlock(); assertNotNull(bestBlock); Block newBlock = newBlock(bestBlock); Result success = chainContainer.verifyBlock(newBlock); assertTrue(success.isSuccess()); bestBlock = chainContainer.getBestBlock(); assertEquals(bestBlock.getHeader().getHei...
ChainContainer implements Cloneable { public boolean rollback(Block block) { int length = chain.getAllBlockList().size(); if (block == null || length == 0) { return false; } Block bestBlock = chain.getBestBlock(); if (!block.getHeader().getHash().equals(bestBlock.getHeader().getHash())) { Log.warn("rollbackTransaction ...
@Test public void testRollback() { testAddAgent(); assertEquals(chainContainer.getCurrentRound().getMemberCount(), 2); for (int i = 3; i > 0; i--) { Block bestBlock = chainContainer.getBestBlock(); boolean success = chainContainer.rollback(bestBlock); assert (success); } assertEquals(chainContainer.getCurrentRound().ge...
ChainContainer implements Cloneable { public ChainContainer getBeforeTheForkChain(ChainContainer chainContainer) { Chain newChain = new Chain(); newChain.setId(chainContainer.getChain().getId()); newChain.initData(chain.getStartBlockHeader(), new CopyOnWriteArrayList<>(chain.getAllBlockHeaderList()), new CopyOnWriteArr...
@Test public void testGetBeforeTheForkChain() { Block forkBlock = null; for (int i = 0; i < 20; i++) { Block bestBlock = chainContainer.getBestBlock(); Block newBlock = newBlock(bestBlock); Result success = chainContainer.verifyAndAddBlock(newBlock, false, true); assertTrue(success.isSuccess()); bestBlock = chainContai...
ChainContainer implements Cloneable { public ChainContainer getAfterTheForkChain(ChainContainer chainContainer) { BlockHeader pointBlockHeader = chainContainer.getChain().getStartBlockHeader(); Chain chain = new Chain(); List<Block> blockList = getChain().getAllBlockList(); boolean canAdd = false; for (int i = 0; i < b...
@Test public void testGetAfterTheForkChain() { Block forkBlock = null; for (int i = 0; i < 30; i++) { Block bestBlock = chainContainer.getBestBlock(); Block newBlock = newBlock(bestBlock); Result success = chainContainer.verifyAndAddBlock(newBlock, false, true); assertTrue(success.isSuccess()); bestBlock = chainContain...
MicroKernelBootstrap extends BaseModuleBootstrap { @Override public void init() { String folder = null; try { NulsConfig.NULS_CONFIG = ConfigLoader.loadIni(NulsConstant.USER_CONFIG_FILE); String mode = NulsConfig.NULS_CONFIG.getCfgValue(NulsConstant.CFG_SYSTEM_SECTION, "mode", "main"); if ("main".equals(mode)) { NulsCo...
@Test public void init() { bootstrap.init(); assertNotNull(NulsConfig.MODULES_CONFIG); assertNotNull(NulsConfig.NULS_CONFIG); assertTrue(SpringLiteContext.isInitSuccess()); assertNotNull(NulsConfig.VERSION); assertNotNull(ValidatorManager.isInitSuccess()); }
NulsDigestData extends BaseNulsData { public static NulsDigestData calcDigestData(BaseNulsData data) { return calcDigestData(data, (byte) 0); } NulsDigestData(); NulsDigestData(byte algType, byte[] bytes); @Override int size(); @Override void parse(NulsByteBuffer byteBuffer); byte getDigestAlgType(); void setDigestAlg...
@Test public void test() { NulsDigestData hash = NulsDigestData.calcDigestData(new byte[32]); System.out.println(hash); assertTrue(true); }
MessageBusServiceImpl implements MessageBusService { @Override public String subscribeMessage(Class<? extends BaseMessage> messageClass, NulsMessageHandler<? extends BaseMessage> messageHandler) { MessageManager.putMessage(messageClass); return handlerManager.registerMessageHandler(null, messageClass, messageHandler); ...
@Test public void subscribeMessage() throws Exception { subscribe(); assertNotNull(handlerId); Field field = messageBusService.getClass().getDeclaredField("processorManager"); field.setAccessible(true); DispatchManager processorManager = (DispatchManager) field.get(messageBusService); Class processorManagerClass = proc...
MessageBusServiceImpl implements MessageBusService { @Override public void unsubscribeMessage(String subscribeId) { this.handlerManager.removeMessageHandler(subscribeId); } @Override String subscribeMessage(Class<? extends BaseMessage> messageClass, NulsMessageHandler<? extends BaseMessage> messageHandler); @Override ...
@Test public void unsubscribeMessage() throws Exception { messageBusService.unsubscribeMessage(handlerId); Field field = messageBusService.getClass().getDeclaredField("processorManager"); field.setAccessible(true); DispatchManager processorManager = (DispatchManager) field.get(messageBusService); Class processorManager...
MessageBusServiceImpl implements MessageBusService { @Override public void receiveMessage(BaseMessage message, Node node) { try { this.processorManager.offer(new ProcessData(message, node)); } catch (Exception e) { Log.error(e); } } @Override String subscribeMessage(Class<? extends BaseMessage> messageClass, NulsMessa...
@Test public void receiveMessage() { BlockMessage blockMessage = new BlockMessage(); Node node = new Node("192.168.1.90",8003,1); messageBusService.receiveMessage(blockMessage, node); }
MessageBusServiceImpl implements MessageBusService { @Override public Result<List<String>> broadcast(BaseMessage message, Node excludeNode, boolean aysn, int percent) { BroadcastResult result = networkService.sendToAllNode(message, excludeNode, aysn, percent); return getNodeIdListResult(result); } @Override String sub...
@Test public void broadcastAndCache() { BlockMessage blockMessage = new BlockMessage(); Node node = new Node("192.168.1.90",8003,1); boolean aysn = true; Result<List<String>> result = messageBusService.broadcast(blockMessage, node, aysn,100); assertTrue(result.isSuccess()); assertTrue(result.getData().size()>0); }
TemporaryCacheManager { public void destroy() { this.smallBlockCacheMap.clear(); this.txCacheMap.clear(); } private TemporaryCacheManager(); static TemporaryCacheManager getInstance(); void cacheSmallBlock(SmallBlock smallBlock); void cacheSmallBlockWithRequest(NulsDigestData requestHash, SmallBlock smallBlock); Small...
@Test public void destroy() { manager.destroy(); assertNull(EhCacheManager.getInstance().getCache("temp-small-block-cache")); assertNull(EhCacheManager.getInstance().getCache("temp-tx-cache")); }
MessageBusServiceImpl implements MessageBusService { @Override public Result sendToNode(BaseMessage message, Node node, boolean aysn) { BroadcastResult result = networkService.sendToNode(message, node, aysn); if (!result.isSuccess()) { Log.error("send to node fail reason: " + result.getErrorCode().getMsg() + "::::" + n...
@Test public void sendToNode() { BlockMessage blockMessage = new BlockMessage(); Node node = new Node("192.168.1.90",8003,1); boolean aysn = true; assertTrue(messageBusService.sendToNode(blockMessage, node, aysn).isSuccess()); }
MessageBusModuleBootstrap extends AbstractMessageBusModule { @Override public void start() { DispatchManager.getInstance().init(true); } @Override void init(); @Override void start(); @Override void shutdown(); @Override void destroy(); @Override String getInfo(); }
@Test public void start() { messageBusModuleBootstrap.start(); }
MessageBusModuleBootstrap extends AbstractMessageBusModule { @Override public void shutdown() { DispatchManager.getInstance().shutdown(); } @Override void init(); @Override void start(); @Override void shutdown(); @Override void destroy(); @Override String getInfo(); }
@Test public void shutdown() { messageBusModuleBootstrap.shutdown(); }
MessageBusModuleBootstrap extends AbstractMessageBusModule { @Override public void destroy() { } @Override void init(); @Override void start(); @Override void shutdown(); @Override void destroy(); @Override String getInfo(); }
@Test public void destroy() { messageBusModuleBootstrap.destroy(); }
AccountBaseService { public Result getPrivateKey(String address, String password) { if (!AddressTool.validAddress(address)) { return Result.getFailed(AccountErrorCode.ADDRESS_ERROR); } Account account = accountService.getAccount(address).getData(); if (null == account) { return Result.getFailed(AccountErrorCode.ACCOUNT...
@Test public void getPrivateKeyTest() { List<Account> accounts = this.accountService.createAccount(1, "nuls123456").getData(); Account account = accounts.get(0); Result result = accountBaseService.getPrivateKey(account.getAddress().toString(), "nuls123456"); assertTrue(result.isSuccess()); try { account.unlock("nuls123...
AccountBaseService { public Result setPassword(String address, String password) { if (!AddressTool.validAddress(address)) { return Result.getFailed(AccountErrorCode.ADDRESS_ERROR); } if (StringUtils.isBlank(password)) { return Result.getFailed(AccountErrorCode.NULL_PARAMETER); } if (!StringUtils.validPassword(password)...
@Test public void setPassword() { List<Account> accounts = this.accountService.createAccount(1, "").getData(); Account account = accounts.get(0); accountBaseService.setPassword(account.getAddress().toString(),"nuls123456"); Account acc = accountService.getAccount(account.getAddress()).getData(); try { assertTrue(acc.un...
AccountBaseService { public Result changePassword(String address, String oldPassword, String newPassword) { if (!AddressTool.validAddress(address)) { return Result.getFailed(AccountErrorCode.ADDRESS_ERROR); } if (StringUtils.isBlank(oldPassword)) { return Result.getFailed(AccountErrorCode.PARAMETER_ERROR); } if (String...
@Test public void changePassword() { List<Account> accounts = this.accountService.createAccount(1, "nuls123456").getData(); Account account = accounts.get(0); accountBaseService.changePassword(account.getAddress().toString(),"nuls123456", "nuls111111"); Account acc = accountService.getAccount(account.getAddress()).getD...
AliasService { public Result<String> setAlias(String addr, String aliasName, String password) { if (!AddressTool.validAddress(addr)) { return Result.getFailed(AccountErrorCode.ADDRESS_ERROR); } Account account = accountService.getAccount(addr).getData(); if (null == account) { return Result.getFailed(AccountErrorCode.A...
@Test public void setAlias() { List<Account> accounts = accountService.createAccount(1, "nuls123456").getData(); Account account = accounts.get(0); Result result = aliasService.setAlias(account.getAddress().toString(), "nuls123456", "Charlie555"); assertTrue(result.isSuccess()); }
AliasService { public Result saveAlias(AliasPo aliaspo) throws NulsException { try { Result result = aliasStorageService.saveAlias(aliaspo); if (result.isFailed()) { this.rollbackAlias(aliaspo); } AccountPo po = accountStorageService.getAccount(aliaspo.getAddress()).getData(); if (null != po) { po.setAlias(aliaspo.getA...
@Test public void saveAlias() { List<Account> accounts = accountService.createAccount(1, "nuls123456").getData(); Account account = accounts.get(0); Alias alias = new Alias(account.getAddress().getAddressBytes(), "lichao"); try { assertTrue(aliasService.saveAlias(new AliasPo(alias)).isSuccess()); } catch (NulsException...
CallContractData extends TransactionLogicData implements ContractData { public String[][] getArgs() { return args; } @Override int size(); @Override void parse(NulsByteBuffer byteBuffer); @Override byte[] getSender(); void setSender(byte[] sender); @Override byte[] getContractAddress(); void setContractAddress(byte[] ...
@Test public void test1() { try { byte[] key = LedgerUtil.asBytes("aasdasdasdasda"); dbService.putModel(area, key, data); CallContractData dataConvert = dbService.getModel(area, key, CallContractData.class); System.out.println(dataConvert.toString()); String[][] strings = dataConvert.getArgs(); for(String[] bbb : strin...
BlockResource { @GET @Path("/bytes") @Produces(MediaType.APPLICATION_JSON) public RpcClientResult getBlockBytes(@QueryParam("hash") String hash) throws IOException { Result result; if (!NulsDigestData.validHash(hash)) { return Result.getFailed(KernelErrorCode.PARAMETER_ERROR).toRpcClientResult(); } Block block = null; ...
@Test public void getBlockBytes() { assertTrue(true); }
ECKey { public static ECKey signedMessageToKey(String message, String signatureBase64) throws SignatureException { byte[] signatureEncoded; try { signatureEncoded = Base64.decode(signatureBase64); } catch (RuntimeException e) { throw new SignatureException("Could not decode base64", e); } if (signatureEncoded.length < ...
@Test public void signedMessageToKeyTest() throws SignatureException { ECKey key = new ECKey(); System.out.println(key.getPrivateKeyAsHex()); System.out.println(key.getPublicKeyAsHex()); String message = "Nuls Signed Message:\nHello,I'am test case!@##$%998877"; String signatureBase64 = key.signMessage(message,null); Sy...
VersionUtils { public static boolean higherThan(String version0, String version1) { if (StringUtils.isBlank(version0) || StringUtils.isBlank(version1)) { throw new RuntimeException("version is null"); } Integer[] intArr0 = strArrayToInt(version0); Integer[] intArr1 = strArrayToInt(version1); boolean result = false; for...
@Test public void higherThan() { String v1 = "1.1.0"; String v2 = "1.1.0-beta"; String v3 = "1.1.1"; String v4 = "1.1.1-beta1"; String v5 = "1.1.1-beta2"; String v6 = "1.1.2-beta1"; String v7 = "1.2.0"; assertTrue(!VersionUtils.higherThan(v2, v1)); assertTrue(VersionUtils.higherThan(v3, v2)); assertTrue(VersionUtils.hi...
FileUtil { public static boolean deleteFolder(File folder) { if (!folder.exists()) { return true; } File[] files = folder.listFiles(); for (File file : files) { if (file.isFile()) { try { boolean b = file.delete(); if (!b) { Log.info("delete " + file.getName() + " result:" + b); mkNullToFile(file); } } catch (Exception...
@Test public void deleteFolder() { FileUtil.deleteFolder("C:\\Users\\Administrator\\Desktop\\release\\NULS-Wallet-0.9.10-windows-x64-for-test\\conf\\client-web"); }
UpgradeThread implements Runnable { private boolean download(String url, String filePath, String signature) throws IOException { if (!upgrading) { setFailedMessage("The upgrade has stopped"); return false; } byte[] bytes = HttpDownloadUtils.download(url); if (!verifySig(bytes, Hex.decode(signature))) { setFailedMessage...
@Test public void download() { System.out.print("abcdefg"); System.out.print("\b"); System.out.print("\b"); System.out.print("\b"); }
PoConvertUtil { public static String getAgentId(NulsDigestData hash) { String hashHex = hash.getDigestHex(); return hashHex.substring(hashHex.length() - 8).toUpperCase(); } static Agent poToAgent(AgentPo agentPo); static AgentPo agentToPo(Agent agent); static Deposit poToDeposit(DepositPo po); static DepositPo deposit...
@Test public void getAgentId() { NulsDigestData hash = NulsDigestData.calcDigestData("123123".getBytes()); System.out.println(PoConvertUtil.getAgentId(hash)); System.out.println(hash); assertTrue(true); }
ChainManager { public void newOrphanChain(Block block) { Chain orphanChain = new Chain(); orphanChain.initData(block); ChainContainer orphanChainContainer = new ChainContainer(orphanChain); orphanChains.add(orphanChainContainer); } ChainManager(); void newOrphanChain(Block block); boolean checkIsBeforeOrphanChainAndAdd...
@Test public void testNewOrphanChain() { assertNotNull(chainManager); Block block = createBlock(); chainManager.newOrphanChain(block); assertEquals(1, chainManager.getOrphanChains().size()); }
ChainManager { public long getBestBlockHeight() { if(masterChain == null || masterChain.getChain() == null || masterChain.getChain().getEndBlockHeader() == null) { return 0L; } return masterChain.getChain().getEndBlockHeader().getHeight(); } ChainManager(); void newOrphanChain(Block block); boolean checkIsBeforeOrphanC...
@Test public void testGetBestBlockHeight() { assertNotNull(chainManager); Block block = createBlock(); ChainContainer masterChain = new ChainContainer(new Chain()); chainManager.setMasterChain(masterChain); masterChain.getChain().addBlock(block); assertEquals(0L, chainManager.getBestBlockHeight()); }
ChainManager { public boolean checkIsBeforeOrphanChainAndAdd(Block block) { BlockHeader header = block.getHeader(); boolean success = false; for(ChainContainer chainContainer : orphanChains) { Chain chain = chainContainer.getChain(); if(header.getHash().equals(chain.getStartBlockHeader().getPreHash())) { success = true...
@Test public void testCheckIsBeforeOrphanChainAndAdd() { testGetBestBlockHeight(); Block block = createBlock(); Block block1 = createBlock(); block1.getHeader().setHeight(1L); block1.getHeader().setPreHash(block.getHeader().getHash()); ChainContainer orphanChain = new ChainContainer(new Chain()); orphanChain.getChain()...
ChainManager { public boolean checkIsAfterOrphanChainAndAdd(Block block) { BlockHeader header = block.getHeader(); for(ChainContainer chainContainer : orphanChains) { Chain chain = chainContainer.getChain(); if(header.getPreHash().equals(chain.getEndBlockHeader().getHash())) { chain.addBlock(block); return true; } } re...
@Test public void testCheckIsAfterOrphanChainAndAdd() { testGetBestBlockHeight(); Block block = createBlock(); Block block1 = createBlock(); block1.getHeader().setHeight(1L); block1.getHeader().setPreHash(block.getHeader().getHash()); ChainContainer orphanChain = new ChainContainer(new Chain()); orphanChain.getChain()....
RoundManager { public void addRound(MeetingRound meetingRound) { roundList.add(meetingRound); } RoundManager(Chain chain); MeetingRound getRoundByIndex(long roundIndex); void addRound(MeetingRound meetingRound); void checkIsNeedReset(); boolean clearRound(int count); MeetingRound getCurrentRound(); MeetingRound initRou...
@Test public void testAddRound() { assertNotNull(roundManager); assertNotNull(roundManager.getChain()); assertEquals(0, roundManager.getRoundList().size()); MeetingRound round = new MeetingRound(); roundManager.addRound(round); assertEquals(1, roundManager.getRoundList().size()); assertEquals(round, roundManager.getCur...
Attribute implements Cloneable, Matchable<Attribute<?>> { public T get() { return value; } Attribute(AttributeDefinition<T> definition); String name(); T get(); T getInitialValue(); void validate(); Attribute<T> protect(); void set(T value); T computeIfAbsent(Supplier<T> supplier); boolean isImmutable(); boolean isPers...
@Test public void testAttributeInitializer() { AttributeDefinition<Properties> def = AttributeDefinition.builder("props", null, Properties.class).initializer(new AttributeInitializer<Properties>() { @Override public Properties initialize() { return new Properties(); } }).build(); Attribute<Properties> attribute1 = def....
StandardConversions { public static byte[] convertJavaToOctetStream(Object source, MediaType sourceMediaType, Marshaller marshaller) throws IOException, InterruptedException { if (source == null) return null; if (!sourceMediaType.match(MediaType.APPLICATION_OBJECT)) { throw new EncodingException("sourceMediaType not co...
@Test public void testJavaToOctetStreamConversion() throws IOException, InterruptedException { Marshaller marshaller = new ProtoStreamMarshaller(); String string = "I've seen things you people wouldn't believe."; Double number = 12.1d; Instant complex = Instant.now(); byte[] binary = new byte[]{1, 2, 3}; MediaType stri...
KeyTransformationHandler { public Object stringToKey(String s) { char type = s.charAt(0); switch (type) { case 'S': return s.substring(2); case 'I': return Integer.valueOf(s.substring(2)); case 'Y': return Byte.valueOf(s.substring(2)); case 'L': return Long.valueOf(s.substring(2)); case 'X': return Short.valueOf(s.subs...
@Test(expectedExceptions = CacheException.class) public void testStringToUnknownKey() { keyTransformationHandler.stringToKey("Z:someKey"); } @Test(expectedExceptions = CacheException.class) public void testStringToKeyWithInvalidTransformer() { keyTransformationHandler.stringToKey("T:org.infinispan.InexistentTransformer...
KeyTransformationHandler { public String keyToString(Object key) { if (key instanceof byte[]) return "A:" + Base64.getEncoder().encodeToString((byte[]) key); if (key instanceof String) return "S:" + key; else if (key instanceof Integer) return "I:" + key; else if (key instanceof Boolean) return "B:" + key; else if (key...
@Test(expectedExceptions = IllegalArgumentException.class) public void testKeyToStringWithDefaultTransformerForNonSerializableObject() { NonSerializableKey key = new NonSerializableKey("test"); keyTransformationHandler.keyToString(key); }
HibernateSearchPropertyHelper extends ReflectionPropertyHelper { @Override public Object convertToPropertyType(Class<?> entityType, String[] propertyPath, String value) { IndexValueFieldDescriptor fieldDescriptor = getValueFieldDescriptor(entityType, propertyPath); if (fieldDescriptor == null) { return super.convertToP...
@Test public void testConvertIdProperty() { assertThat(convertToPropertyType(TestEntity.class, "id", "42")).isEqualTo("42"); } @Test public void testConvertStringProperty() { assertThat(convertToPropertyType(TestEntity.class, "name", "42")).isEqualTo("42"); } @Test public void testConvertIntProperty() { assertThat(conv...
EmptyIntSet extends AbstractImmutableIntSet { @Override public boolean containsAll(IntSet set) { return set.isEmpty(); } static IntSet getInstance(); @Override boolean contains(int i); @Override boolean containsAll(IntSet set); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @O...
@Test public void testContainsAll1() throws Exception { Set<Integer> hashSet = new HashSet<>(); hashSet.add(3); assertFalse(es.containsAll(hashSet)); assertTrue(hashSet.containsAll(es)); hashSet.remove(3); assertTrue(hashSet.containsAll(es)); assertTrue(es.containsAll(hashSet)); } @Test public void testContainsAll() th...
HibernateSearchPropertyHelper extends ReflectionPropertyHelper { @Override public IndexedFieldProvider<Class<?>> getIndexedFieldProvider() { return entityType -> { IndexDescriptor indexDescriptor = getIndexDescriptor(entityType); if (indexDescriptor == null) { return IndexedFieldProvider.NO_INDEXING; } return new Searc...
@Test public void testRecognizeAnalyzedField() { assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isAnalyzed(new String[]{"description"})).isTrue(); } @Test public void testRecognizeStoredField() { assertThat(propertyHelper.getIndexedFieldProvider().get(TestEntity.class).isStored(new String[]{"...
ReflectionHelper { public static PropertyAccessor getAccessor(Class<?> clazz, String propertyName) throws ReflectiveOperationException { if (propertyName == null || propertyName.length() == 0) { throw new IllegalArgumentException("Property name cannot be null or empty"); } if (propertyName.indexOf('.') != -1) { throw n...
@Test public void testGetSimpleProperty() throws Exception { assertEquals(int.class, ReflectionHelper.getAccessor(Base.class, "prop1").getPropertyType()); assertEquals(float.class, ReflectionHelper.getAccessor(Base.class, "prop2").getPropertyType()); } @Test public void testPropertyNotFound() throws Exception { expecte...
Interval { public boolean contains(K value) { return (includeLower ? low.compareTo(value) <= 0 : low.compareTo(value) < 0) && (includeUpper ? up.compareTo(value) >= 0 : up.compareTo(value) > 0); } Interval(K low, boolean includeLower, K up, boolean includeUpper); static K getMinusInf(); static K getPlusInf(); boolean c...
@Test public void testContains() { assertTrue(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false).contains(20)); assertFalse(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false).contains(1000)); assertFalse(new Interval(Interval.<Integer>getMinusInf(), false, 1000, false).contains(1001)); ass...
DoubleStat { Double getSum() { if (count == 0) { return null; } double tmp = sum + sumCompensation; if (Double.isNaN(tmp) && Double.isInfinite(simpleSum)) { return simpleSum; } else { return tmp; } } }
@Test public void testEmptySum() { DoubleStat sum = new DoubleStat(); assertNull(sum.getSum()); }
DoubleStat { Double getAvg() { return count == 0 ? null : getSum() / count; } }
@Test public void testEmptyAvg() { DoubleStat avg = new DoubleStat(); assertNull(avg.getAvg()); }
EmptyIntSet extends AbstractImmutableIntSet { @Override public IntStream intStream() { return IntStream.empty(); } static IntSet getInstance(); @Override boolean contains(int i); @Override boolean containsAll(IntSet set); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Overrid...
@Test public void testIntStream() throws Exception { assertEquals(0, es.intStream().count()); }
LikeCondition implements Condition<String> { @Override public boolean match(String attributeValue) { if (attributeValue == null) { return false; } switch (type) { case Equals: return attributeValue.equals(value); case StartsWith: return (length == -1 || length == attributeValue.length()) && attributeValue.startsWith(va...
@Test public void testDegeneratedEquals() { LikeCondition likeCondition = new LikeCondition("ab"); assertTrue(likeCondition.match("ab")); assertFalse(likeCondition.match("ac")); assertFalse(likeCondition.match("XabY")); } @Test public void testDegeneratedContains() { LikeCondition likeCondition = new LikeCondition("%ab...
EmptyIntSet extends AbstractImmutableIntSet { @Override public boolean equals(Object obj) { if (obj instanceof Set) { return ((Set) obj).size() == 0; } return false; } static IntSet getInstance(); @Override boolean contains(int i); @Override boolean containsAll(IntSet set); @Override int size(); @Override boolean isEm...
@Test public void testEquals() throws Exception { IntSet sis2 = new SingletonIntSet(4); assertNotEquals(es, sis2); assertNotEquals(sis2, es); IntSet sis3 = new SmallIntSet(2); assertEquals(sis3, es); assertEquals(es, sis3); }
Configuration { public int maxRetries() { return maxRetries; } Configuration(ExecutorFactoryConfiguration asyncExecutorFactory, Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory, ClassLoader classLoader, ClientIntelligence clientIntelligence, ConnectionPoolConfiguration connect...
@Test(expectedExceptions = CacheConfigurationException.class, expectedExceptionsMessageRegExp = "ISPN(\\d)*: Invalid max_retries \\(value=-1\\). " + "Value should be greater or equal than zero.") public void testNegativeRetriesPerServer() { ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBu...
Configuration { public SecurityConfiguration security() { return security; } Configuration(ExecutorFactoryConfiguration asyncExecutorFactory, Supplier<FailoverRequestBalancingStrategy> balancingStrategyFactory, ClassLoader classLoader, ClientIntelligence clientIntelligence, ConnectionPoolConfigu...
@Test(expectedExceptions = CacheConfigurationException.class) public void testInvalidAuthenticationConfig() { ConfigurationBuilder builder = HotRodClientTestingUtil.newRemoteConfigurationBuilder(); builder.security().authentication().enable().saslMechanism("PLAIN"); builder.build(); }
RocksDBStore implements NonBlockingStore<K, V> { @Override public CompletionStage<Void> write(int segment, MarshallableEntry<? extends K, ? extends V> entry) { return handler.write(segment, entry); } @Override CompletionStage<Void> start(InitializationContext ctx); @Override CompletionStage<Void> stop(); @Override Set...
@Test(groups = "stress") public void testConcurrentWrite() throws InterruptedException { final int THREADS = 8; final AtomicBoolean run = new AtomicBoolean(true); final AtomicInteger written = new AtomicInteger(); final CountDownLatch started = new CountDownLatch(THREADS); final CountDownLatch finished = new CountDownL...
L1ConfigurationBuilder extends AbstractClusteringConfigurationChildBuilder implements Builder<L1Configuration>, ConfigurationBuilderInfo { public L1ConfigurationBuilder enable() { attributes.attribute(ENABLED).set(true); return this; } L1ConfigurationBuilder(ClusteringConfigurationBuilder builder); @Override ElementDef...
@Test(expectedExceptions = CacheConfigurationException.class) public void testL1WithExceptionEviction() { Configuration config = new ConfigurationBuilder() .clustering() .cacheMode(CacheMode.DIST_SYNC) .l1().enable() .memory() .evictionStrategy(EvictionStrategy.EXCEPTION) .size(10) .transaction() .transactionMode(org.i...
DependencyGraph { public List<T> topologicalSort() throws CyclicDependencyException { lock.readLock().lock(); try { ArrayList<T> result = new ArrayList<>(); Deque<T> noIncomingEdges = new ArrayDeque<>(); Map<T, Integer> temp = new HashMap<>(); for (Map.Entry<T, Set<T>> incoming : incomingEdges.entrySet()) { int size = ...
@Test public void testEmpty() throws CyclicDependencyException { assertTrue(new DependencyGraph().topologicalSort().isEmpty()); } @Test public void testConcurrentAccess() throws Exception { DependencyGraph<String> graph = new DependencyGraph<>(); ExecutorService service = Executors.newCachedThreadPool(getTestThreadFact...
DependencyGraph { public void removeDependency(T from, T to) { lock.writeLock().lock(); try { Set<T> dependencies = outgoingEdges.get(from); if (dependencies == null || !dependencies.contains(to)) { throw new IllegalArgumentException("Inexistent dependency"); } dependencies.remove(to); incomingEdges.get(to).remove(from...
@Test public void testRemoveDependency() throws CyclicDependencyException { DependencyGraph<String> g = new DependencyGraph<>(); g.addDependency("E", "B"); g.addDependency("E", "C"); g.addDependency("E", "D"); g.addDependency("B", "D"); g.addDependency("B", "C"); g.addDependency("C", "D"); assertEquals(g.topologicalSor...
DependencyGraph { public void addDependency(T from, T to) { if (from == null || to == null || from.equals(to)) { throw new IllegalArgumentException("Invalid parameters"); } lock.writeLock().lock(); try { if (addOutgoingEdge(from, to)) { addIncomingEdge(to, from); } } finally { lock.writeLock().unlock(); } } List<T> to...
@Test(expectedExceptions = IllegalArgumentException.class) public void testAddSelf() { new DependencyGraph<>().addDependency("N", "N"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAdNull() { new DependencyGraph<>().addDependency("N", null); }
GridFile extends File { @Override public boolean createNewFile() throws IOException { if (exists()) return false; if (!checkParentDirs(getAbsolutePath(), false)) throw new IOException("Cannot create file " + getAbsolutePath() + " (parent dir does not exist)"); metadataCache.put(getAbsolutePath(), new Metadata(0, System...
@Test(expectedExceptions = IOException.class) public void testCreateNewFileInNonExistentDir() throws IOException { File file = fs.getFile("nonExistent/file.txt"); file.createNewFile(); }
EmptyIntSet extends AbstractImmutableIntSet { @Override public int size() { return 0; } static IntSet getInstance(); @Override boolean contains(int i); @Override boolean containsAll(IntSet set); @Override int size(); @Override boolean isEmpty(); @Override boolean contains(Object o); @Override PrimitiveIterator.OfInt i...
@Test public void testForEachPrimitive() { Set<Integer> results = new HashSet<>(); es.forEach((IntConsumer) results::add); assertEquals(0, results.size()); } @Test public void testForEachObject() { Set<Integer> results = new HashSet<>(); es.forEach((Consumer<? super Integer>) results::add); assertEquals(0, results.size...
GridFile extends File { @Override public String getPath() { return path; } GridFile(String pathname, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(String parent, String child, Cache<String, Metadata> metadataCache, int chunkSize, GridFilesystem fs); GridFile(File parent, String ...
@Test(expectedExceptions = FileNotFoundException.class) public void testWritingToDirectoryThrowsException2() throws IOException { File dir = createDir(); fs.getOutput(dir.getPath()); } @Test(expectedExceptions = FileNotFoundException.class) public void testReadingFromDirectoryThrowsException2() throws IOException { Fil...