id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
6123437_2
class ClassSearchUtil { public static String getPropertyFromClassPath(String propertyFileResourcePath,String propertyName ) throws Exception { Properties p = new Properties(); InputStream inStream = null; try { inStream = ClassSearchUtil.class.getClassLoader().getResourceAsStream(propertyFileResourcePath); ...
assertNotNull(ClassSearchUtil.getPropertyFromClassPath("META-INF/jsystemCore.build.properties", "jversion")); } }
6154058_11
class WonAssembler { @Deprecated public static void assemble(GraphCollection namedSignedGraph, Dataset graphOrigin) throws Exception { Ontology o = prepareSignatureOntology(namedSignedGraph); verifyGraphCollectionContainsExactlyOneNamedGraph(namedSignedGraph); addSignatureTriplesToOrigi...
// The Signingframework reader cannot reproduce the correct graph // structure, it has problems with blank nodes [] parts. // GraphCollection gc = TriGPlusReader.readFile(inFile); // create dataset that contains atom core data graph Dataset testDataset = TestSigningUtils.prepareT...
6179560_1
class KeySet { public KeySet(byte[] key, byte[] nonce) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, NoSuchPaddingException, InvalidAlgorithmParameterException { MaskGenerationFunction mgf = null; mgf = new MaskGenerationFunction(MessageDigest.getInstance("SHA256")); byte[] s...
byte[] k = {119,-72,44,103,89,-33,-10,45,51,24,-107,-57,-110,63,-104,-46,-118,40,-69,-86,114,31,33,-90,4,118,83,125,-7,16,-65,111,79,-89,61,61,102,68,-101,-40,99,-15,-24,-42,-125,35,115,-89,59,-24,11,-40,-74,89,66,-31,107,-17,-40,125,99,-101,-12,116,-7,102,-115,39,-101,-67,84,-29,-120,-31,-24,-24,-84,10,-79,-74,-21,1...
6179800_6
class Transformation implements Serializable { public T variable(String name, Object value) { return param(name, value); } public Transformation(Transformation transformation); public Transformation(List<Map> transformations); public Transformation(); public T width(Object value); ...
// using strings Transformation t = new Transformation(); t.variable("$foo", 10) .chain() .ifCondition(faceCount().gt(2)) .crop("scale") .width(new Condition("$foo * 200 / faceCount")) .endIf(); assertEquals(...
6187281_10
class QuartzTaskScheduler implements TaskScheduler { @Override public TaskRegistration scheduleTask(TaskConfiguration config, Object bean) throws TaskSchedulerException { if (config == null) { throw new IllegalArgumentException("config is null"); } if (bean == null) { ...
Scheduler scheduler = new FakeQuartzScheduler(); QuartzTaskScheduler quartzTaskScheduler = new QuartzTaskScheduler(); quartzTaskScheduler.setScheduler(scheduler); TestTask task = new TestTask(); TaskRegistration registration = quartzTaskScheduler.scheduleTask( n...
6212860_2
class QuadTree { public Object[] getValues() { final List<Object> arr = new ArrayList<Object>(); this.traverse_(this.root_, new Func() { @Override public void call(QuadTree quadTree, Node node) { arr.add(node.getPoint().getValue()); } }); ...
Object[] values = getTree().getValues(); Arrays.sort(values); String valueString = Arrays.asList(values).toString(); assertEquals("Sorted values should be [Bar, Baz, Bing, Bong, Foo]", "[Bar, Baz, Bing, Bong, Foo]", valueString); } }
6215833_5
class BTree { public void insert(KeyClass key, ValueClass value) { if (root == null) { root = BTreeNode.createLeaf(null, null); } if (root.ckeckExists(key)) { throw new DuplicateKeyException(); } BTreeNode.InsertResult insertResult ...
tree.insert(1L, 1L); Assert.assertNotNull(tree.getRoot()); Assert.assertArrayEquals(new Long[]{1L}, tree.getRoot().getKeys()); Assert.assertArrayEquals(new Long[]{1L}, tree.getRoot().getValues()); tree.insert(3L, 3L); tree.insert(2L, 2L); ...
6257768_8
class AbstractTriple { static Vector splitSpace(String triple){ final Vector results = new Vector(); String remaining = triple; int nextPos; do{ nextPos = remaining.indexOf(' '); if(nextPos >= 0){ results.addElement(remaining.substring(0, nextPos)); remaining = remaining.substring(nextPos + 1...
final Vector splitted = AbstractTriple.splitSpace(" asdf fdsa"); assertEquals(3, splitted.size()); assertEquals("", splitted.get(0)); assertEquals("asdf", splitted.get(1)); assertEquals("fdsa", splitted.get(2)); } }
6269725_1
class PageParametersExtensions { public static final boolean isNullOrEmpty(final StringValue stringValue) { return (stringValue == null) || stringValue.isNull() || stringValue.isEmpty(); } public static void addParameters(final IRequestParameters parameters, final Map<String, String[]> parameterMap); public ...
boolean actual = PageParametersExtensions.isNullOrEmpty(null); AssertJUnit.assertTrue("Should be true.", actual); StringValue sv = StringValue.valueOf(""); actual = PageParametersExtensions.isNullOrEmpty(sv); AssertJUnit.assertTrue("Should be true.", actual); final String s = null; sv = StringValue.valueO...
6275822_36
class Globs { public static ImmutableList<String> glob(final String glob) { Path path = getGlobPath(glob); int globIndex = getGlobIndex(path); if (globIndex < 0) { return of(glob); } return doGlob(path, searchPath(path, globIndex)); } private Globs();...
File file = folder.newFile(); String path = file.getAbsolutePath(); ImmutableList<String> files = Globs.glob(path); assertThat(files.contains(path), is(true)); } }
6278839_0
class ConnectionEvent extends Event { public Connection getConnection() { return this.connection; } public ConnectionEvent(EventType<? extends Event> et, Connector sConnector, Connector rConnector, Connection connection); public Connector getSenderConnector(); public Connector getReceive...
VFlow flow = FlowFactory.newFlow(); VNode n1 = flow.newNode(); Connector sender1 = n1.setMainOutput(n1.addOutput("control")); VNode n2 = flow.newNode(); Connector receiver2 = n2.addInput("control"); n2.setMainInput(receiver2); Connector sender2 = n2.addOutput("co...
6280863_22
class SqlPartialParser { public static String parseFromPath(final String path) { try { return fromPathToStringCache.get(path, new Callable<String>() { @Override public String call() throws Exception { return _parseFromPath(path); } }); } catch (ExecutionException e) { throw new Runtim...
try { SqlPartialParser.parseFromPath("/co/jirm/core/sql/partial-test-validate.sql#other"); fail("Should have thrown an exception"); } catch (JirmIllegalStateException e) { assertEquals("Reference '> #stuff' in /co/jirm/core/sql/partial-test-validate.sql at line: 44 does" + "\nNOT MATCH declaration /...
6281707_79
class LocalOAuthTokenCacheService implements OAuthTokenCacheService { @Override public void cacheToken(Token requestToken) { if (requestToken == null || requestToken.getToken() == null) { return; } tokenCache.put(requestToken.getToken(), requestToken); } @Override p...
oAuthTokenCacheService.cacheToken(null); assertEquals(1, oAuthTokenCacheService.tokenCache.size()); } }
6290993_103
class OneToManyJoin { public static <K, U, V, T> PCollection<T> oneToManyJoin(PTable<K, U> left, PTable<K, V> right, DoFn<Pair<U, Iterable<V>>, T> postProcessFn, PType<T> ptype) { return oneToManyJoin(left, right, postProcessFn, ptype, -1); } public ...
PTable<Integer, String> left = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()), 1, "one", 2, "two"); PTable<Integer, String> right = MemPipeline.typedTableOf(Avros.tableOf(Avros.ints(), Avros.strings()), 2, "2A", 2, "2B"); PCollection<Pair<String, String>> joined = OneToManyJo...
6293402_212
class RangeValidator extends AbstractValidator<T> { public static <C extends Comparable<? super C>> RangeValidator<C> of( String errorMessage, C minValue, C maxValue) { return new RangeValidator<>(errorMessage, Comparator.nullsFirst(Comparator.naturalOrder()), minValue, ...
assertPasses(10, RangeValidator.of("Must be between -123 and 42", -123, 42)); } }
6331476_36
class SystemMetadata { public Aspect.Builder getAspect() { final Aspect.Builder aspect = Aspect.all(); final All all = ClassReflection.getAnnotation(c, All.class); if (all != null) { aspect.all(all.value()); } final One one = ClassReflection.getAnnotation(c, One....
@All(ComponentX.class) abstract class Test extends BaseSystem { } assertEquals(Aspect.all(ComponentX.class), new SystemMetadata(Test.class).getAspect()); } }
6332635_3
class Header { public String getContentType() { return getFirstValue(CONTENT_TYPE); } public Header(); public Header(InputStream in); public Header(String header); public Header(Header header); public void add(String key, String val); public void add(HeaderField field); public void remove(HeaderField ...
assertTrue(new MimeType(header.getContentType()).match("text/xml")); } }
6357227_0
class MovingAverageUDF extends UDF { public float evaluate( final int numberOfUnits, final Text key, final float value) { LinkedList<Float> list = map.get(key); if (list == null) { list = new LinkedList<Float>(); map.put(key, list); } list.add(value); if (list.size() > numberOfUnits) { list.remo...
MovingAverageUDF udf = new MovingAverageUDF(); Text key = new Text("key"); assertEquals(0.0f, udf.evaluate(0, key, 1.0f), 0.0001f); assertEquals(0.0f, udf.evaluate(0, key, 2.0f), 0.0001f); assertEquals(0.0f, udf.evaluate(0, key, 3.0f), 0.0001f); assertEquals(0.0f, udf.evaluate(0, key, 4.0f), 0.0001f); } }
6358188_343
class FloatAnyAggregatorFactory extends AggregatorFactory { @Override public VectorAggregator factorizeVector(VectorColumnSelectorFactory selectorFactory) { ColumnCapabilities capabilities = selectorFactory.getColumnCapabilities(fieldName); if (capabilities == null || capabilities.getType().isNumeric()) ...
VectorAggregator aggregator = target.factorizeVector(selectorFactory); Assert.assertNotNull(aggregator); Assert.assertEquals(FloatAnyVectorAggregator.class, aggregator.getClass()); } }
6370211_54
class DefaultInterviewServiceImpl extends PersistenceManagerAwareService implements InterviewService { public List<StageTransition> getStageTransitions(Interview interview, Stage stage) { StageTransition template = new StageTransition(); template.setInterview(interview); template.setStage(stage.getName()...
DefaultInterviewServiceImpl service = new DefaultInterviewServiceImpl(); service.setPersistenceManager(persistenceManagerMock); // Create an empty list of stage transitions for the test. List<StageTransition> expectedStageTransitions = new ArrayList<StageTransition>(); StageTransition stageTransit...
6405716_25
class CharacterConverter extends AbstractConverter<Character> { @Override public Character convert(String value) { if (value != null && value.length() > 0) { return value.charAt(0); } return null; } private CharacterConverter underTest; } class Charact...
Character result = underTest.convert(" "); assertEquals(' ', result.charValue()); } }
6434628_5
class PermutationUtil { public static Set<String> permutateSQL(String delimiter, String... frag) { return new PermutationGenerator(frag).setDelimiter(delimiter).permutateSQL(); } } class PermutationUtilTest { @Test public void testPermutate() {
Set<String> set = PermutationUtil.permutateSQL("-", "1"); Assert.assertEquals(1, set.size()); Assert.assertTrue(set.contains("1")); set = PermutationUtil.permutateSQL("-", "1", "1"); Assert.assertEquals(1, set.size()); Assert.assertTrue(set.contains("1-1")); set...
6437134_0
class RouteRouteParser extends RouteParser { public Route parse() throws IOException { Route route = new Route(); try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); ...
// SETUP DATA config.put("name", "Sisimiut - Nuuk"); InputStream is = getClass().getResourceAsStream("/routes/Sisimiut - Nuuk.route"); RouteParser parser = new RouteRouteParser(is, config); // EXECUTE Route r = parser.parse(); // TEST ASSERTIONS...
6444116_54
class BanNameCommand extends CommonCommand { @Override public boolean onCommand(final CommonSender sender, CommandParser parser) { final boolean isSilent = parser.isSilent(); if (isSilent && !sender.hasPermission(getPermission() + ".silent")) { sender.sendMessage(Message.getString("sender.error.noPe...
PlayerData player = testUtils.createRandomPlayer(); CommonServer server = spy(plugin.getServer()); CommonSender sender = spy(server.getConsoleSender()); String[] args = new String[]{player.getName(), "test", "-s"}; assert (cmd.onCommand(sender, new CommandParser(plugin, args, 1))); await().unt...
6454766_0
class HazelcastAgent implements DiscoveryAgent, ConfigurationAgent { public boolean isLeader() { boolean leader = false; for (Member member : hazelcast.getCluster().getMembers()) { String zone = member.getStringAttribute("zone"); if (zone == null) { continue;...
HostInfo info = EasyMock.createNiceMock(HostInfo.class); EasyMock.expect(info.getZoneName()).andReturn("zone").anyTimes(); EasyMock.replay(info); HazelcastAgent agent = new HazelcastAgent(SERVICE, info, MONITOR); List<Boolean> listenerFired = new ArrayList<>(); agent.reg...
6457784_0
class Freud { public static <A> boolean analyse(A analysedObject, Matcher assertion) { return assertion.matches(analysedObject); } public static FreudRuleBuilder<T> iterateOver(Class<T> type); public static Iterable<Object[]> parameterise(Iterable<A> sourceObjects, int numberOfParameters); ...
assertTrue(Freud.analyse(analysed, CoreMatchers.startsWith("Z"))); } }
6476959_9
class App { static String run(File file, String fileTitle, boolean renderHtml) throws IOException, LinkTargetException, EngineException { // Set-up a simple wiki configuration WikiConfig config = DefaultConfigEnWp.generate(); final int wrapCol = 80; // Instantiate a compiler for wiki pages WtEngineImpl e...
String title = "Simple_Page"; URL url = AppTest.class.getResource("/" + title + ".wikitext"); String path = StringTools.decodeUsingDefaultCharset(url.getFile()); String actual = App.run(new File(path), title, false); actual = FileTools.lineEndToUnix(actual); InputStream expectedIs = AppTest.class.getReso...
6489406_31
class EventEmittingTrackerImpl implements EventEmittingTracker { static boolean isTrackStale(long lastAnyUpdate, long lastPositionUpdate, long currentUpdate) { long lastUpdate = Math.max(lastAnyUpdate, lastPositionUpdate); boolean trackStale = lastUpdate > 0L && currentUpdate - lastUpdate >= TRACK_...
assertFalse(EventEmittingTrackerImpl.isTrackStale(0, 0, EventEmittingTrackerImpl.TRACK_STALE_MILLIS - 1)); assertFalse(EventEmittingTrackerImpl.isTrackStale(0, 0, EventEmittingTrackerImpl.TRACK_STALE_MILLIS + 1)); long now = new Date(System.currentTimeMillis()).getTime(); assertFalse(E...
6500041_18
class FreebaseRDFMapper extends Mapper<LongWritable,Text,Text,Text> { @Override public void map(LongWritable k, Text v,Context c) throws IOException, InterruptedException { String line=v.toString(); if (line.startsWith("@prefix")) { incrementCounter(c,FreebasePrefilterCounter.PREFI...
String ordinaryTriple = "ns:aviation.aircraft.first_flight\tns:type.property.unique\ttrue."; mapper.map(new LongWritable(1L), new Text(ordinaryTriple), context); verify(context).getCounter(FreebasePrefilterCounter.ACCEPTED); verify(context) .write(new Text( "<http...
6505114_0
class ClassUtils { public static <T> T createInstanceOfGenericType(Class clazz){ return createInstanceOfGenericType(clazz,0); } public static T createInstanceOfGenericType(Class clazz,int index); public static Class<?> getRawType(Type type); } class ClassUtilsTest { @Test void createIn...
UtilA<Long> utilA = new UtilA<>(); Long dynamic = (Long) ClassUtils.createInstanceOfGenericType(utilA.getClass()); utilA.setDynamicInstace(dynamic); Assert.assertEquals(dynamic.longValue(),0);; } }
6552338_4
class ConnectionFactoryImpl extends EObjectImpl implements ConnectionFactory { public RecordFactory getRecordFactory() throws ResourceException { try { if (recordFactory == null) { JCoRepository repository = ((ConnectionImpl)getConnection()).getDestination().getRepository(); recordFactory = CciFactoryImp...
// Given ConnectionImpl mockConnection = mock(ConnectionImpl.class); JCoDestination mockDestination = mock(JCoDestination.class); JCoRepository mockRepository = mock(JCoRepository.class); when(mockConnectionManager.allocateConnection(mockManagedConnectionFactory, null)).thenReturn(mockConnection); when(mock...
6563886_6
class StringConverter implements Converter { public Object convert(String value) { return value; } public String toString(Object value); private StringConverter converter; } class StringConverterTest { private StringConverter converter; @Test public void convert() {
assertEquals("", converter.convert("")); assertEquals("try", converter.convert("try")); assertNull(converter.convert(null)); } }
6603193_10
class ArraySet extends AbstractSet<E> { @Override public boolean remove(@Nullable Object element) { int length = array.length; int index = indexOf(element, array, 0, length); if (index < 0) { return false; } Object[] newArray = new Object[length -...
set.addAll(Arrays.asList(0, 1, 2)); assertTrue(set.remove(1)); assertEquals(2, set.size()); assertTrue(set.remove(0)); assertEquals(1, set.size()); assertTrue(set.remove(2)); assertEquals(0, set.size()); } }
6605842_1
class ZkTopicManager extends AbstractTopicManager implements TopicManager { @Override public void stop() { logger.info("Stopping Topic manager."); // we just unregister it with zookeeper to make it unavailable from hub servers list try { hubManager.unregisterSelf(); ...
ServerConfiguration cfg1 = new CustomServerConfiguration(cfg.getServerPort() + 1), cfg2 = new CustomServerConfiguration( cfg.getServerPort() + 2); // TODO change cfg1 cfg2 params ZkTopicManager tm1 = new ZkTopicManager(zk, cfg1, scheduler), tm2 = new ZkTopicMan...
6662839_98
class TrusGuardLogParser implements LogParser { @Override public Map<String, Object> parse(Map<String, Object> params) { String line = (String) params.get("line"); if (line == null) return null; try { Map<String, Object> m = new HashMap<String, Object>(); Scanner scanner = new Scanner(line); scann...
String line = "1`0`2`1`000000`3`20071009`11:35:41`Low`6`172.16.104.1`3748`211.48.62.132`110`3003``스팸 메일 차단`2`0`circleo@gmail.com`circleo@kornet.net`FW: 광고 ..테스트 메일`"; Map<String, Object> m = new TrusGuardLogParser().parse(line(line)); // check log header assertNotNull(m); assertEquals(1, m.get("version")); ...
6682435_0
class UsageTimestampTool { void writeTimestamp(File directory, Long timestamp) throws IOException { File timestampFile = new File(directory, TIMESTAMP_FILE_NAME); CheckinUtils.writeObjectToFile(timestampFile, timestamp); } boolean generateAndWriteTimestamp(File directory); public int run(); public ...
LOG.info("Writing timestamp file to temporary directory for tests."); Long timestamp = 5684L; mTool.writeTimestamp(mTempDir.getRoot(), timestamp); LOG.info("Reading back contents of timestamp file and comparing."); assertEquals("timestamp read does not match timestamp that should have been written....
6719207_30
class CoordinationStructures { public long uniqueVersionId() { IdGenerator idGenerator = hz.getIdGenerator(CoordinationStructures.VERSION_GENERATOR); long id = idGenerator.newId(); int timeSeconds = (int) (System.currentTimeMillis() / 1000); long paddedId = id << 32; return paddedId + timeSeconds...
try { SploutConfiguration config = SploutConfiguration.getTestConfig(); HazelcastInstance hz = Hazelcast.newHazelcastInstance(HazelcastConfigBuilder.build(config)); CoordinationStructures cS = new CoordinationStructures(hz); for (int i = 0; i < 1000; i++) { long version1 = cS.unique...
6725438_4
class IoUtils { public static void transfer(final InputStream input, final OutputStream output, final BuffersPool buffersPool) throws IOException { final InputStream in = buffersPool == null ? new BufferedInputStream(input, BUFFER_SIZE_8K) : new PoolableBufferedInputStream(input, BUFFER_SIZE_8K, ...
OutputStream output = mock(OutputStream.class); IoUtils.transfer(testInput, output, buffersPool); verify(output, atLeast(1)).write(any(byte[].class), anyInt(), anyInt()); verify(output).flush(); } }
6726370_93
class JenkinsVersion implements Comparable<JenkinsVersion> { public boolean isGreaterThan(String version) { JenkinsVersion create = create(version); return this.cv.compareTo(create.cv) > 0; } public JenkinsVersion(); public JenkinsVersion(String version); public final static Jen...
JenkinsVersion jv = new JenkinsVersion("1.651.1"); assertThat(jv.isGreaterThan("1.651.1")).isFalse(); } }
6752107_4
class TimeParserUtil { public static long parseDuration(String duration) { if (duration == null || duration.isEmpty()) { throw new IllegalArgumentException("duration may not be null"); } long toAdd = -1; if (days.matcher(duration).matches()) { Matcher matcher...
assertThat(parseDuration("1m"), is(60000L)); assertThat(parseDuration("2mn"), is(120000L)); assertThat(parseDuration("3min"), is(180000L)); assertThat(parseDuration("10d"), is(864000000L)); assertThat(parseDuration("20h"), is(72000000L)); assertThat(parseDuration("40s"), ...
6780534_29
class MessagesCloudDataStore implements MessagesDataStore { @Override public Observable<Void> delete(String messageId) { return apiService.deleteMessage(messageId); } public MessagesCloudDataStore(StudIpLegacyApiService apiService); @Override public Observable<List<MessageEntity>> messageInbox(); @Ove...
given(mockApiService.getMessage(FAKE_ID)).willReturn(Observable.empty()); messagesCloudDataStore.delete(FAKE_ID); verify(mockApiService).deleteMessage(FAKE_ID); } }
6791064_5
class CrontabTriggle implements Triggle { public void triggle(Date now) { Map<String, Task> tasks = scheduler.getAllRegistedTask(); Transaction t = Cat.newTransaction("Time-2", "CronTabTriggle"); for (Task task : tasks.values()) { Cat.logEvent("For",""); if (ta...
/* * insert previous task attempt */ TaskAttempt attempt = new TaskAttempt(); attempt.setTaskid(TASKID2); String instanceID = idFactory.newInstanceID(TASKID2); attempt.setInstanceid(instanceID); attempt.setAttemptid(idFactory.newAttemptID(instanceID)); ...
6804081_10
class ClassMethodsAnnotatedWith extends AbstractSpecification<Class<?>> { Class<?>[] getAllInterfacesAndClasses(Class<?> clazz) { return getAllInterfacesAndClasses(new Class[] { clazz } ); } public ClassMethodsAnnotatedWith(Class<? extends Annotation> annotation); @Override public boolean is...
assertThat(underTest.getAllInterfacesAndClasses(C2.class)).containsOnly(A2.class , B2.class , C2.class) ; assertThat(underTest.getAllInterfacesAndClasses(C1.class)).containsOnly(A1.class , B1.class , C1.class , Z1.class); } }
6810283_20
class AppointmentTypeValidator implements Validator { public void validate(Object obj, Errors errors) { AppointmentType appointmentType = (AppointmentType) obj; if (appointmentType == null) { errors.rejectValue("appointmentType", "error.general"); } else { validateDurationField(errors, appointmentType); ...
String evilName = "<script>alert(1)</script>"; AppointmentType appointmentTypeEvilName = new AppointmentType(evilName, "", 10); appointmentTypeValidator.validate(appointmentTypeEvilName, errors); Mockito.verify(errors).rejectValue("name", "appointmentscheduling.AppointmentType.unsafeName.errorMessage"); } }
6821657_32
class JsonBodyPattern extends BodyPattern { @Override public MatchField matches(StubMessage request) { String expected = JsonUtils.prettyPrint(pattern); String actual = JsonUtils.prettyPrint(request.getBody()); MatchResult result = matchResult(request); MatchField field = new Ma...
assertPattern("{\"foo\":\"bar\"}").matches("{\"foo\":\"bar\"}"); assertPattern("{\"foo\":\"bar\"}").doesNotMatch("{\"foo\":\"blah\"}"); assertPattern("{\"foo\":\"bar\"}").doesNotMatch("{\"foo2\":\"bar\"}"); assertPattern("{\"foo\":\"bar\"}").doesNotMatch("{}"); } }
6822394_1121
class AnnotationHandlerChainBuilder extends HandlerChainBuilder { public List<Handler> buildHandlerChainFromClass(Class<?> clz, List<Handler> existingHandlers, QName portQName, QName serviceQName, String bindingID) { LOG.fine("building handler chain"); ...
HandlerTestImpl handlerTestImpl = new HandlerTestImpl(); AnnotationHandlerChainBuilder chainBuilder = new AnnotationHandlerChainBuilder(); QName portQName = new QName("http://apache.org/handler_test", "SoapPortWildcard"); QName serviceQName = new QName("http://apache.org/handler_test", "...
6827663_4
class FibonacciCalculatorImpl implements FibonacciCalculator { @Override public long calculate(int order) { return order < 3 ? 1 : calculate(order-1) + calculate(order-2); } FibonacciCalculatorImpl calc; } class FibonacciCalculatorImplTest { FibonacciCalculatorImpl calc; @Test public void testRecursion...
assertEquals(calc.calculate(10)+calc.calculate(11), calc.calculate(12)); } }
6830643_0
class AmazonAppNotifier extends SherlockFragmentActivity { @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getSupportMenuInflater(); inflater.inflate(R.menu.activity_main, menu); return true; } @Override protected void onCreate(Bundle savedInst...
Menu mockMenu = mock(Menu.class); activity.onCreateOptionsMenu(mockMenu); verify(mockMenuInflater).inflate(R.menu.activity_main, mockMenu); } }
6833345_0
class NGSessionPool { NGSession take() { synchronized (lock) { if (done) { throw new UnsupportedOperationException("NGSession pool is shutting down"); } NGSession session = idlePool.poll(); if (session == null) { session = instanceCreator.get(); session.start(); ...
NGSessionPool pool = new NGSessionPool(server, 1); NGSession session = pool.take(); assertNotNull(session); } }
6848534_3
class WordCountAnalyzer { public TopWordCounts findTop(int number, Comparator<Integer> comparator) { return analyse(new FindTopAnalysis(number, comparator)); } public WordCountAnalyzer(WordCounts wc, boolean par); public WordCountAnalyzer(WordCounts wc, boolean par, int parLevel); publi...
assertEquals(twc, a1.findTop(number, COMP)); } }
6863498_22
class JiraRESTClient { public static List<IssueDTO> getIssues(String url, String username, String password, String path, String query) { WebClient client = createClient(url); checkAutherization(client, username, password); // Go to baseURI client.back(true); client.path(...
List<IssueDTO> issues = JiraRESTClient.getIssues( properties.getProperty("url"), properties.getProperty("username"), properties.getProperty("password"), JiraRESTClient.PATH_SEARCH, getJiraLabel(properties.getProperty("label"))); assertTrue...
6867673_30
class KeyValues { public Set<String> getKeys() { @SuppressWarnings("unchecked") final Set<String> result = new HashSet<String>(this.values.keySet()); return result; } public KeyValues(); @SuppressWarnings("unchecked") public KeyValues add(final String key, final String value)...
assertThat(keyValues.getKeys(), containsInAnyOrder("name_1", "name_2", "name_3")); } }
6872642_22
class PersonForm extends BasePage implements Serializable { public String edit() { if (id == null) { id = new Long(getParameter("id")); } person = personManager.get(id); return "edit"; } @Autowired public void setPersonManager(@Qualifier("personManager") Gener...
log.debug("testing edit..."); bean.setId(1L); assertEquals("edit", bean.edit()); assertNotNull(bean.getPerson()); assertFalse(bean.hasErrors()); } }
6879138_0
class SecuredAssembler extends ModelAssembler { @Override public Model open(Assembler a, Resource root, Mode mode) { List<Statement> lst = root.listProperties().toList(); Resource rootModel = getUniqueResource( root, BASE_MODEL ); if (rootModel == null) { throw new AssemblerException( root, String.format...
Resource r = model.createResource( "http://xenei.org/jena/security/test#secModel"); Object o = assembler.open( r ); Assert.assertTrue( o instanceof Model); Assert.assertTrue( o instanceof SecuredModel ); } }
6900541_1
class Utils { public static String readableFileSize(long size) { if(size <= 0) return "0 KB"; final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" }; int digitGroups = (int) (Math.log10(size)/Math.log10(1000)); return new DecimalFormat("#,##0.#").format(size/Math.pow(10...
String result = Utils.readableFileSize(0); Assert.assertEquals("0 KB", result); result = Utils.readableFileSize(957498560); Assert.assertEquals("957.5 MB", result); result = Utils.readableFileSize(2579477837L); Assert.assertEquals("2.6 GB", result); result = Ut...
6921975_21
class RequestSigningUtil { public static String createRequestSignature(final String method, final String dateHeader, final String requestUri, ByteSource body, final String secretKey) { final String signatureBase = createSignatureBase(method, dateHeader, requestUri, body); return createRequestSignat...
MockHttpServletRequest request = new MockHttpServletRequest("PUT", "some/URI"); request.addHeader("x-hmac-auth-date", formattedDateOfNow()); request.setContent("{ \"key\": \"value\"}".getBytes()); String encrypted = RequestSigningUtil.createRequestSignature(wrap(request), "secretKey");...
6944525_585
class RestLiServer implements RestRequestHandler, RestToRestLiRequestHandler, StreamRequestHandler, StreamToRestLiRequestHandler { @Override public void handleRequest(RestRequest request, RequestContext requestContext, Callback<RestResponse> callback) { //This code path c...
//This test verifies the server's ability to accept request attachments and send back response attachments. This is the //main test to verify the wire protocol for streaming. We send a payload that contains the rest.li payload and some attachments //and we send a response back with a rest.li payload and som...
6946733_5
class HazelcastJobHandleFactory implements JobHandleFactory { public final byte[] getNextJobHandle() { String handle = "H:".concat(clusterHostname).concat(":").concat(String.valueOf(jobHandleCounter.incrementAndGet())); return handle.getBytes(); } public HazelcastJobHandleFactory(Hazelcas...
IAtomicLong mockAtomicLong = mock(IAtomicLong.class); when(mockAtomicLong.incrementAndGet()).thenReturn(1L); HazelcastInstance mockHazelcast = mock(HazelcastInstance.class); when(mockHazelcast.getAtomicLong(anyString())).thenReturn(mockAtomicLong); HazelcastJobHandleFactory ha...
6951233_116
class SessionController1_9 extends BaseRestController { @RequestMapping(method = RequestMethod.POST) @ResponseBody @ResponseStatus(value = HttpStatus.OK) public void post(HttpServletRequest request, @RequestBody Map<String, String> body) { String localeStr = body.get("locale"); if (localeStr != null) { Loca...
Locale newLocale = new Locale("sp"); String content = "{\"locale\":\"" + newLocale.toString() + "\"}"; Assert.assertNotEquals(newLocale, Context.getLocale()); controller.post(hsr, new ObjectMapper().readValue(content, HashMap.class)); Assert.assertEquals(newLocale, Context.getLocale()); } }
6961882_16
class HttpHeaderParser { public static String parseCharset(Map<String, String> headers, String defaultCharset) { String contentType = headers.get(HTTP.CONTENT_TYPE); if (contentType != null) { String[] params = contentType.split(";"); for (int i = 1; i < params.length; i++) ...
// Like the ones we usually see headers.put("Content-Type", "text/plain; charset=utf-8"); assertEquals("utf-8", HttpHeaderParser.parseCharset(headers)); // Charset specified, ignore default charset headers.put("Content-Type", "text/plain; charset=utf-8"); assertEquals("u...
6972004_6
class MatchersEx { public static <T, V> Matcher<T> compose(final Function<T, ? extends V> transformer, final Matcher<V> matcher) { checkNotNull(transformer, "transformer"); checkNotNull(matcher, "matcher"); return new TypeSafeMatcher<T>() { @Override public void de...
// test boolean result = composeMatcher.matches(input); // verify verify(function).apply(input); verify(matcher).matches(output); assertThat(result, is(true)); } }
7010395_8
class Duration { @JsonCreator public static Duration valueOf(String text) { String trimmed = WHITESPACE.removeFrom(text).trim(); return new Duration(quantity(trimmed), unit(trimmed)); } public Duration(double quantity, Unit unit); public long value(); private static double qu...
assertThat(valueOf("1d"), is(new Duration(1L, DAYS))); assertThat(valueOf("1 d"), is(new Duration(1L, DAYS))); assertThat(valueOf("1 day"), is(new Duration(1L, DAYS))); assertThat(valueOf("1 days"), is(new Duration(1L, DAYS))); } }
7014975_0
class HashedWheelTimer implements Timer { @Override public TimeOut newTimeout(TimerTask task, long delay, TimeUnit unit) { start(); if (task == null) { throw new NullPointerException("task"); } if (unit == null) { throw new NullPointerException("unit"); } long deadline = System.nanoTime() + unit....
final HashedWheelTimer timer = new HashedWheelTimer(Executors.defaultThreadFactory(), 100, TimeUnit.MILLISECONDS, 32); final AtomicInteger counter = new AtomicInteger(); timer.newTimeout(new TimerTask() { @Override public void run(final TimeOut TimeOut) throws Exception { counter.incrementAndGet();...
7015517_16
class PluginKeyUtils { public static boolean isValid(String pluginKey) { return StringUtils.isNotBlank(pluginKey) && StringUtils.isAlphanumeric(pluginKey); } private PluginKeyUtils(); @CheckForNull public static String sanitize(@Nullable String mavenArtifactId); private static String keepLettersAndDig...
assertThat(PluginKeyUtils.isValid("foo")).isEqualTo(true); assertThat(PluginKeyUtils.isValid("sonarfooplugin")).isEqualTo(true); assertThat(PluginKeyUtils.isValid("foo6")).isEqualTo(true); assertThat(PluginKeyUtils.isValid("FOO6")).isEqualTo(true); } }
7022775_194
class TorrentClient { public byte[] getExtensionBytes() { return Arrays.copyOf(extensionBytes, extensionBytes.length); } private TorrentClient(Builder builder); private byte[] createPeerId(); public void download(Torrent torrent, Collection<String> trackerUrls); public void download(Torrent torrent); publi...
ConnectionDegradation connectionDegradationMock = mock(ConnectionDegradation.class); PhaseRegulator phaseRegulatorMock = mock(PhaseRegulator.class); ScheduledExecutorService executorServiceMock = mock(ScheduledExecutorService.class); IPeerConnector peerConnectorMock = mock(IPeerConnector.class); IPeerDistribu...
7028076_1
class TwitterServiceImpl implements TwitterService { public RequestToken getRequestToken() { final Twitter twitter = factory.getInstance(); try { return twitter.getOAuthRequestToken(); } catch (TwitterException e) { throw this.wrapException(e); } } p...
assertNotNull(this.service.getRequestToken()); } }
7031510_60
class FileSystem { protected static int maxFileNumber(String baseDir, String database, String date, String prefix, String suffix) { File[] files = visitFiles(baseDir, database, date, prefix, suffix); int max = -1; for (File file : files) { int number = parseNumber(file, prefix, ...
File file0 = new File(testDir, "/puma/20151010/bucket-0.data"); createFile(file0); File file1 = new File(testDir, "/puma/20151010/bucket-1.data"); createFile(file1); File file2 = new File(testDir, "/puma/20151010/bucket-10.data"); createFile(file2); File file3 = new File(testDir, "/puma/20151010/bucket...
7033568_0
class Minigames extends JavaPlugin { public MinigamePlayerManager getPlayerManager() { return this.playerManager; } public Minigames(); protected Minigames(final JavaPluginLoader loader, final PluginDescriptionFile description, final File dataFolder, final File file); public static Comp...
assertNotSame(player.getLocation(),game.getLobbyPosition()); plugin.getPlayerManager().addMinigamePlayer(player); MinigamePlayer mplayer = plugin.getPlayerManager().getMinigamePlayer(player.getUniqueId()); plugin.getPlayerManager().joinMinigame(mplayer, game, false, 0D); LobbySet...
7043506_11
class StreamAggregator { public static Observable<GroupedObservable<TypeAndNameKey, Map<String, Object>>> aggregateGroupedStreams(Observable<GroupedObservable<InstanceKey, Map<String, Object>>> stream) { return aggregateUsingFlattenedGroupBy(stream); } private StreamAggregator(); @SuppressWa...
TestScheduler scheduler = new TestScheduler(); TestSubject<GroupedObservable<InstanceKey, Map<String, Object>>> stream = TestSubject.create(scheduler); AtomicInteger numGroups = new AtomicInteger(); TestSubscriber<Object> ts = new TestSubscriber<>(); StreamAggregator.aggregateG...
7056723_44
class MethodCallerBytecodeGenerator extends AbstractClassGenerator { public MethodCaller create() { Object key = KEY_FACTORY.newInstance(callTarget.getTargetMethod(), null); try { return (MethodCaller) super.create(key); } catch (Mock4AjException error) { // NOPMD ...
Object caller = createGenerator(getTimeTarget).create(); assertThat(caller, instanceOf(MethodCaller.class)); } }
7072487_3
class EntitlementProducer { public String createEntitlement() { List<String> entitlementStrings = listEntitlements(); if (entitlementStrings.isEmpty()) { return null; } return StringUtils.join(entitlementStrings, ENTITLEMENT_SEPARATOR); } public EntitlementProd...
Membership ms = createMembership(); addPost(ms, "körvezető"); addPost(ms, "jani"); when(mock.findMembershipsForUser(user)).thenReturn(Arrays.asList(ms)); String memberEntitlement = "urn:geant:niif.hu:sch.bme.hu:entitlement:tag:Kir-Dev:1"; String leaderEntitlemnet = "urn:...
7091762_2
class CronExpressionDescriptor { public static String getDescription(String expression) throws ParseException { return getDescription(DescriptionTypeEnum.FULL, expression, new Options(), I18nMessages.DEFAULT_LOCALE); } private CronExpressionDescriptor(); public static String getDescription(S...
Assert.assertEquals("Every minute between 11:00 AM and 11:10 AM", CronExpressionDescriptor.getDescription("0-10 11 * * *")); Assert.assertEquals("Every minute between 11:00 and 11:10", CronExpressionDescriptor.getDescription("0-10 11 * * *", Options.twentyFourHour())); Assert.assertEquals("Every...
7109191_7
class JavaScriptSettings { public static final JavaScriptSettingsBuilder newBuilder() { return new JavaScriptSettingsBuilder() { private JQueryUiBuilder jqueryUiBuilder; private BootstrapJsBuilder bootstrapJsBuilder; @Override public JQueryUiBuilder withJque...
JavaScriptResourceReference fullCore = new JavaScriptResourceReference(getClass(), "full-core"); JavaScriptSettings settings = JavaScriptSettings.newBuilder().withJqueryUi(JQueryUiVersions.v1_9_2) .withAllUiCore(fullCore).endJqueryUi().build(); assertThat(settings.jqueryUi.uiCoreCo...
7139471_49
class MovieCategorySpinnerOnItemSelectedListener extends BaseSpinnerOnItemSelectedListener implements OnItemSelectedListener { @Override public void onItemSelected(AdapterView<?> viewAdapter, View view, int position, long id) { if (view == null) { return; } setMultiViewVideoActivity(activity); ...
doReturn(mockCategoryInfo).when(mockAdapterView).getItemAtPosition( anyInt()); doReturn("All").when(mockCategoryInfo).getCategory(); doReturn("Action").when(mockCategoryState).getGenreCategory(); doReturn(0).when(spyOnItemSelectedListener).getSavedInstancePosition( any(AdapterView.class)...
7144342_0
class Future implements java.util.concurrent.Future<V> { Future(MessagePack messagePack, FutureImpl impl) { this(messagePack, impl, null); } Future(MessagePack messagePack, FutureImpl impl); Future(MessagePack messagePack, FutureImpl impl, Template resultTemplate); public Future(Messa...
EventLoop loop = EventLoop.start(); Server svr = new Server(loop); svr.serve(new TestHandler()); svr.listen(19860); Client cli = new Client("127.0.0.1", 19860, loop); TestInterface c = cli.proxy(TestInterface.class); try { Future<String> f1 = c.m1("...
7170387_1
class DatabaseRequiredInRole extends AbstractRoleValidator { @Override public void validate(@Nullable String database, String role) throws ConfigurationException { /* * Rule only applies to rules in per database policy file */ if(database != null) { Iterable<Authorizable> authorizables = p...
DatabaseRequiredInRole dbRequiredInRole = new DatabaseRequiredInRole(); try { dbRequiredInRole.validate("db1", "server=server1->db=db1->URI=file:///user/hive/warehouse/tab1"); Assert.fail("Expected ConfigurationException"); } catch (ConfigurationException e) { ; } } }
7212262_3
class HazelcastService implements SmartLifecycle { @Override public int getPhase() { return Integer.MAX_VALUE; } public HazelcastService(final Config configuration, final MetricsRegistry metricsRegistry); @Override public void start(); @Override public void stop(); @Override public boolean isRunni...
final HazelcastService objectUnderTest = newObjectUnderTest(); assertEquals("getPhase() should return Integer.MAX_VALUE", Integer.MAX_VALUE, objectUnderTest.getPhase()); } }
7220231_1
class TnefTimeZone { public static TimeZone getTimeZone(int index, boolean observeDaylightSaving, String tzId) throws IOException { if (index < 0 || index > 59) return null; int bias = 0; // UTC offset in minutes int standardBias = 0; // offset in minutes from bias duri...
TimeZone tz = null; RawInputStream ris = null; ris = new RawInputStream(intToleByteArray(13), 0, 4); tz = TnefTimeZone.getTimeZone(ris); Assert.assertFalse(tz == null); Assert.assertTrue(tz.getRawOffset() == -28800000); Assert.assertTrue(tz.getDSTSavings(...
7257232_7
class Normalisation { public static String canonicaliseURL(String url) { return canonicaliseURL(url, true, true); } public static String sanitiseWARCHeaderValue(String value); public static String canonicaliseHost(String host); public static String fixURLErrors(String url); public stat...
final String[][] TESTS = new String[][]{ {"http://example.com/%C3%86blegr%C3%B8d", "http://example.com/Æblegrød"}, // UTF-8 escapes {"http://example.com/%C3%86blegr%C3", "http://example.com/Æblegr%c3"}, // Half UTF-8 2-byte escape {"http://example.com/Æ...
7272424_1
class PromoService implements Serializable { public void applyShippingPromotions(ShoppingCart shoppingCart) { if ( shoppingCart != null ) { //PROMO: if cart total is greater than 75, free shipping if ( shoppingCart.getCartItemTotal() >= 75) { shoppingCart.setShippingPromoSavings(shoppingCart.g...
//cart total 0 Assert.assertEquals(0, shoppingCart.getCartItemTotal(), 0); promoService.applyShippingPromotions(shoppingCart); Assert.assertEquals(0, shoppingCart.getShippingTotal(), 0); //cart total 74.99 shoppingCart.setCartItemTotal(74.99); shoppingCart.setShippingTotal(4.99); promoSer...
7276954_28
class CatalogPathUtils { public static AlluxioURI getTablePathUdb(String dbName, String tableName, String udbType) { return new AlluxioURI(PathUtils .concatPath(ServerConfiguration.get(PropertyKey.TABLE_CATALOG_PATH), dbName, TABLES_ROOT, tableName, udbType)); } private CatalogPathUtils...
String dbName = "dbName"; String tableName = "tableName"; String udbType = "udbType"; AlluxioURI path = CatalogPathUtils.getTablePathUdb(dbName, tableName, udbType); assertEquals(path.getPath(), PathUtils.concatPath(ServerConfiguration.global().get( PropertyKey.TABLE_CATALOG_PATH), dbName, ...
7308129_2
class PingServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(String.valueOf(new Date().getTime())); } } class PingServletTest { @Test public void test() throws ServletException, IOExcepti...
// given HttpServletResponse resp = Mockito.mock(HttpServletResponse.class); StringWriter sw = new StringWriter(); Mockito.when(resp.getWriter()).thenReturn(new PrintWriter(sw)); // when new PingServlet().doGet(null, resp); // then String s = sw.toString(); assertNotNull(s); long parsedTimestamp =...
7316492_0
class LocalizedString implements Serializable, Cloneable { public String get(Locale locale) { return localized.get(locale); } public LocalizedString(Map<Locale, String> localized); public LocalizedString(); public Map<Locale, String> getLocalized(); @Override public LocalizedString ...
final Locale en_US = Locale.fromJavaLocale(java.util.Locale.US); final Locale he_IL = Locale.fromJavaLocale(new java.util.Locale("he", "IL")); final Map<Locale, String> localized = new LinkedHashMap<>(); localized.put(en_US, "English string with special characters: \"{},\\"); lo...
7321072_139
class TextTokenizer { public LinkedList<Token> tokenize(String text) { if (logger.isDebugEnabled()) logger.debug("Tokenizing text: '" + text + "'"); text = text.replaceAll(" +", " "); // remove multiple consequent space chars text = text.trim(); final LinkedList<TextB...
{ final String text = "Fiyatları uçuşa geçti."; final Iterable<String> tokens = getSurfaces(tokenizer.tokenize(text)); assertThat(Lists.newArrayList(tokens), equalTo(Arrays.asList("Fiyatları", "uçuşa", "geçti", "."))); } { final String text = "Fiya...
7337208_1
class FileHashComparer { public static Map<String, Long> readHashes( File file ) throws FileNotFoundException { return readHashes( new FileInputStream(file) ); } public static ComparisonResult compareHashesAndDir( File hashes, File dir, IOFileFilter filter ); public static ComparisonResult com...
System.out.println( "readHashFile" ); File hashes = new File("testdata/utils/crc32hashes.txt"); Map<String, Long> result = FileHashComparer.readHashes( hashes ); assertEquals( Long.valueOf(0xf735fe81L), result.get(STR_ORACLE_DS) ); assertEquals( Long.valueOf(0x1...
7386322_2
class MainController extends AbstractController { @ResourceMapping(GET_TEMPLATES) public void getTemplates(ResourceRequest request, ResourceResponse response, @RequestParam("page") int page, @RequestParam("rows") int rows) throws Exception { try { User user = liferayService.getU...
MockResourceResponse response = new MockResourceResponse(); MockResourceRequest request = new MockResourceRequest(); List <Long> organizationIds = new LinkedList<Long>(); organizationIds.add((long) 1); organizationIds.add((long) 2); when(mockUser.getLast...
7393690_23
class ByteUtil { public static byte[] split(byte[] bytes, int start, int end) { if (bytes == null) { return null; } if (start < 0) { throw new IllegalArgumentException("start < 0"); } if (end > bytes.length) { throw new IllegalArgumentException("end > size"); } if (start > end) { throw new ...
byte[] in = new byte[] {0, 0, 1, 1, 1, 1, 0, 0}; byte[] out = ByteUtil.split(in, 2, 6); Assert.assertArrayEquals(new byte[] {1, 1, 1, 1}, out); System.out.println(String.format("[CRAFT-ATOM-UTIL] (^_^) <%s> Case -> make split. ", CaseCounter.incr(1))); } }
7403823_41
class CheckClasses { @SuppressWarnings("rawtypes") public static List<Class> getCheckClasses() { return CLASSES; } private CheckClasses(); } class CheckClassesTest { @Test public void test() {
for (Class cls : CheckClasses.getCheckClasses()) { String testName = '/' + cls.getName().replace('.', '/') + "Test.class"; assertThat(getClass().getResource(testName)) .overridingErrorMessage("No test for " + cls.getSimpleName()) .isNotNull(); } HtmlRulesDefinition rulesDefiniti...
7403873_31
class XmlSensor implements Sensor { @Override public void execute(SensorContext context) { List<InputFile> inputFiles = new ArrayList<>(); fileSystem.inputFiles(mainFilesPredicate).forEach(inputFiles::add); if (inputFiles.isEmpty()) { return; } boolean isSonarLintContext = context.runti...
init(false); fs.add(createInputFile("src/wrong-ampersand.xhtml")); sensor.execute(context); assertThat(context.allIssues()).isEmpty(); assertLog("Unable to analyse file .*wrong-ampersand.*", true); assertLog("Cause: org.xml.sax.SAXParseException.* Element type \"as\\.length\" must be followed...
7410462_0
class SubjectExtractor { public List<String> extract(String[] tokens) throws IOException { return extract(parser.parse(tokens)); } public SubjectExtractor(Parser parser, String confStr, boolean normalize); private void loadConfigString(String confStr); private Set<String> parsePart(Strin...
assertEquals(Arrays.asList("игрушка", "Lava", "кукла", "майя"), subjExtractor.extract("мягкая муз игрушка Lava кукла майя в красном платье".split(" "))); assertEquals(Arrays.asList(new String[]{"сапог"}), subjExtractor.extract(new String[]{"женские", "сапоги"})...
7416235_10
class GraphName { public static GraphName of(String name) { return new GraphName(canonicalize(name)); } private GraphName(String name); public static GraphName newAnonymous(); public static GraphName root(); public static GraphName empty(); private static String canonicalize(String name); public...
assertGraphNameEquals("", GraphName.of("")); assertGraphNameEquals("/", GraphName.of("/")); assertGraphNameEquals("/", GraphName.of("//")); assertGraphNameEquals("/", GraphName.of("///")); assertGraphNameEquals("foo", GraphName.of("foo")); assertGraphNameEquals("foo", GraphName.of("foo/")); ...
7416278_0
class PollingInputStream extends InputStream { @Override public synchronized int read(byte[] buffer, int offset, int length) throws IOException { int bytesRead = 0; if (length > 0) { while (available() == 0) { // Block until there are bytes to read. Thread.yield(); } synch...
PipedInputStream pipedInputStream = new PipedInputStream(); PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream); PollingInputStream pollingInputStream = new PollingInputStream(pipedInputStream, Executors.newCachedThreadPool()); byte[] expectedBuffer = new byte[64]; ...
7416746_1
class Node { public synchronized Channel getFreeChannel() { for (Channel c : channels) { if (c.isFree()) { c.setFree(false); return c; } } return null; } public Node(AntChipInterface antchip); protected synchronized EventMachine getEvm(); public AntChipInterface getAntChip(); public sync...
when(channel1.isFree()).thenReturn(false); assertNull(node.getFreeChannel()); } }
7420937_193
class GetProcessApplicationNameFromAnnotation implements Supplier<Optional<String>>, UnaryOperator<Optional<String>> { @Override public Optional<String> apply(Optional<String> springApplicationName) { Optional<String> processApplicationName = GetProcessApplicationNameFromAnnotation.getProcessApplicationName.ap...
assumeAnnotatedBeans(Variables.createVariables()); assertThat(function.apply(Optional.of("foo"))).isEqualTo(Optional.of("foo")); } }
7422160_52
class FileUtil { public static String backupFile(File source) { File backup = new File(source.getParent() + "/~" + source.getName()); try { BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(source))); BufferedWriter writer = new BufferedWriter( new OutputStreamW...
String content = FileUtil.readFile("testing.txt"); FileUtil.backupFile(new File("src/test/resources/testing.txt")); String content2 = FileUtil.readFile("~testing.txt"); Assert.assertEquals(content, content2); try { FileUtil.backupFile(new File("test/missing.txt")); fail("No Exception thrown with missin...
7436396_4
class UserDaoJDBC implements UserDao { @Override public User addUser(final User user) { // create date set to now(), only work for mysql final String INSERT_SQL = "insert into t_user (imei, imsi, phone_name,createdate) values (?, ?, ?, now())"; // return this.jdbcTemplate.update(INSERT_SQL, user.getImei(), ...
String newImei = "46022222222222"; int count = userDao.getUserCount(); logger.debug("user count is "+count); User user = new User(); user.setImei(newImei); user.setImsi(newImei); user.setPhoneName("Shanzhai"); logger.info("before add:"+user); user = userDao.addUser(user); //User ID should get...
7438954_5
class ArgumentMerger { public PlungerArguments merge(String cmdTarget, Config config, CommandLine line, Options options) throws Exception { PlungerArguments result = new PlungerArguments(); Target commandTarget = new TargetParser().parse(cmdTarget); Entry entry = config.getEntry(commandTarget.getHost()); if (...
PlungerArguments pa = merge("provider://host:1234/queue.destination", CommandName.CAT, "-n1", "-re"); assertMisc(pa, "cat", true, false); assertTarget(pa, "provider", "host", 1234, null, null, "queue.destination", "destination"); assertTrue(pa.containsCommandArgument("n")); assertTrue(pa.getCommandArgument("...
7450263_2
class HessianDecoder extends OneToOneDecoder { @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (!(msg instanceof ChannelBuffer)) { return msg; } ChannelBuffer buf = (ChannelBuffer) msg; if (buf.hasArray()) { ...
//构造序列化后的hessian字节码 SwallowMessage msg = new SwallowMessage(); msg.setGeneratedTime(new Date()); msg.setMessageId(123L); HashMap<String, String> map = new HashMap<String, String>(); map.put("property-key", "property-value"); msg.setContent("content"); ByteArrayOutputStrea...
7455819_22
class GzipCompressionPostHandler extends AbstractHandlerChain { @Override public boolean isApplicable(HandlerContext handlerContext) { // Retrieves the content type from the filtered response String mimeType = handlerContext.getResponse().getContentType(); // Required conditions boolean...
response.setContentType("incompatible-content-type"); HandlerContext handlerContext = new HandlerContext(context, request, response, null); assertThat(handler.isApplicable(handlerContext)).isFalse(); } }
7465720_23
class AbstractNativeElementContext implements SearchContext, FindsByTagName, FindsByName, FindsById, FindsByText, FindsByXPath, FindsByPartialText, FindsByClass { protected static List<AndroidElement> searchViews(AbstractNativeElementContext context, View root, ...
// Bottom ViewGroup D = match(); ViewGroup e = ignore(); ViewGroup F = match(); // Middle ViewGroup b = ignore(D, e); ViewGroup C = match(F); // Root ViewGroup root = ignore(b, C); List<View> views = searchViews(root); assertFoun...