id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
2117797_49
class WebRadioMessageFactory extends AbstractMessageFactory { @Override public List<Message2Send> getMessage(MessageProcessUnit inUnit) { if (inUnit instanceof MessageNSettingProcessUnit) { final SubscriptionSchedulingData theSubscriptionSchedulingData = inUnit.get(); final ApplicationSettingData urlSetting...
final Application theApplication = Factories.APPLICATION.findByName("net.violet.webradio.U105"); Factories.APPLICATION_SETTING.create(theApplication, "url", "webradioUrl"); final Subscription theSubscription = new SubscriptionMock(1, theApplication, getKowalskyObject()); final CCalendar theDeliveryDate = new CC...
2118259_0
class ContactsEJB implements ContactsService { @Override @Nonnull public List<ContactDetailsDTO> getContactDetails() { initContactsIfRequired(); final ArrayList<ContactDetailsDTO> contactDetails = new ArrayList<ContactDetailsDTO>(); for( final Contact contact : _contactDAO.findAll() ) { c...
assertEquals( 22, s( ContactsService.class ).getContactDetails().size() ); } }
2125451_113
class HashObject extends AbstractGeoGigOp<ObjectId> { public HashObject setObject(RevObject object) { this.object = object; return this; } @Override protected ObjectId _call(); private RevFeatureType featureType1; private RevFeatureType featureType2; private RevFeatureType fea...
RevPerson tagger = new RevPersonImpl("volaya", "volaya@boundlessgeo.com", -1000, -1); RevPerson tagger2 = new RevPersonImpl("groldan", "groldan@boundlessgeo.com", 10000, 0); RevTag tag = new RevTagImpl(null, "tag1", ObjectId.forString("fake commit id"), "message", tagger); ...
2125920_34
class LazyMPEInference extends InferenceApplication { public static void inference(List<Rule> rules, Reasoner reasoner, GroundRuleStore groundRuleStore, TermStore termStore, TermGenerator termGenerator, LazyAtomManager lazyAtomManager, int maxRounds) { // Performs rounds of inferenc...
LazyMPEInference mpe = new LazyMPEInference(info.model, inferDB); // The Friends predicate should be empty. assertEquals(0, inferDB.countAllGroundRandomVariableAtoms(info.predicates.get("Friends"))); mpe.inference(); // There are multiple optimal configuration to the first rou...
2129779_2
class PersonController { @RequestMapping(method=RequestMethod.GET,value="edit") public ModelAndView editPerson(@RequestParam(value="id",required=false) Long id) { logger.debug("Received request to edit person id : "+id); ModelAndView mav = new ModelAndView(); mav.setViewName("edit"); Person person ...
Long template = dataInitializer.getPeople().get(1); ModelAndView mav = personController.editPerson(template); assertNotNull(mav); assertEquals("edit", mav.getViewName()); Object object = mav.getModel().get("person"); assertTrue(Person.class.isAssignableFrom(object.getClass())); Person person = (Person) ob...
2139087_23
class MapUnitToPixelTransform { public Point<C2D> toPoint(Pixel pixel) { double x = extent.lowerLeft().getX() + mapUnitsPerPixelX * (pixel.x - this.pixelRange.getMinX()); double y = extent.upperRight().getY() - mapUnitsPerPixelY * (pixel.y - this.pixelRange.getMinY()); return point(extent....
Point<C2D> pnt = pixRangeBasedTransform.toPoint(Pixel.valueOf(100, 50)); assertTrue(equalsWithinTolerance(point(crs, c(10, 100)), pnt, Math.ulp(100d))); pnt = pixRangeBasedTransform.toPoint(Pixel.valueOf(100, 249)); assertTrue(equalsWithinTolerance(point(crs, c(10, 20.4)), pnt, Math.ul...
2144321_9
class PathUtils { public static String[] getMatchingPaths(final String[] includes, final String[] excludes, final String baseDir) { final DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(baseDir); if (includes != null && includes.length > 0) scanner.setIncludes(includes); if (exclud...
File dir = createDirectory(); File include = File.createTempFile("include", ".filetomatch", dir); File.createTempFile("neutral", ".notmatch", dir); File exclude = File.createTempFile("exlude", ".filetomatch", dir); String[] paths = PathUtils.getMatchingPaths( new String[] { "*.filetomatch" }, new Stri...
2153523_457
class CssResponseRewriter implements ResponseRewriter { public void rewrite(HttpRequest request, HttpResponseBuilder original) throws RewritingException { ContentRewriterFeature.Config config = rewriterFeatureFactory.get(request); if (!RewriterUtils.isCss(request, original)) { return; } String...
String content = IOUtils.toString(this.getClass().getClassLoader(). getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic.css")); String expected = IOUtils.toString(this.getClass().getClassLoader(). getResourceAsStream("org/apache/shindig/gadgets/rewrite/rewritebasic-expected.css"...
2155500_4
class CustomerSampler implements Sampler<Customer> { public Customer sample() throws Exception { Integer id = idSampler.sample(); Pair<String, String> name = nameSampler.sample(); Store store = storeSampler.sample(); Location location = locationSampler.sample(store); return new Customer(id, name, store, l...
SeedFactory factory = new SeedFactory(1234); List<Pair<String, String>> nameList = Lists.newArrayList(); nameList.add(Pair.of("Fred", "Fred")); nameList.add(Pair.of("Gary", "Gary")); nameList.add(Pair.of("George", "George")); nameList.add(Pair.of("Fiona", "Fiona")); List<Location> zipcodes = Arrays.asLi...
2157104_2
class FormatadorCodigo { public static String formata(String codigo) throws ErroCompilacao { Programa programa = Portugol.compilarParaAnalise(codigo); ASAPrograma asa = programa.getArvoreSintaticaAbstrata(); StringWriter stringWriter = new StringWriter(); try { Ge...
String codigo = "programa { " + " const inteiro _X = 0, _Y = 1, _MODELO = 2, _VELOCIDADE = 3, _COMBUSTIVEL = 4, _DANOS = 5" + " funcao inicio() {} " + "} "; ...
2158982_18
class DefaultQueryMetadata implements QueryMetadata, Cloneable { @Override public List<Expression<?>> getGroupBy() { return groupBy; } public DefaultQueryMetadata(); private static Predicate and(Predicate lhs, Predicate rhs); public DefaultQueryMetadata noValidate(); @Override pu...
metadata.addJoin(JoinType.DEFAULT, str); metadata.addGroupBy(str); assertEquals(Arrays.asList(str), metadata.getGroupBy()); } }
2173227_2
class ROADMRepository extends ResourceRepository { public void capabilityFactoryAdded(ICapabilityFactory capabilityFactory) { log.info("Adding factory: " + capabilityFactory.getType()); this.capabilityFactories.put(capabilityFactory.getType(), capabilityFactory); } public ROADMRepository(String resourceType);...
roadmRepository = new ROADMRepository("ROADMrepository"); roadmRepository.setResourceDescriptorRepository(new MockDescriptorRepository()); roadmRepository.capabilityFactoryAdded(new MockCapabilityFactory("factory1")); roadmRepository.capabilityFactoryAdded(new MockCapabilityFactory("factory2")); Assert.asse...
2173449_175
class ProductSubsetBuilder extends AbstractProductBuilder { public static Product createProductSubset(Product sourceProduct, ProductSubsetDef subsetDef, String name, String desc) throws IOException { return createProductSubset(sourceProduct, false, subsetDef, n...
final Product product2 = ProductSubsetBuilder.createProductSubset(product, null, "subset", ""); final Band band = product2.getBand(DUMMY_BAND1); final Band band2 = product2.getBand(DUMMY_BAND2); assertNotNull(band); assertNotNull(band2); final ImageInfo imageInfo = band....
2188276_354
class SqlGenerationPreferences { public void setSqlStatementSeparator(String sqlStatementSeparator) { this.sqlStatementSeparator = sqlStatementSeparator; } public boolean isQuoteConstraintNames(); public void setQuoteConstraintNames(boolean quoteConstraintNames); public boolean isQuoteColumnNames(); public v...
classUnderTest.setSqlStatementSeparator("\n"); assertEquals("\n", classUnderTest.getSqlStatementSeparator()); } }
2192780_20
class JOOX { public static Content content(final String value) { return new Content() { @Override public String content(Context context) { return value; } }; } public static Match(); public static Match(Object object); public st...
assertEquals("<customer id=\"0\"><age>0</age></customer>", $.content(new Customer()).content()); assertEquals($(new Customer()).toString(), $.content()); assertEquals("<customer id=\"0\"><customer id=\"0\"><age>0</age></customer></customer>", $.find("customer").content(ne...
2192825_0
class JSONWriter { public String write(Object object) throws JSONException { return this.write(object, null, null, false); } public String write(Object object, Collection<Pattern> excludeProperties, Collection<Pattern> includeProperties, boolean excludeNullProperties); ...
Bean bean1=new Bean(); bean1.setStringField("str"); bean1.setBooleanField(true); bean1.setCharField('s'); bean1.setDoubleField(10.1); bean1.setFloatField(1.5f); bean1.setIntField(10); bean1.setLongField(100); bean1.setEnumField(AnEnum.ValueA); ...
2197202_17
class SugarConfig { public static void clearCache() { fields.clear(); fields = new HashMap<>(); } public static void setFields(Class<?> clazz, List<Field> fieldz); public static List<Field> getFields(Class<?> clazz); } class SugarConfigTest { @Test public void testClearCache...
SugarConfig.clearCache(); Assert.assertEquals(true, SugarConfig.fields.isEmpty()); } }
2197427_2
class TumbleJ { public JSONObject postPhoto(String caption, String source, String link, String tags, String date) throws Exception { Map<String, Object> params = new HashMap<String, Object>(); if (caption != null && caption != "") params.put("caption", caption); params.put("source", source); if (link...
// response: {"meta":{"status":201,"msg":"Created"},"response":{"id":8868275314}} JSONObject response = tj.postPhoto("Smile", "http://30.media.tumblr.com/tumblr_lk5tyx3Zqo1qb67gho1_500.jpg", "Senyum itu indah dan menyenangkan, apalagi dari mojang geulis :)", "smile,senyum", null); assertNotNull(respon...
2209304_0
class JbossRemotingExporter extends RemoteExporter implements InitializingBean, BeanNameAware, SmartLifecycle { @Override public void stop(Runnable callback) { stop(); if (null != callback) { callback.run(); } } @Override public void setBeanName(String name); pr...
AnnotationConfigApplicationContext client = null, server = null; try { server = new AnnotationConfigApplicationContext(ServerConfiguration.class); client = new AnnotationConfigApplicationContext(ClientConfiguration.class); Crm clientBean = client.getBean(Crm.class);...
2213380_0
class ArvcRiskModel { public double calculateRisk(double baselineSurvival) { return calculateRisk(baselineSurvival, linearPredictor()); } ArvcRiskModel(int sex, int age, int hxSyncope, int hxNSVT, int pvcCount, int twiCount, int rvef); private double linearPredictor(); ...
ArvcRiskModel pt1 = new ArvcRiskModel(0, 48, 0, 0, 1, 4, 55 ); assertEquals(3.0, pt1.calculateRisk(ArvcRiskModel.year5), 0.0001); assertEquals(1.8, pt1.calculateRisk(ArvcRiskModel.year2), 0.0001); assertEquals(1.1, pt1.calculateRisk(ArvcRiskModel.year1), 0.0001); ...
2254694_7
class ConversionService { public Converter<?> getConverter(Class<?> type, Annotation[] annotations) { for (ConverterFactory factory : factories) { Converter<?> converter = factory.createConverter(type, annotations); if (converter != null) { return converter; ...
Converter<?> converter = conversion.getConverter(Integer.class, null); Map<String, String[]> data = new HashMap<String, String[]>(); data.put("val1", new String[]{"1"}); data.put("val2", new String[]{"2", "3", "4"}); //convert a single value Object val = converter.conve...
2259237_53
class AbstractSearchResultFactoryImpl implements SearchResultFactory { protected void populateServiceAlerts(Set<String> serviceAlertDescriptions, List<ServiceAlertBean> serviceAlertBeans) { populateServiceAlerts(serviceAlertDescriptions, serviceAlertBeans, true); } public AbstractSearchResultFactoryImpl();...
populateServiceAlerts(serviceAlertDescriptions, serviceAlertBeans, false); assertEquals(1, serviceAlertDescriptions.size()); String d = (String) serviceAlertDescriptions.toArray()[0]; assertTrue("line one\nline two".equals(d)); } }
2271327_0
class Shortcuts { public static LoadableDetachableModel loadedModel(final Object bean, final String loadMethod) { // assert that method exists ReflectUtils.getZeroArgMethod(bean.getClass(), loadMethod); return new LoadableDe...
final List<String> values = new ArrayList(); IModel model = Shortcuts.loadedModel(new TestBean(values), "load"); List<String> loaded = (List<String>) model.getObject(); Assert.assertTrue(loaded == values); Assert.assertTrue(loaded.size() == 1); l...
2272670_4
class ImageComparisonMatchers { @Factory public static Matcher<Object> isApproved() throws IOException { final StackTraceElement trace = StackUtils .getCallingTestMethodStackTraceElement(); final String methodName = trace.getMethodName(); final String className = getClas...
matcher = ImageComparisonMatchers.isApproved(); final BufferedImage image = ImageIO.read(getClass().getResource( "/net/avh4/util/imagecomparison/hamcrest/ImageComparisonMatchersTest.isApproved_withMatchingImage.png")); assertThat(matcher, not(doesNotMatch(image))); } }
2287347_24
class AggregationService { public List<AggregatedSegment> aggregateSegments(List<? extends ConnectableSegment> segments) { List<AggregatedSegment> aggregatedSegments = new ArrayList<AggregatedSegment>(); for (Iterator<? extends ConnectableSegment> it = segments.iterator(); it.hasNext();) { ConnectableSegment s...
List<AggregatedSegment> list = aggregationService.aggregateSegments(Collections.EMPTY_LIST); assertTrue(list.isEmpty()); } }
2293442_5
class UUIDUtils { public static String toOID(UUID uuid) { return toOID(uuid, OID_ROOT); } public static boolean isUUID(String uuidstr); public static String toOID(UUID uuid, String prefix); public static String toOIDFromUUIDString(String uuidstr); public static String toOIDFromUUIDStr...
UUID uuid = UUID.fromString("f81d4fae-7dec-11d0-a765-00a0c91e6bf6"); assertEquals("2.25.329800735698586629295641978511506172918", UUIDUtils.toOID(uuid)); } }
2296450_8
class AnnotationDataBuilder { static void populateDataIndexFromAnnotations(final AnnotationData data, final Class expectedAnnotationClass, final Method targetMethod) throws NoSuchMethodException, IllegalAccessException,...
final AnnotationData data = new AnnotationData(); Class expected = InvalidateAssignCache.class; Method targetMethod = null; // Not an update type. AnnotationDataBuilder.populateDataIndexFromAnnotations(data, expected, null); assertEquals(AnnotationData.DEFAULT_INTEGER, ...
2304277_106
class MetadataIdentificationUtils { public static String getMetadataInstance(final String metadataId) { if (isIdentifyingInstance(metadataId)) { return metadataId.substring(metadataId.indexOf(INSTANCE_DELIMITER) + 1); } return null; } private MetadataIdentificationUtils(); public static St...
assertEquals(INSTANCE_CLASS, MetadataIdentificationUtils.getMetadataInstance(INSTANCE_MID)); } }
2306348_0
class DefaultHelloService implements HelloService { public String sayHello( String who ) { return "Hello " + who; } int port; private Tomcat tomcat; } class TestDefaultHelloService { int port; private Tomcat tomcat; @Test public void testSayHello() {
HelloService service = JAXRSClientFactory.create( "http://localhost:" + port + "/" + getRestServicesPath() + "/testServices/", HelloService.class ); String who = "foo"; assertEquals( "Hello "+who, service.sayHello( who ) ); } }
2306900_3
class PropertiesBasedDatastore implements GatewayDatastore { @Override public List<String> getAddressesForApplication(String jid) { return delegateStore.getAddressesForApplication(jid); } public PropertiesBasedDatastore(final Resource properties); public PropertiesBasedDatastore(final Resource properties, i...
clearCurrentTempFile(); tempFile = File.createTempFile("test", ".properties"); tempFile.deleteOnExit(); String newMappings = ".*usera.*=usera@localhost\n" + ".*usera.*=usera@localhost\n" + ".*usera.*=usera@localhost\n" + " \n"; // erase exi...
2311431_0
class Vertex { public final int orientation(Vertex a, Vertex b, Vertex c) { double result = Geometry.leftOfPlane(a.x, a.y, a.z, b.x, b.y, b.z, c.x, c.y, c.z, x, y, z); if (result > 0.0) { return 1; } else if (result < 0.0) { ...
Vertex[] fourCorners = Tetrahedralization.getFourCorners(); assertEquals(1, fourCorners[3].orientation(fourCorners[0], fourCorners[1], fourCorners[2])); assertEquals(-1, fourCorners[3].orientati...
2316136_86
class CreateMeasure extends AnnotationType { public AggregationType getAggregateType() { return aggregateType; } public String getName(); public void setName( String name ); public void setAggregateType( AggregationType aggregateType ); public String getFormatString(); public void setFormatString( S...
CreateMeasure createMeasure = new CreateMeasure(); assertEquals( AggregationType.SUM, createMeasure.getAggregateType() ); } }
2316191_151
class DSWDatasourceServiceImpl implements IDSWDatasourceService { public SerializedResultSet doPreview( String connectionName, String query, String previewLimit ) throws DatasourceServiceException { if ( !hasDataAccessPermission() ) { logger.error( Messages.getErrorString( "DatasourceServiceImpl.ERROR_...
doReturn( true ).when( dswService ).hasDataAccessPermission(); SerializedResultSet result = dswService.doPreview( CONNECTION_NAME, VALID_QUERY, PREVIEW_LIMIT ); try { verify( dswService ).executeQuery( "[connection &#25509;&#32154; &lt;;&gt;!@#$%^&amp;*()_-=+.,]", VALID_QUERY, PREVIEW_LIMIT );...
2316200_293
class UsersVm { public void closeChangePasswordDialog() { zkHelper.findComponent(CHANGE_PASSWORD_DIALOG).detach(); } public UsersVm(@Nonnull UserService userService); @Init public void init(@ContextParam(ContextType.VIEW) Component component); @VisibleForTesting void init(Component compo...
Component mockComponent = mock(Component.class); when(zkHelper.findComponent(CHANGE_PASSWORD_DIALOG)).thenReturn(mockComponent); usersVm.closeChangePasswordDialog(); verify(mockComponent).detach(); } }
2316202_113
class UserDataCacheService { public Integer getNewPmCountFor(String username) { Element cacheElementForUser = userDataCache.get(username); if (cacheElementForUser == null) { return null; } return (Integer) cacheElementForUser.getValue(); } public UserDataCacheS...
when(cache.get(USERNAME)).thenReturn(new Element(USERNAME, 2)); Integer count = userDataCacheService.getNewPmCountFor(USERNAME); assertEquals(count.intValue(), 2); verify(cache).get(USERNAME); } }
2335594_25
class ExceptionWrapper { public CheckStylePluginException wrap(@Nullable final String message, @NotNull final Throwable error) { final Throwable root = rootOrCheckStyleException(error); final String exMessage = ofNullable(message).orElseGet(root::getMessage); if (isParseException(root)) { ...
assertThat( new ExceptionWrapper() .wrap(null, new CheckstyleException("aTestException", new IllegalStateException("aTestException"))), is(instanceOf(CheckStylePluginException.class))); } }
2341027_0
class IntegerParamEncoder implements IParamEncoder { @Override public int readTo(DecoderAdapter dest, String encoded, MessageParamField field ) { int decodedValue = IntegerEncoded.parseInt(encoded, radix); dest.putInt(field.dbFieldName, decodedValue); return 1; } public Integ...
int i = 0; for (char c : IntegerEncoded.ALPHABET) { String str = String.valueOf(c); MapEncoderAdpater dest = new MapEncoderAdpater(); service.readTo(dest, str, MessageParamField.LOC_ALTITUDE ); int decoded = dest.getInt(MessageParamField.LOC_ALTITUDE ); ...
2349728_0
class ConvertUtils { public static Repository eventRepoToRepo(GitHubEvent.RepoIdentifier repo) { String[] ref = repo.repoWithUserName().split("/"); return InfoUtils.createRepoFromData(ref[0], ref[1]); } private static final String REPO_NAME_FIRST_PART; private static final String REPO_NAME_SECOND_PART; priva...
ConvertUtils.eventRepoToRepo(event.repo()); assertThat(event.repo().repoWithUserName(), equalTo(REPO_NAME)); } }
2357859_654
class SetAccessStatusFilter implements IndexDocumentFilter { @Override public void filter(DocumentIndexingPackage dip) throws IndexingException { log.debug("Performing set access status filter on {}", dip.getPid()); dip.getDocument().setStatus(determineAccessStatus(dip)); } public void...
addInheritedRoleAssignment(pid, PUBLIC_PRINC, UserRole.canViewMetadata); addInheritedRoleAssignment(pid, AUTHENTICATED_PRINC, UserRole.canViewMetadata); when(inheritedAclFactory.getEmbargoUntil(pid)).thenReturn(getNextYear()); filter.filter(dip); verify(idb).setStatus(listCapt...
2364987_147
class DefaultExecutor implements Executor { @Override public void orFallBackTo(Runnable defaultClosure) { defaultClosure.run(); } @Override public Executor perform(Closure closure); } class DefaultExecutorTest { @Test public void performsDefaultAction() throws Exception {
Runnable action = mock(Runnable.class); new DefaultExecutor().orFallBackTo(action); verify(action).run(); } }
2383782_393
class InputLogicParser { public String parse(Element root) { return parseWithName(root, null); } @SuppressWarnings("unchecked") public String parseWithName(Element root, String name); public String parse(Element root, String opt, String min, String wait); @SuppressWarnings("unchecked") pr...
//@formatter:off String xml = "<input-logic>" + "<and>" + "<combine>" + "<data-in dataset=\"A\" />" + "<data-in dataset=\"B\" />"+ "</combine>" ...
2394379_79
class DefaultQueryMatcher implements QueryMatcher { @Override public boolean matches(Document document, Document query) { for (String key : query.keySet()) { Object queryValue = query.get(key); validateQueryValue(queryValue, key); if (!checkMatch(queryValue, key, doc...
Document query = map("a", size(1)); assertThat(matcher.matches(json(""), query)).isFalse(); assertThat(matcher.matches(json("a: 'x'"), query)).isFalse(); assertThat(matcher.matches(map("a", list()), query)).isFalse(); assertThat(matcher.matches(map("a", list(1)), query)).isTrue...
2397476_0
class DateTimeParameter { public DateTime getValue() { return value; } public DateTimeParameter(final String value); private static final DateTimeFormatter ISO_DATE; } class TestDateTimeParameter { private static final DateTimeFormatter ISO_DATE; @Test(groups = "fast") pu...
System.setProperty("user.timezone", "UTC"); // Compare Epoch Assert.assertEquals(new DateTimeParameter(null).getValue().toDateTime(DateTimeZone.UTC).getMillis() / 1000, new DateTime(DateTimeZone.UTC).getMillis() / 1000); Assert.assertEquals(new DateTimeParameter("2012").getValue().getC...
2403733_3
class PromoteKeyOperation extends BaseOperation { public PromoteKeyResult execute(long masterKeyId, byte[] cardAid, long[] subKeyIds) { OperationLog log = new OperationLog(); log.add(LogType.MSG_PR, 0); // Perform actual type change UncachedKeyRing promotedRing; { ...
PromoteKeyOperation op = new PromoteKeyOperation(RuntimeEnvironment.application, new ProviderHelper(RuntimeEnvironment.application), null, null); byte[] aid = Hex.decode("D2760001240102000000012345670000"); // only promote the first, rest stays dummy long keyId = Keyrin...
2408915_45
class StaticResource { public int getResourceId(Context context) { int resourceId = context.getResources().getIdentifier( resourceName, resourceType, hasResourcePackage() ? resourcePackage : context.getPackageName()); checkResource(resourceId); return resourceId; } StaticResource(String value); pri...
MockResourcesBuilder aContextOfResources = aContextOfResources(); int expectedResourceId = aContextOfResources.declareResource(RESOURCE_NAME, RESOURCE_TYPE, RESOURCE_PACKAGE); StaticResource resource = new StaticResource(resourceValue(RESOURCE_NAME, RESOURCE_TYPE, RESOURCE_PACKAGE)); assertThat(resource.getRe...
2416378_14
class ASTUtils { public boolean inherits(ASTType astType, ASTType inheritable) { if (astType == null) { return false; } if(inheritable == null || inheritable.equals(OBJECT_TYPE)){ return true; } if (astType.equals(inheritable)) { return tr...
assertTrue(astUtils.inherits(a, null)); assertFalse(astUtils.inherits(null, null)); } }
2422006_24
class Hook { public void shutdown() { keepRunning = false; thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { logger.error("Error shutting down thread with hook", e); } } Hook(Thread thread); public boolean keepRunning(); private Hook instance; private Thread thread;...
assertTrue(instance.keepRunning()); instance.shutdown(); assertFalse(instance.keepRunning()); } }
2432524_5
class XMLUtils { public static String prettyPrint( String xml ) { return prettyPrint( xml, INDENT_NUMBER ); } public static String prettyPrint( String xml, int indent ); public static AttributesImpl toAttributesImpl( Attributes attributes ); private static final String LINE_SEPARATOR;...
String xml = "<a><b>c</b></a>"; System.out.println( prettyPrint( xml ) ); long start = System.currentTimeMillis(); char[] padding = new char[4]; Arrays.fill( padding, ' ' ); assertEquals( "<a>" + LINE_SEPARATOR + String.copyValueOf( padding ) + "<b>c</b>" + LINE_SEPARAT...
2434719_21
class CharacterSet extends ArrayList<CharacterRange> { public boolean contains(int charCode) { boolean found = false; for (int i = 0; !found && i < size(); i++) { CharacterRange range = get(i); if (range.characterSet != null) { // Version 1 CGT ...
// version 1 format (Strings) CharacterSet set = new CharacterSet(); set.add(new CharacterRange("ABC")); set.add(new CharacterRange("XyZ")); assertTrue("A", set.contains("A".codePointAt(0))); assertTrue("B", set.contains("B".codePointAt(0))); assertTrue("C", set.c...
2438993_1
class WebApplicationMetaData { public String getContextPath() { return this.contextPath; } public boolean forceDefaultContext(); public boolean forceDefaultStaticPathPrefix(); public void addHost(String host); public void addHosts(List<String> hosts); public List<String> getHosts()...
assertEquals(null, new WebApplicationMetaData().getContextPath()); } }
2449032_110
class Value { Value not () { throw newOperandException ("not"); } abstract String getType(); Value or(Value v); Value and(Value v); abstract Value equal(Value v); abstract Value unequal(Value v); Value lessThan(Value v); Value lessOrEqual(Value v); Value greaterTha...
try { mValue.not (); fail ("no exception"); } catch (ExecutionException ee) { // ok } } }
2466190_0
class Util { public static File getEncryptedFilename(File file) { String filename = file.getName(); return filename.endsWith(ENCRYPTED_FILENAME_SUFFIX) ? file : new File(file.getParent(), filename + ENCRYPTED_FILENAME_SUFFIX); } public static int getStatusBarHeight(Window window); public static int pixelsToDi...
File file = new File("/data/user/0/test.bin"); File encryptedFile = Util.getEncryptedFilename(file); assertEquals(new File("/data/user/0/test.bin.encrypted"), encryptedFile); File decryptedFile = Util.getUnencryptedFilename(encryptedFile); assertEquals(file, decryptedFile); } }
2470704_0
class LevenshteinDistanceMatcher extends AbstractMatcher { protected float normalize(float score, int longestString){ return 1f - (score / longestString); } @Override protected float doMatchScore(String matchText, String cadidate); private LevenshteinDistanceMatcher levenshteinDistanceMatcher; } class Levens...
float score = this.levenshteinDistanceMatcher.normalize(5, 20); assertEquals(0.75f,score, 0f); } }
2474070_1
class ExperienceParser { public static Gson createGson(Context context) { if (gson == null) { GsonBuilder builder = new GsonBuilder(); if (context == null || Feature.get(context, R.bool.feature_load_old_experiences).isEnabled()) { builder.registerTypeAdapterFactory(new ExperienceTypeAdapterFactor())...
Experience experience = TestUtils.loadExperience("test_old"); Assert.assertTrue(experience.getName().equals("Test")); final Gson gson = ExperienceParser.createGson(null); System.out.println(gson.toJson(experience)); //Experience experience = new Experience(); //experience.setChecksumModulo(3); // TODO ...
2478263_260
class CypherProxyController { @RequestMapping(value = "/findExternalUrlForStudy/{studyTitle}", method = RequestMethod.GET, produces = "application/json") @ResponseBody public String findExternalLinkForStudyWithTitle(HttpServletRequest request, @PathVariable("studyTitle") String taxonName) throws IOExceptio...
String externalLink = new CypherProxyController().findExternalLinkForStudyWithTitle(null, "None existing study"); assertThat(externalLink, is("{}")); } }
2479886_26
class CcsdsPacket { @Override public String toString() { StringBuffer sb = new StringBuffer(); StringBuffer text = new StringBuffer(); byte c; int len = bb.limit(); int lengthRoundedUpToNextMultipleOf16 = (int) Math.ceil(len / 16.0) * 16; sb.append("apid: " + get...
CcsdsPacket ccsdsPacket = new CcsdsPacket(ByteBuffer.wrap(testPacketOf32Bytes)); // Initialize TimeEncoding to be able to call CcsdsPacket.toString() TimeEncoding.setUp(); String packetString = ccsdsPacket.toString(); Assert.assertEquals("apid: 906\n" + "packetId...
2485432_0
class IPNetwork extends PGcidr implements Serializable, Cloneable, Comparable<IPNetwork> { public byte[] getNetmaskAddress() { return netmaskAddress; } public IPNetwork(); public IPNetwork(PGcidr net); public IPNetwork(String net); @Override public void setValue(String v); publ...
IPNetwork net = new IPNetwork(); Assert.assertEquals("Empty IPNetwork must not have a network address", null, net.getNetmaskAddress()); } }
2488113_3
class DefaultHateoasContext implements HateoasContext { @Override public LinkableInfo getLinkableInfo(String link) { LinkableInfo linkableInfo = linkableMapping.get(link); Validate.notNull(linkableInfo, "Invalid link: " + link); return linkableInfo; } @Override public void map...
LinkableInfo result = tested.getLinkableInfo("test.dummy.sneaky.subpath"); assertEquals("test.dummy.sneaky.subpath", result.getId()); assertEquals("GET", result.getHttpMethod()); assertEquals("/dummy/subpath", result.getMethodPath()); } }
2488848_139
class MiniRepository implements Repository { public boolean exists(@Nullable ID subject, @Nullable UID predicate, @Nullable NODE object, @Nullable UID context) { return findStatements(subject, predicate, object, context, false).hasNext(); } public MiniRepository(); public MiniRepository(int ...
assertTrue(repository.exists(null, null, null, null)); repository.remove(null, null, null, null); assertFalse(repository.exists(null, null, null, null)); } }
2491679_4
class PisPasepValidator implements ConstraintValidator<PisPasep, String> { @Override public boolean isValid(String pis, final ConstraintValidatorContext context) { boolean result = false; if ( pis == null || "".equals(pis) ) { result = true; } else { result = PISPASEP.isValido(pis); } return result; ...
PisPasepValidator validator = new PisPasepValidator(); PowerMock.mockStatic(PISPASEP.class); EasyMock.expect(PISPASEP.isValido(EasyMock.anyObject(String.class))).andReturn(true); PowerMock.replay(PISPASEP.class); // validator.isValid() must use the return of PISPASEP.isValido(). // PISPASEP value doesn't ...
2497245_83
class SizeValue { @Nonnull public static SizeValue percent(final int percentage) { return new SizeValue(percentage, SizeValueType.Percent); } public SizeValue(@Nonnull final SizeValueType type); public SizeValue(final int value, @Nonnull final SizeValueType type); public SizeValue(@Nonnull final Si...
SizeValue value = SizeValue.percent(10); assertEquals(100, value.getValueAsInt(1000.f)); assertEquals(10, value.getValueAsInt(100.f)); assertEquals(100.f, value.getValue(1000.f), 1.0e-7); assertEquals(10.f, value.getValue(100.f), 1.0e-7); assertTrue(value.hasValue()); assertTrue(value.isPerc...
2499324_6
class PcapReader implements Iterable<Packet> { protected LinkType getLinkType(long linkTypeVal) { switch ((int)linkTypeVal) { case 0: return LinkType.NULL; case 1: return LinkType.EN10MB; case 101: return LinkType.RAW; case 108: return LinkType.LOOP; case 113: return LinkType.LIN...
assertEquals(PcapReader.LinkType.RAW, reader.getLinkType(101)); } }
2501197_4
class Validation { public <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyPath, Class<?>... groups) { Set<ConstraintViolation<T>> violations = new HashSet<ConstraintViolation<T>>(); try { int currentIndex = -1; String currentPropertyPath; ...
RootBean rootBean = new RootBean(); NestedBean nestedBean = new NestedBean(); rootBean.setNestedBean(nestedBean); Set<ConstraintViolation<RootBean>> violations = validation.validateProperty(rootBean, "nestedBean.property"); Assert.assertTrue(violations.size() == 1); } }
2505794_638
class OrPredicate implements Predicate<T> { @Override public boolean evaluate(final T instance) { return any(predicates, new UnaryPredicate<UnaryPredicate<? super T>>() { @Override public boolean evaluate(UnaryPredicate<? super T> predicate) { return predicate.evaluate(instance)...
// Given OrPredicate<Object> orPredicate = new OrPredicate<Object>(Literals.<UnaryPredicate<? super Object>>iterable()); // When boolean result = orPredicate.evaluate(new Object()); // Then assertThat(result, is(false)); } }
2510313_7
class DefaultStatementBuilder implements StatementBuilder, OngoingUpdate, OngoingReadingWithWhere, OngoingReadingWithoutWhere, OngoingMatchAndUpdate { @Override public OngoingReadingWithoutWhere match(PatternElement... pattern) { return this.match(false, pattern); } DefaultStatementBuilder(); DefaultStat...
DefaultStatementBuilder builder = new DefaultStatementBuilder(); assertThatIllegalArgumentException().isThrownBy(() -> builder.match((PatternElement[]) null)) .withMessage("Patterns to match are required."); assertThatIllegalArgumentException().isThrownBy(() -> builder.match()) .withMessage("At least one p...
2516145_2
class Configurator { public String[] asArray(String value){ return value.split(","); } @PostConstruct public void initialize(); @Produces public int getInteger(InjectionPoint ip); @Produces public boolean getBoolean(InjectionPoint ip); @Produces public String getString(InjectionPoint ip...
String[] expected = {"hey","joe"}; String[] actual = cut.asArray("hey,joe"); assertArrayEquals(expected, actual); } }
2521501_29
class SC extends Canvas { public void confirm(String message, BooleanCallback callback) { confirm(null, message, callback); } public SC(); SC(ServerSideProxyFactory serverSideProxyFactory); public void say(String message); public void say(String message, BooleanCallback bcb); public void say(String title...
final String message = "message"; sc.confirm(message, null); verify(serverSideProxy).call(eq("confirm"), anyInt(), eq(message), anyString()); } }
2524488_375
class ScannerOptions implements ScannerBase { @Override public synchronized void fetchColumn(Text colFam, Text colQual) { checkArgument(colFam != null, "colFam is null"); checkArgument(colQual != null, "colQual is null"); Column c = new Column(TextUtil.getBytes(colFam), TextUtil.getBytes(colQual), null...
try (ScannerOptions options = new ScannerOptions()) { assertEquals(0, options.getFetchedColumns().size()); IteratorSetting.Column col = new IteratorSetting.Column(new Text("family"), new Text("qualifier")); options.fetchColumn(col); SortedSet<Column> fetchedColumns = options.getFet...
2536041_2
class DistCache { public static void addJarDirToDistributedCache(Configuration conf, File jarDirectory) throws IOException { if (!jarDirectory.exists() || !jarDirectory.isDirectory()) { throw new IOException("Jar directory: " + jarDirectory.getCanonicalPath() + " does not " + "exist or is not...
DistCache.addJarDirToDistributedCache(testConf, testFolder.getRoot().getCanonicalPath()); // Throw the added jar paths in a set to detect duplicates. String[] splitJarPaths = StringUtils.split(testConf.get("tmpjars"), ","); Set<String> addedJarPaths = new HashSet<String>(); for (String path: splitJa...
2544900_7
class JsspPhenotypeEvaluator implements IPhenotypeEvaluator { public double[] evaluateSchedule(Integer[] jobArray) { _schedule = null; return evaluateSchedule(jobArray, false); } public JsspPhenotypeEvaluator(JobsDefinition jobsDefinition); @Override public double[] evaluate(Obje...
JsspPhenotypeEvaluator evaluator = new JsspPhenotypeEvaluator(_jobsDefinition); Integer[] jobArray = new Integer[] {1,1,1,2,2,2}; double[] objVal = evaluator.evaluateSchedule(jobArray); assertEquals (12, (int)objVal[0]); jobArray = new Integer[] {1,2,1,2,1,2}; ...
2550825_37
class AkkaRouterConfigHelper { public Map<String, String> getRouterConfigInformation(RouterConfig routerConfig) { Map<String, String> result = new HashMap<String, String>(); result.put("Router", routerConfig.getClass().getSimpleName()); String routerDispatcher = routerConfig.routerDispatche...
Map<String, String> result = tested.getRouterConfigInformation(new TestCustomRouterConfig()); Map<String, String> expected = createdExpected(); assertEquals("extracted values", expected, result); } }
2562751_4
class Decoder { static byte[] convertBoolArrayToByteArray(boolean[] boolArr) { byte[] byteArr = new byte[(boolArr.length + 7) / 8]; for (int i = 0; i < byteArr.length; i++) { byteArr[i] = readByte(boolArr, 8 * i); } return byteArr; } public DecoderResult decode(AztecDetectorResult detector...
boolean[] bool0 = {}; boolean[] bool1 = { true }; boolean[] bool7 = { true, false, true, false, true, false, true }; boolean[] bool8 = { true, false, true, false, true, false, true, false }; boolean[] bool9 = { true, false, true, false, true, false, true, false, true }; b...
2572668_0
class RemoteUserTokenUserManager extends AbstractReadOnlyUserManager { @Override public Set<User> searchUsers(UserSearchCriteria criteria) { final Set<User> users = this.listUsers(); final Set<User> filteredUsers = this.filterListInMemeory(users, criteria); logger.debug("filteredUsers({...
UserManager userLocator = this.lookup(UserManager.class, RemoteUserTokenAuthenticatingRealm.REALM_NAME); Set<User> result = userLocator.searchUsers(new UserSearchCriteria("joh")); Assert.assertEquals(1, result.size()); // your test could be a bit more robust Assert.assertEquals(...
2576064_42
class DataWrapperFactory { public static Map<String, List<CtxModelObject>> sortByObfuscability(List<CtxModelObject> ctxDataList) { if (null == ctxDataList || ctxDataList.size() <= 0) { // LOG.error("Can't sort null values"); return null; } String notObfuscableType = "NOT_OBFUCSABLE"; DataTypeUtils dat...
// Null or empty Map<String, List<CtxModelObject>> ctxDataListRetrieved1 = DataWrapperFactory.sortByObfuscability(null); Map<String, List<CtxModelObject>> ctxDataListRetrieved2 = DataWrapperFactory.sortByObfuscability(new ArrayList<CtxModelObject>()); assertNull("Retrieved data list should be null", ctxDataList...
2580771_3
class DirectMemoryServlet extends HttpServlet { @Override protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException { // url format = /cache/key so get the key from path String path = req.getPathInfo(); String servletPath =...
MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader( "Accept", MediaType.APPLICATION_JSON ); request.setServletPath( "cache" ); request.setPathInfo( "/foo" ); MockHttpServletResponse response = new MockHttpServletResponse(); directMemoryS...
2588654_1
class PeakPlugin implements PluginWithDependencies { protected boolean updatePeakForChannel(Network network, Channel channel) { try { int storedCount = getCount(network, channel); int numberCurrentlyOnChannel = channel.getNicks().size(); if (storedCount < numberCurrentl...
testChannel.addNick(testNick1); assertTrue(peakPlugin.updatePeakForChannel(network, testChannel)); assertFalse(peakPlugin.updatePeakForChannel(network, testChannel)); testChannel.addNick(testNick2); assertTrue(peakPlugin.updatePeakForChannel(network, testChannel)); asser...
2611961_0
class RegistrationUtils { public static String estimateAge(String birthdate) throws ParseException { Date date = RegistrationUtils.parseDate(birthdate); return PatientUtils.estimateAge(date); } public static Date parseDate(String date); public static String formatDate(Date date); public static PersonName get...
Assert.assertEquals( "~0 D ", RegistrationUtils.estimateAge( date ) ); } }
2613332_20
class DashBoardPage extends SharePage implements Dashboard { @SuppressWarnings("unchecked") @Override public DashBoardPage render(RenderTime timer) { basicRender(timer); // We don't know if the dashlets will appear so do the basic rendering try { getDashlet("...
//Were already logged in from the previous test. drone.refresh(); DashBoardPage dashBoard = drone.getCurrentPage().render(); Assert.assertNotNull(dashBoard); } }
2614085_60
class HtmlPortletPreferenceSearchContentExtractor implements ISearchContentExtractor { @Override public boolean appliesTo(IPortletDefinition portlet) { final boolean portletMatch = portletName.equalsIgnoreCase(portlet.getPortletDescriptorKey().getPortletName()); final boolean we...
final IPortletDescriptorKey portletDescriptorKey = mock(IPortletDescriptorKey.class); when(portletDescriptorKey.getPortletName()).thenAnswer(invocation -> NOT_A_MATCH); when(portletDescriptorKey.getWebAppName()).thenAnswer(invocation -> NOT_A_MATCH); final IPortletPreference portletPre...
2618757_4
class SpringPluggableSchemas implements Schemas, Namespaces { public Map<String, Schema> getNamedMappings() { ensureInit(); return nameToSchemaMappings; } public SpringPluggableSchemas(); public SpringPluggableSchemas(ClassLoader classLoader); public SpringPluggableSchemas(Resou...
Map<String, Schema> names = sps.getNamedMappings(); Resource resource; Schema beansSchema = names.get("www.springframework.org/schema/beans/spring-beans-2.5.xsd"); resource = assertSourceInfoAndGetResource(beansSchema, SpringPluggableSchemaSourceInfo.class); assertResource("org/...
2622978_77
class JpaCacheEvictionHandler { public final void onAfterTestMethod(@Observes(precedence = 45) AfterPersistenceTest event) { executeCacheEviction(event, TestExecutionPhase.AFTER); } public JpaCacheEvictionHandler(); public JpaCacheEvictionHandler(Instance<Context> ctx, JpaCacheEvictionConfig...
jpaCacheEvictionHandler.onAfterTestMethod(createAfterEvent(new StubTestCaseWithModifiedAnnotation())); assertThat(tmpLookupName).isEqualTo("customEntityManager"); assertThat(tmpCacheEvicted).isTrue(); } }
2624179_0
class ReplicantRuntime { @Action void registerConnector( @Nonnull final Connector connector ) { if ( Replicant.shouldCheckInvariants() ) { invariant( () -> _connectors.stream() .noneMatch( e -> e.getConnector().getSchema().getId() == connector.getSchema().getId() ), ...
final ReplicantRuntime runtime1 = Replicant.context().getRuntime(); final SystemSchema schema = newSchema(); // This connector will self-register to runtime1 final Connector connector1 = createConnector( schema ); final IllegalStateException exception = expectThrows( IllegalStateException.c...
2626654_7
class HDIVUtil { public static String stripAndFillSessionData(final String url, final UrlDataImpl urldata) { final int pos = url.indexOf(';'); if (pos != -1) { final char[] data = url.toCharArray(); int sessionStart; if ((sessionStart = indexOf(data, jsessionLower, pos)) != -1 || (sessionStart = indexOf(...
final String url = "/testAction.do;jsessionid=67CFB560B6EC2677D51814A2A2B16B24"; final UrlDataImpl data = new UrlDataImpl(url, Method.GET); Assert.assertEquals("/testAction.do", HDIVUtil.stripAndFillSessionData(url, data)); Assert.assertEquals("jsessionid=67CFB560B6EC2677D51814A2A2B16B24", data.getjSessionId()...
2647335_4
class BundleNameTemplate { public String forGroup(String groupName, ResourceHtmlTag tag) { return namePattern .replace("@groupName@", groupName) .replace("@extension@", tag.getExtension()); } public BundleNameTemplate(String namePattern); @Override public bool...
String p = "@groupName@-345\\.@extension@"; BundleNameTemplate template = new BundleNameTemplate(p); assertEquals("test-345\\.css", template.forGroup("test", ResourceHtmlTag.CSS)); assertEquals("test-345\\.js", template.forGroup("test", ResourceHtmlTag.JS)); } }
2651891_0
class StringRepository { public String get() { if (stringList.isEmpty()) { return null; } else { String result = stringList.remove(0); return result; } } public StringRepository(List<String> stringList); public void put(String data); @...
StringRepository instance = new StringRepository(stringList); Story story = Story.create(new Scenario() { { expect(stringList).isEmpty(); willReturn(true); } }); story.begin(); assertNull(instance.get()); story.end()...
2656737_4
class CDABuilder { public String createConsentCDA(Patient patient, PatientConsentPolicy policy, DocumentEntry documentEntry) { // Basic checks if (patient == null) throw new IllegalArgumentException("Patient cannot be null."); if (policy == null) throw new IllegalArgumentException("policy cannot be nu...
Patient patient = createPatient(); DocumentEntry de = documentEntryBuilder.createDocumentEntry( new CoalaAuthor("testName", "testName", "testName"), patient, PatientConsentPolicy.ONE, new Date(), new Date()); String cdaResult = cdaBuilder.createConsentCDA(patient, PatientConsentPolicy.ONE, de); ass...
2666578_179
class StringAuthentication implements Authentication { @Override public int hashCode() { int hash = 17; hash = hash * 31 + key.hashCode(); hash = hash * 31 + ( ( value != null ) ? value.hashCode() : 0 ); return hash; } public StringAuthentication( String key, Strin...
Authentication auth1 = new StringAuthentication( "key", "value" ); Authentication auth2 = new StringAuthentication( "key", "value" ); assertEquals( auth1.hashCode(), auth2.hashCode() ); } }
2675355_2
class JavaParserJsonDeserializer { public Node deserializeObject(JsonReader reader) { Log.info("Deserializing JSON to Node."); JsonObject jsonObject = reader.readObject(); return deserializeObject(jsonObject); } private Node deserializeObject(JsonObject nodeJson); private NodeL...
Type type = parseType("Blub<>"); String serialized = serialize(type, false); Node deserialized = deserializer.deserializeObject(Json.createReader(new StringReader(serialized))); assertEqualsStringIgnoringEol("Blub<>", deserialized.toString()); assertEquals(type.hashCode(), dese...
2675654_37
class Deps { public static DependencyAtom getMinimumVersion(DependencyAtom left, DependencyAtom right) { String leftVersion = left.getPropertyValue(); String rightVersion = right.getPropertyValue(); if ((leftVersion == null) || (rightVersion == null) || leftVersion.equals(rightVersion)) { ...
DependencyAtom left = DependencyAtom.parse("foo:foo:1.0", new AtomicReference<String>()); DependencyAtom right = DependencyAtom.parse("foo:foo:1.0", new AtomicReference<String>()); DependencyAtom result = Deps.getMinimumVersion(left, right); assertNull(result); left = Dependenc...
2680621_5
class FormEntryContext { public Widget getWidgetByFieldName(String fieldName) { for (Map.Entry<Widget, String> e : fieldNames.entrySet()) { if (e.getValue().equals(fieldName)) return e.getKey(); } return null; } public FormEntryContext(Mode mode); public Mode getMode(); public String registerWidge...
DropdownWidget widget = new DropdownWidget(); context.registerWidget(widget); String fieldName = context.getFieldName(widget); Widget w = context.getWidgetByFieldName(fieldName); assertNotNull(w); } }
2685841_1710
class AdditionalDocumentsController implements PatientDataController<Attachment> { @Override public void writeJSON(Patient patient, JSONObject json) { writeJSON(patient, json, null); } @Override public PatientData<Attachment> load(Patient patient); @Override public void save(@Nonnull f...
JSONObject json = new JSONObject(); this.mocker.getComponentUnderTest().writeJSON(this.patient, json, Collections.singletonList(CONTROLLER_NAME)); Assert.assertTrue(json.has(DATA_NAME)); JSONArray result = json.getJSONArray(DATA_NAME); Assert.assertEquals(2, result.length()); ...
2689039_50
class SimpleVehicleMessage extends NamedVehicleMessage { @Override public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeValue(getValue()); } public SimpleVehicleMessage(Long timestamp, String name, Object value); public SimpleVehicleMessage...
Parcel parcel = Parcel.obtain(); message.writeToParcel(parcel, 0); // Reset parcel for reading parcel.setDataPosition(0); VehicleMessage createdFromParcel = VehicleMessage.CREATOR.createFromParcel(parcel); assertThat(createdFromParcel, instanceOf(SimpleV...
2694049_1
class KerberizedSshServer { SshServer getServer() { return server; } public KerberizedSshServer(int port, String keytab, String principalName); public void start(); public static void main(String args[]); } class KerberizedSshServerTest { @Test public void testServerWithPrincipal() throws UnknownHostExc...
KerberizedSshServer server = new KerberizedSshServer(1235, "aFile", "host/localhost"); SshServer sshServer = server.getServer(); GSSAuthenticator authenticator = sshServer.getGSSAuthenticator(); assertNotNull(authenticator); String principal = (String) getField(authenticator, "servicePrincipalName"); ...
2698192_2
class Throwables2 { public static String explain(final Throwable throwable) { checkNotNull(throwable); StringBuilder buff = new StringBuilder(); explain(buff, throwable); Throwable cause = throwable; while ((cause = cause.getCause()) != null) { buff.append(", caused by: "); explain(...
String msg = Throwables2.explain(new RuntimeException("foo")); log(msg); assertThat(msg, is("java.lang.RuntimeException: foo")); } }
2708082_94
class DecisionPath extends DecisionMaker implements Serializable { public void pushDecision(Decision decision) { int p = last.get(); decision.setPosition(p); if(decisions.size() == p){ decisions.add(decision); }else if(decisions.size() == p + 1) { decisions.s...
Assert.assertEquals(dp.size(), 1); Assert.assertEquals(dp.last.get(), 1); IntDecision d1 = dp.makeIntDecision(vars[0], DecisionOperatorFactory.makeIntEq(), 4); dp.pushDecision(d1); Assert.assertEquals(d1.getPosition(), 1); Assert.assertEquals(dp.size(), 2); Assert...
2708789_0
class HelloWorldTasklet implements Tasklet { @Override public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception { // why not using println? because it makes testing harder, *nix and // windows think different about ...
assertEquals(RepeatStatus.FINISHED, tasklet.execute(null, null)); // assert sysoutput assertEquals("Hello World!", outContent.toString()); } }
2710254_2
class YAMLUtils { public void loadSettings(String resourcePath, String defaultResourcePath, Object bean) { try { Map properties = loadSettings(resourcePath, defaultResourcePath); BeanUtils.populate(bean, properties); } catch (IllegalAccessException | InvocationTargetExceptio...
Map map = new HashMap(); new YAMLUtils().loadSettings("test.yml", "default-test.yml", map); Assert.assertNotNull(map); Assert.assertEquals(map.get("prop1"), 11); Assert.assertEquals(map.get("prop2"), "22"); Assert.assertEquals(map.get("prop3"), 3); } }
2719141_12
class FileManipulator { public boolean contentEquals( String src, String dest ) throws FileManipulatorException { FileObject srcFile = null; FileObject destFile = null; try { LOGGER.debug( "Comparing the content of {} and {}", src, dest ); srcFile...
assertEquals( true, fileManipulator.contentEquals( "http://localhost:" + port + "/repos/asf/incubator/kalumet/trunk/LICENSE", "http://localhost:" + port + "/repos/asf/incubator/kalumet/trunk/LICENSE" ) ); } }
2737689_92
class PYamlObject extends PAbstractObject { public final PJsonObject toJSON() { try { JSONObject json = new JSONObject(); for (String key: this.obj.keySet()) { Object opt = opt(key); if (opt instanceof PYamlObject) { opt = ((PYamlO...
Map<String, Object> map = new HashMap<>(); map.put("att1", 1); map.put("att2", new Object[]{1, 2}); Map<String, Object> embedded = new HashMap<>(); embedded.put("embeddedAtt1", true); Map<String, Object> embeddedEmbedded = new HashMap<>(); embeddedEmbedded.put("e...
2740148_425
class BilouCodec implements SequenceCodec<String> { @Override public boolean areOutcomesCompatible(String[] outcomes) { Set<String> start = new HashSet<>(); Set<String> cont = new HashSet<>(); Set<String> last = new HashSet<>(); Set<String> unit = new HashSet<>(); for (int i = 0; i < outcomes....
Assert.assertFalse(codec.areOutcomesCompatible(new String[] {B_START, B_CONTINUE})); Assert.assertFalse(codec.areOutcomesCompatible(new String[] {A_UNIT, B_START, B_CONTINUE})); Assert.assertFalse(codec.areOutcomesCompatible(new String[] {A_START, A_LAST, B_START, B_CONTINUE})); } }