id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
3468420_206
class CollisionPlaneRoadModel extends PlaneRoadModel { @Override public void addObjectAt(RoadUser obj, Point pos) { if (obj instanceof MovingRoadUser) { checkArgument(!isOccupied(pos), "Cannot add an object on an occupied position: %s.", pos); blockingRegistry.addAt((MovingRoadUser) obj, po...
boolean fail = false; model.addObjectAt(ru1, new Point(1, 1)); try { model.addObjectAt(ru2, new Point(1, 1)); } catch (final IllegalArgumentException e) { fail = true; assertThat(e.getMessage()) .contains("Cannot add an object on an occupied position:"); } assertThat(fa...
3471752_7
class HashUtils { @NotNull public static String computeSha256Hash(@NotNull final byte[] bytes) throws NoSuchAlgorithmException { return computeHash(bytes, "SHA-256"); } private HashUtils(); @NotNull public static String computeMd5Hash(final byte[] bytes); private static String byteTo...
try { Assert.assertEquals(EXPECTED_PHOTO_HASH_SHA256, HashUtils.computeSha256Hash(PHOTO_BYTES)); Assert.assertEquals(EXPECTED_TEXT_HASH_SHA256, HashUtils.computeSha256Hash(TEXT_BYTES)); } catch (NoSuchAlgorithmException e) { Assert.fail("Call to FluxtreamCaptu...
3472718_65
class StandaloneExp extends Exp { public abstract String getCode()@Override public abstract String getCode(); public abstract String getCode()public StandaloneExp append(StandaloneExp other); public abstract String getCode()public StandaloneExp append(NestedExp other); public abstract String getCode()public void...
assertEquals("\n$_ = $proceed($$);", StandaloneExp.PROCEED_AND_ASSIGN.getCode()); } }
3477759_76
class AdminController { @RequestMapping(params = "resume", method = RequestMethod.GET) public String resumeGame(Model model) { timerService.resume(); return getAdminPage(model); } public AdminController(); AdminController(TimerService timerService, GameSettingsService gameSettin...
when(timerService.isPaused()).thenReturn(GAME_ACTIVE); String jsp = controller.resumeGame(model); assertEquals("admin", jsp); verify(model).addAttribute("paused", GAME_ACTIVE); verify(timerService).resume(); } }
3510405_18
class ShortUrl implements Serializable { public void setFullUrl(String fullUrl) { this.fullUrl = fullUrl; } private static int safeLongToInt(long l); public static Long shortCodeToId(String shortCode); public Long getId(); public void setId(Long id); public String getFullUrl(); @Transien...
shortUrl.setFullUrl("http://repasky.name"); constraintViolations = validator.validate(shortUrl); assertEquals(0, constraintViolations.size()); } }
3513261_56
class XCodeContext implements IXCodeContext { public String getProvisioningProfile() { return getSettings().getAllSettings().get(Settings.ManagedSetting.PROVISIONING_PROFILE.name()); } public XCodeContext(List<String> buildActions, File projectRootDirectory, PrintStream out, Settings settings, Op...
Map<String, String> managedOptions = new HashMap<String, String>(); managedOptions.put(Options.ManagedOption.CONFIGURATION.getOptionName(), "Release"); managedOptions.put(Options.ManagedOption.SDK.getOptionName(), "mysdk"); managedOptions.put(Options.ManagedOption.PROJECT.getOptionName(), "MyLibrary.xco...
3523632_78
class ObjectUtil { public static int hashCode(Object... objects) { return Arrays.hashCode(objects); } public static boolean equals(@Nullable Object a, @Nullable Object b); public static String toPrettyString(Object value); private static String primitiveArrayToString(Object value, Class componentType); privat...
assertThat(ObjectUtil.hashCode("a", "b") - ObjectUtil.hashCode("a", "a")).isEqualTo(1); } }
3526892_12
class ProbabilityDistributions { static public Double calculateLabelCost(String calcLabel, Map<String, Double> labelProbabilities, CostMatrix<String> costMatrix) { if (calcLabel == null) { return Double.NaN; } double sum = 0.; for (String label: costMatrix.getKnownValues()) { double cost = costMatrix...
String calcLabel = "OK"; Map<String, Double> labelProbabilities = new HashMap<String, Double>(); labelProbabilities.put("OK", 0.5); labelProbabilities.put("LOK", 0.0); labelProbabilities.put("HOK", 1.); CostMatrix<String> costMatrix = new CostMatrix<String>(); costMatrix.add("OK", "OK", 1.); costMatrix...
3536819_44
class PropertiesWrapper implements Properties { @Nullable @Override public Object getPropertyUnchecked(@NotNull String name) { try { return getProperty(name); } catch (Exception e) { return null; } } private PropertiesWrapper(@NotNull Object object)...
assertNull(comprehensive.getPropertyUnchecked("custom.fake")); } }
3548254_1
class GeoToWktConverter { public static String convertToWktString(Geoshape fieldValue) throws BackendException { if (fieldValue.getType() == Geoshape.Type.POINT) { Geoshape.Point point = fieldValue.getPoint(); return "POINT(" + point.getLongitude() + " " + point.getLatitude() + ")";...
Geoshape p1 = Geoshape.point(35.4, 48.9); //no spaces, no negative values Geoshape p2 = Geoshape.point(-35.4,48.9); //negative longitude value Geoshape p3 = Geoshape.point(35.4, -48.9); //negative latitude value String wkt1 = "POINT(48.9 35.4)"; String actualWkt1 = GeoToWktConve...
3551455_26
class Functions { public static <T> Function<List<T>, T> firstOfList() { return list -> list.get(0); } private Functions(); public static Function<List<T>, T> lastOfList(); public static Function<List<T>, T> nthOfList(int index); public static Function<List<T>, List<T>> permutationOfList( int....
assertEquals('a', firstOfList().apply(ONE)); assertEquals('a', firstOfList().apply(TWO)); assertEquals('a', firstOfList().apply(THREE)); } }
3570915_4
class SmartTimeFormat extends TimeFormat { public static int[] parseToHourAndMinutes(final String timeString) throws ParseException { String time = timeString; time = Strings.nullToEmpty(time).trim(); if (time.length() == 0) { throw new ParseException("String is empty",...
int[] hoursAndMinutes = SmartTimeFormat.parseToHourAndMinutes("9,75"); assertEquals(hoursAndMinutes[0], 9); assertEquals(hoursAndMinutes[1], 45); } }
3580492_6
class GameOfLife { public void nextCycle() throws GameOfLifeException { // We initialize the next state as a x + 1, y + 1 of current state // We do this so next cells can be born around past state emptyMatrix(auxMatrix, MAX_X, MAX_Y); for(int i = 0; i < MAX_X; i++) { for(int j = 0; j < MAX_Y; j++) { if...
byte[] bytes = new byte[] { -52, 51 }; GameOfLife gameOfLife = new GameOfLife(4, bytes, 8, 8, 10); assertEquals(1, gameOfLife.getMatrix()[0][0]); assertEquals(1, gameOfLife.getMatrix()[0][1]); assertEquals(0, gameOfLife.getMatrix()[0][2]); assertEquals(0, gameOfLife.getMatrix()[0][3]); assertEquals(1, ga...
3590026_7
class DefaultRopContext implements RopContext { public ServiceMethodHandler getServiceMethodHandler(String methodName, String version) { return serviceHandlerMap.get(ServiceMethodHandler.methodWithVersion(methodName, version)); } public DefaultRopContext(ApplicationContext context); public v...
ApplicationContext context = mock(ApplicationContext.class); when(context.getBeanNamesForType(Object.class)).thenReturn(new String[]{"service1"}); Class withGroupServiceClass = WithGroupService.class; when(context.getType("service1")).thenReturn(withGroupServiceClass); RopContex...
3590271_2
class PluginManager extends HasEventBus { public static PluginManager getInstance() { if (ourInstance == null) { ourInstance = new PluginManager(); } return ourInstance; } private PluginManager(); public void loadPlugins(); private Collection<? extends Plugin>...
PluginManager manager = PluginManager.getInstance(); try { // private Collection<? extends Plugin> sortDependencies(Collection<? extends Plugin> plugins) { Method sort = manager.getClass().getDeclaredMethod("sortDependencies", Iterable.class); sort.setAccessible...
3603171_2
class HttpClientFactory { CloseableHttpClient getHttpClient(final ProxyConfiguration proxyConfiguration, final HttpClientConfiguration httpClientConfiguration) throws SmartlingApiException { HttpClientBuilder httpClientBuilder = getHttpClientBuilder(); if (hasActiveProxyConfiguration(proxyConfigur...
ArgumentCaptor<CredentialsProvider> credentialsProviderCaptor = ArgumentCaptor.forClass(CredentialsProvider.class); ArgumentCaptor<HttpHost> httpHostArgumentCaptor = ArgumentCaptor.forClass(HttpHost.class); PowerMockito.when(httpClientBuilder.setProxy(httpHostArgumentCaptor.capture())).thenRetur...
3610576_0
class SortJob implements Tool, Configurable { @Override public int run(String[] args) throws Exception { if(args.length != 2) { System.out.println("Invalid number of arguments\n\n" + "Usage: IdentityJob <input_path> <output_path>\n\n"); return -1; } String input = args[0]; String output = args[1...
trash(OUTPUT); File iFile = new File(INPUT); Charset utf8 = Charset.forName("UTF-8"); String inputStr = "A-This is\nB-the file\nC-content\n"; Files.write(inputStr, iFile, utf8); ToolRunner.run(new SortJob(), new String[]{INPUT, OUTPUT}); String outputStr = Files.toString(new File(OUTPUT, ...
3628180_31
class UserService { public User getUserByUsername(String username) { User currentUser = authenticationService.getCurrentUser(); String domain = DomainUtil.getDomainFromLogin(currentUser.getLogin()); String login = DomainUtil.getLoginFromUsernameAndDomain(username, domain); return ge...
mockAuthenticationOnUserService("jdubois@ippon.fr"); User user = userService.getUserByUsername("jdubois"); assertThat(user.getStatusCount(), is(2L)); assertThat(user.getFollowersCount(), is(3L)); assertThat(user.getFriendsCount(), is(4L)); } }
3644569_17
class EntityMappingExtractorImpl implements EntityMappingExtractor { public Fields extractFields(Class<?> type) { if (type == null) { throw new NullPointerException("Cannot extract entity mapping, type is null!"); } final Entity entityAnnotation = type.getAnnotation(Entity.class); if (entityAnnotation == n...
final Fields extract = extractor.extractFields(EntityWithoutProperties.class); assertThat("Non-entites should not generate any mapped fields.", extract.isEmpty(), is(true)); } }
3645037_2
class ProxyGrantingTicketStorageImpl implements ProxyGrantingTicketStorage { @Override public String retrieve(final String proxyGrantingTicketIou) { if (CommonUtils.isBlank(proxyGrantingTicketIou)) { return null; } final ProxyGrantingTicketHolder holder = this.cache.get(pro...
Assert.assertNull(this.storage.retrieve(null)); } }
3649012_0
class FFPojoAnnotationFieldManager { public Class<?> getClassDecorator(Class<? extends Annotation> clazzPositionalFieldAnnotation){ if (!isFFPojoAnnotationField(clazzPositionalFieldAnnotation)){ throw new FFPojoException(String.format("The class %s not seem a DelimitedField or PositionalField a...
Class<?> decorator = annotationFieldManager.getClassDecorator(DateDelimitedField.class); Truth.assert_().that(decorator).isEqualTo(InternalDateDecorator.class); } }
3655926_5
class URIcompliance { static String extractPersistentId(URI objURI) { String URIstr = objURI.toString(); Matcher m = genericURIpattern1Pat.matcher(URIstr); if (m.matches()) { return m.group(1); } else { return null; } } private static void validateIdVersion(String displayId, String version); st...
if (extractPersistentId(uri6)==null) { return; } assert(false); } }
3657930_2715
class TreeUtil { public static boolean isNodeType(Tree tree, String typeName, Tree typeRoot) { String primaryName = TreeUtil.getName(tree, JCR_PRIMARYTYPE); if (typeName.equals(primaryName)) { return true; } else if (primaryName != null) { Tree type = typeRoot.getChi...
Tree tree = mockTree(PathUtils.ROOT_PATH, true); assertFalse(TreeUtil.isNodeType(tree, NT_REP_ROOT, typeRoot)); } }
3661343_12
class GroupingHelper { public <KeyT> Map<KeyT, ValueT> groupUnique(Function<ValueT, KeyT> keyExtractor) { Map<KeyT, ValueT> groupedEntities = new HashMap<>(); for (ValueT value : collection) { final KeyT key = keyExtractor.apply(value); if (groupedEntities.get(key) != null) ...
Map<Integer, Integer> expected = new HashMap<>(); expected.put(2, 1); expected.put(4, 2); expected.put(6, 3); final Map<Integer, Integer> result = GROUPING_HELPER.groupUnique(number -> number * 2); Assert.assertEquals("Unexpected map content", expected, r...
3664810_0
class RepositoryEntityController extends AbstractRepositoryRestController implements ApplicationEventPublisherAware { @RequestMapping(value = BASE_MAPPING + "/{id}", method = RequestMethod.GET) public ResponseEntity<EntityModel<?>> getItemResource(RootResourceInformation resourceInformation, @BackendId Serializab...
KeyValuePersistentEntity<?, ?> entity = mappingContext .getRequiredPersistentEntity(RepositoryPropertyReferenceControllerUnitTests.Sample.class); ResourceMappings mappings = new PersistentEntitiesResourceMappings( new PersistentEntities(Collections.singleton(mappingContext))); ResourceMetadata metadata...
3674743_1
class LogglyBatchAppender extends AbstractLogglyAppender<E> implements LogglyBatchAppenderMBean { @Override public int getDiscardedBucketsCount() { return outputStream.getDiscardedBucketCount(); } @Override protected void append(E eventObject); @Override public void start(); @Override ...
// assert nothing yet discarded (because nothing is yet sent) assertEquals(0, appender.getDiscardedBucketsCount()); // send stuff and wait for it to be received final int NUM_MSGS = 40; appendFullBuckets(NUM_MSGS); httpServer.waitForRequests(MAX_BUCKETS); // assert excess buckets (those > ...
3690150_69
class UiUtils { public String pageLink(String providerName, String pageName) { return pageLink(providerName, pageName, null); } public void includeCss(String file); public void includeCss(String providerName, String file); public void includeCss(String providerName, String file, Integer priority); public void...
String link = ui.pageLink("mymoduleid", "myPage?param=val#mySection", null); Assert.assertTrue(link.endsWith("/mymoduleid/myPage.page?param=val#mySection")); } }
3691193_14
class AllComponentsState { @Transactional public void setComponentState(String componentId, ComponentType type, boolean enabled) { log.debug("Setting Component State : componentId = " + componentId + " type = " + type + " enabled " + enabled); ComponentState componentState; synchronize...
String componentId = "componentId"; ComponentType componentType = ComponentType.APP; Criteria mockCriteria = mock(Criteria.class); DbSession mockSession = mock(DbSession.class); when(sessionFactory.getCurrentSession()).thenReturn(mockSession); when(mockSession.createCrite...
3699746_62
class OsgiDefaultProducer extends DefaultProducer { @Override protected void doStop() throws Exception { ServiceHelper.stopService(processor); services.stopTracking(); super.doStop(); } public OsgiDefaultProducer(OsgiDefaultEndpoint endpoint, Map<String, Object> props); @...
OsgiDefaultProducer producer = createProducer(Collections.singletonMap("key", (Object) "value")); ServiceHelper.startService(producer); ServiceHelper.stopService(producer); verify(producer.getApplicationBundleContext()).removeServiceListener(Matchers.any(ServiceListener.class)); } ...
3706353_2
class OmitIndexingFilter implements IndexingFilter { @Override public NutchDocument filter(NutchDocument doc, Parse parse, Text url, CrawlDatum datum, Inlinks inlinks) throws IndexingException { // Prepare data String realUrl = new String(url.getBytes()).substring(0, url.getLength()); Metadata metadata = pars...
// Prepare data Parse parse = mock(Parse.class); Configuration configuration = mock(Configuration.class); ParseData parseData = new ParseData(); parseData.setParseMeta(metadata); // Mock data when(parse.getData()).thenReturn(parseData); when(configuration.get(anyString())).thenReturn(""); when(con...
3710234_51
class Lexer { public List<RobotLine> lex() throws CoreException { try { System.out.println("Lexing " + filename); CountingLineReader contents = new CountingLineReader(filestream); String line; int lineNo = 0; int charPos = 0; while (nu...
Lexer lexer = new Lexer("x"); List<RobotLine> lines = lexer.lex(); assertEquals(1, lines.size()); RobotLine line1 = lines.get(0); assertThat(line1.lineNo, is(0)); assertThat(line1.lineCharPos, is(0)); assertThat(line1.arguments.size(), is(1)); } }
3713233_87
class ClassMetaExtractor { public ClassMeta extract(String sourceCodeString) { Assertion.on("sourceCodeString").mustNotBeNull(sourceCodeString); ClassMeta meta = new ClassMeta(); String modifiedSourceCodeString = TrimFilterUtil.doAllFilters(sourceCodeString); // -----------------...
ClassMetaExtractor target = new ClassMetaExtractor(config); String sourceCodeString = null; try { target.extract(sourceCodeString); fail(); } catch (JUnitHelperCoreException e) { } } }
3713238_183
class Minus extends AbstractRhsFunctionHandler { @Override public Symbol execute(RhsFunctionContext context, List<Symbol> arguments) throws RhsFunctionException { RhsFunctions.checkAllArgumentsAreNumeric(getName(), arguments); RhsFunctions.checkArgumentCount(this, arguments); ...
Minus minus = new Minus(); assertEquals(-33, minus.execute(rhsFuncContext, Symbols.asList(syms, 33)).asInteger().getValue()); } }
3722315_4
class UPortalURLServiceImpl implements IURLService { @Override public String getLocationUrl(Location location, PortletRequest request) { try { final String encodedLocation = URLEncoder.encode(location.getIdentifier(), "UTF-8"); return portalContext.concat("/s/location?id=").conc...
Location location = new Location(); location.setIdentifier("ABC"); String url = urlService.getLocationUrl(location, request); assertEquals("/context/s/location?id=ABC", url); } }
3724388_103
class IOUtil extends WWIO { public static ByteBuffer readByteBuffer(URL url) throws IOException { ByteBuffer byteBuffer = null; if (URLUtil.isForResourceWithExtension(url, "zip")) { //try opening the file as a zip file; if this fails, log a warning and read file directly into the buffer InputStream is = ...
ByteBuffer byteBuffer = IOUtil.readByteBuffer(getClass().getResource("bytes.out")); assertNotNull(byteBuffer); assertEquals(1, byteBuffer.get()); assertEquals(2, byteBuffer.get()); assertEquals(3, byteBuffer.get()); assertEquals(4, byteBuffer.get()); assertEquals(5, byteBuffer.get()); } }
3726486_7
class HashCalculator { public HashCalculationResult calculateSuperHash(File file) throws IOException { // Ignore files smaller than 0.5kb long fileSize = file.length(); if (fileSize <= FILE_MIN_SIZE_THRESHOLD) { logger.debug("Ignored file " + file.getName() + " (" + FileUtils.by...
HashCalculator hashCalculator = new HashCalculator(); File originFile = new File(URLDecoder.decode(getClass().getResource("/superHash/origin.txt").getFile(), "utf-8")); HashCalculationResult originFileHashResult = hashCalculator.calculateSuperHash(originFile); File whitespaceChangesFile...
3728202_22
class ApiController extends AbstractApiController { protected void setResultOptions(AbstractEntry entry, Integer count, Integer startIndex, String sortBy) { entry.setFiltered(false); entry.setSorted(sortBy != null); if (sortBy != null) { entry.sortEntryCollection(sortBy); } entry.setUpdated...
AbstractEntry entry = new PersonEntry(new Person(), 1, 1, "name", 5); controller.setResultOptions(entry, 3, 2, "name"); assertEquals(1, entry.getTotalResults()); } }
3728381_27
class NdefMessageEncoder { public byte[] encodeSingle(Record record) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); encodeSingle(record, baos); return baos.toByteArray(); } public NdefMessageEncoder(NdefRecordEncoder ndefRecordEncoder); public void encodeSingle(Record record, ByteArrayOutputS...
byte[] single = encoder.encodeSingle(new UriRecord( "http://www.verylongurl.com/aljhsldfkjhasldfkhjaljhsldfkjhasldf" + "khjaljhsldfkjhasldfkhjaljhsldfkjhasldfkhjaljhsldfkjhasldfkhjaljhsldfkjhasldfkhjal" + "jhsldfkjhasldfkhjaljhsldfkjhasldfkhjaljhsldfkjhasldfkhjaljhsldfkjhasldfkhjaljhsldf" + "kj...
3732883_60
class ApiNode implements Node { @Override public NodePath getNodePath() { String name = getName(); ApiNode parent = context.getParentNode(); NodePath path = isRoot() ? NodePath.root() : NodePath.path(name); if (parent != null) { path = parent.getNodePath().append(pa...
root.addChild("child0").addChild("child0-0"); assertEquals("/child0", root.getChild("child0").getNodePath().toString()); assertEquals("/child0/child0-0", root.getChild("child0").getChild("child0-0").getNodePath().toString()); } }
3742443_2
class Gq implements Identifiable, Group<Gq> { @Override public Group.Element<Gq> getIdentityElement() { return element(BigInteger.ONE); } public Gq(GqSetup setup); private Group.Element<Gq> element(BigInteger element); @Override public Group.Element<Gq> getGenerator(); @Override public String getIdentity()...
Group.Element<Gq> identity = group.getIdentityElement(); assertEquals(group, identity.getGroup()); } }
3743376_249
class Community extends DSpaceObject implements DSpaceObjectLegacySupport { void setLogo(Bitstream logo) { this.logo = logo; setModified(); } protected Community(); void addSubCommunity(Community subCommunity); public void removeSubCommunity(Community subCommunity); public B...
// Disallow current Community WRITE perms doThrow(new AuthorizeException()).when(authorizeServiceSpy).authorizeAction(context, c, Constants.WRITE); File f = new File(testProps.get("test.bitstream").toString()); communityService.setLogo(context, c, new FileInputStream(f)); fail("...
3743505_14
class DropboxAPI { public List<Entry> search(String path, String query, int fileLimit, boolean includeDeleted) throws DropboxException { assertAuthenticated(); if (fileLimit <= 0) { fileLimit = SEARCH_DEFAULT_LIMIT; } String target = "/search/" + session.ge...
try { // Should be too short, and give an error api.search("/", "", 1000, false); assert false: "Short (empty) search string did not throw an error."; } catch (DropboxServerException e) { if (e.error != DropboxServerException._400_BAD_REQUEST) { ...
3744706_7
class ResourceLoader { public InputStream getResourceAsStream(String name) throws IOException { if (name.startsWith("classpath:")) return openClasspathResource(name); else if (name.startsWith("file:")) return openFileResource(name); else return op...
logger.info("testWarInternalRelativePathNoBasedir()"); ResourceLoader loader = new ResourceLoader(war); // without a basedir, relative paths are relative to the root of the WAR in = loader.getResourceAsStream("WEB-INF/web.xml"); assertNotNull("returned resource", in); ...
3750999_3
class ProfileTemplate extends AbstractTemplate implements ProfileOperations { public XingProfile getUserProfile() { return getProfileById("me"); } public ProfileTemplate(String xingBaseUrl, RestOperations restOperations, ObjectMapper objectMapper); public ProfileTemplate(RestOperations restO...
mockServer.expect(requestTo(XingTemplate.DEFAULT_BASE_URL + ProfileTemplate.USERS_URL.replaceFirst("\\{id\\}", "me"))).andExpect(method(GET)) .andRespond(withSuccess(new ClassPathResource("testdata/profile.json", getClass()), MediaType.APPLICATION_JSON)); XingProfile userProfile = xing.profileOperations().getUs...
3756907_0
class BackoffSleeper { public BackoffSleeper(long minWait, long maxWait, double backoffMultiplier) { if (minWait <= 0) { throw new IllegalArgumentException("Minimum wait must be at least 1 ms"); } if (maxWait <= minWait) { throw new IllegalArgumentExc...
BackoffSleeper sleeper = new BackoffSleeper(50, 230, 2.0); long now = System.currentTimeMillis(); sleeper.sleep(); Assert.assertEquals(now + 50, System.currentTimeMillis(), 50); sleeper.sleep(); Assert.assertEquals(now + 150, System.currentTimeMillis(), 100); slee...
3765814_1
class ExtensionObjectMapper { public static <T> T getOtherAttribute(Map<QName, String> otherAttributes, String attributeName) { T otherAttribute = null; for (QName qname : otherAttributes.keySet()) { String value = otherAttributes.get(qname); String key = qname.getLocalPart(...
String crazyName = ExtensionObjectMapper.getOtherAttribute(unMarshalledLb.getOtherAttributes(), "crazyName"); Assert.assertEquals("foo", crazyName); } }
3772264_10
class RiemannReporter extends ScheduledReporter { @Override public void report(SortedMap<String, Gauge> gauges, SortedMap<String, Counter> counters, SortedMap<String, Histogram> histograms, SortedMap<String, Meter> meters, ...
reporter.report(map("gauge", gauge(1.1)), this.<Counter>map(), this.<Histogram>map(), this.<Meter>map(), this.<Timer>map()); final InOrder inOrder = inOrder(riemann, eventDSL, client); inOrder.verify...
3781210_16
class UserTemplate implements UserOperations { public UserCredentials createUser() { return createUser(null); } public UserTemplate(RestOperations restOperations); public UserCredentials createUser(UserConfig userConfig); public void modifyUser(String userId, UserConfig userConfig); public void resetPasswor...
masterKeyMockServer.expect(requestTo("https://go.urbanairship.com/api/user")) .andExpect(method(POST)) .andRespond(withResponse(jsonResource("data/user-credentials"), responseHeaders, HttpStatus.CREATED, "Created")); UserCredentials credentials = urbanAirship.userOperations().createUser(); assertEquals("htt...
3787360_8
class StompFrameDecoder extends ReplayingDecoder<VoidEnum> { public static String unescapeHeader(String string) { if (string == null) return string; string = string.replace("\\n", "\n"); string = string.replace("\\c", ":"); string = string.replace("\\\\", "\\"); return string; } public StompFrameDe...
assertNull(StompFrameDecoder.unescapeHeader(null)); } }
3798663_0
class SqlMapQuery implements RepositoryQuery { @Override public Object execute(Object[] parameters) { Object parameterObject = parametersParsing(parameters); if (StatementType.SELECT.equals(statementType)) { if (!queryMethod.isPageQuery() && !queryMethod.isCollectionQuery()) { return templa...
when(mappedStatement.getStatementType()).thenReturn(StatementType.SELECT); when(queryMethod.isCollectionQuery()).thenReturn(true); new SqlMapQuery(queryMethod, delegate, template).execute(null); verify(template).queryForList(namedQueryName, null); } }
3806452_12
class SimpleVersion implements Comparable<SimpleVersion>, Serializable { public static String getCurrentJavaVirtualMachineSpecificationVersion() { return System.getProperty("java.vm.specification.version", "1.8"); } public SimpleVersion(final Integer major, final Integer medium); public fina...
Assert.assertNotNull(SimpleVersion.getCurrentJavaVirtualMachineSpecificationVersion()); } }
3808230_16
class CachingDocumentNIO implements DocumentReader<T>, DocumentWriter<T> { @Override public boolean deleteDocumentFile(DatabaseDocument<T> d, String fileName) { return writer.deleteDocumentFile(d, fileName); } public CachingDocumentNIO(DatabaseConnector<T> backing, Cache<T> cache); public CachingDocumentNI...
io.deleteDocumentFile(doc1, "file"); verify(writer, times(1)).deleteDocumentFile(doc1, "file"); verifyNoMoreInteractions(cache); } }
3817774_2
class MockNats implements Nats { @Override public Request request(String subject, long timeout, TimeUnit unit, MessageHandler... messageHandlers) { return request(subject, "", timeout, unit, messageHandlers); } @Override public boolean isConnected(); @Override public boolean isClosed(); @Override public void ...
final Nats nats = new MockNats(); final String subject = "test"; final String response = "This is a response."; nats.subscribe(subject, new MessageHandler() { @Override public void onMessage(Message message) { message.reply(response); } }); final boolean[] flag = new boolean[] { false }; nat...
3833897_2
class DomainObjectAllocator { public <T extends AbstractDomainObject> T allocateObject(Class<T> objClass, Object oid) { if (objClass == null) { throw new RuntimeException("Cannot allocate object '" + oid + "'. Class not found"); } if (Modifier.isAbstract( objClass.getModifiers()...
DomainObjectAllocator allocator = new DomainObjectAllocator(MyADO.class); AbstractDomainObject object = allocator.allocateObject(MyDO.class, "xpto"); assertEquals(object.getClass(), MyDO.class); assertEquals(object.getExternalId(), "xpto"); } }
3836962_11
class JSAbstractOperations { static Double ToNumber(Object arg) { if (arg == null) { return 0.0d; } else if (Boolean.TRUE.equals(arg)) { return 1.0d; } else if (Boolean.FALSE.equals(arg)) { return 0.0d; } else if (arg instanceof String) { return ToNumber((String) arg); } else if (arg instanc...
assertEquals(0.0, ToNumber(false), 0.0); assertEquals(Double.POSITIVE_INFINITY, 1 / ToNumber(false), 0.0); assertEquals(1.0, ToNumber(true), 1.0); } }
3842880_1
class CombinationProcessor implements AnalysisProcessor { @Override public void run(IProgressMonitor monitor) { Date startTime = new Date(); // Prepare data matrix to combine IMatrix data = analysis.getData().get(); // Dimension to combine using the module map MatrixD...
CombinationAnalysis analysis = getAnalysis(); // Keep the correct results IMatrix resultsOk = analysis.getResults().get(); analysis.setResults(null); try { AnalysisProcessor processor = new CombinationProcessor(analysis); processor.run(getProgressMonito...
3847504_139
class SearchQueryImpl implements SearchQuery { public SearchQuery withPathPrefix(String path) { clearExpectations(); if (path.endsWith("/")) path = path.substring(0, path.length() - 1); this.pathPrefix = path; if (pathPrefix == null) throw new IllegalArgumentException("Path prefix must no...
String prefix = "/path/prefix"; query.withPathPrefix(prefix); assertEquals(prefix, query.getPathPrefix()); } }
3859251_23
class LogManagerProperties extends Properties { @Override public synchronized Object remove(final Object key) { final Object def = preWrite(key); final Object man = super.remove(key); return man == null ? def : man; } LogManagerProperties(final Properties parent, final String...
String prefix = LogManagerPropertiesTest.class.getName(); LogManager manager = LogManager.getLogManager(); try { String key = prefix.concat(".dummy"); Properties parent = new Properties(); parent.put(key, "value"); parent.put("", "empty"); ...
3869967_60
class MongoAppSessionRepository extends CrudRepositoryBase<AppSession, String> implements AppSessionRepository { @Override public <S extends AppSession> S add(final S appSession) { Preconditions.checkNotNull(appSession, "Cannot add null AppSession"); Preconditions.checkNotNull(appSession.getId(), "Cannot add App...
final AppSession appSession = SecurityFactory.eINSTANCE.createAppSession(); appSession.setId("00000000"); appSession.setCreationTime(new DateTime()); appSession.setStatus(AppSessionStatus.ACTIVE); appSession.setIpAddress("127.0.0.1"); appSession.setTimeout(1800000L); appSession.setAccessTime(new DateTime(...
3885169_5
class User extends AbstractEntity { public boolean verifyPassword(String password) { return new BasicPasswordEncryptor().checkPassword(password, this.password); } public String getFirstname(); public void setFirstname(String firstname); public String getSurname(); public void setSurname(String surname); ...
User user = new UserTestdataBuilder().build(); Assert.assertTrue(user.verifyPassword("secret")); Assert.assertFalse(user.verifyPassword("other")); } }
3894929_2
class HasXPath extends TypeSafeDiagnosingMatcher<Node> { public HasXPath(String xPathExpression, Matcher<String> valueMatcher) { this(xPathExpression, NO_NAMESPACE_CONTEXT, valueMatcher); } public HasXPath(String xPathExpression, Matcher<String> valueMatcher); public HasXPath(String xPathExp...
assertMatches(hasXPath("//emptySomething"), xml); } }
3900538_7
class TrackMessageSizeDecoder implements ReplayDecoder<String, String> { @Override public Decoded<List<String>> decode(Event type, String message) { if (type.equals(Event.MESSAGE)) { if (skipFirstMessage.getAndSet(false)) return empty; Decoded<List<String>> messages = new Decod...
decoder = new TrackMessageSizeDecoder("^", false); String messages = "37^{\"message\":\"ab\",\"time\":1373900488807}37^{\"message\":\"ab\",\"time\":1373900488808}37^{\"message\":\"ab\",\"time\":1373900488810}"; List<String> expected = new ArrayList<String>() { { add("...
3910894_1
class GoogleMusicAPI implements IGoogleMusicAPI { @Override public final Collection<Song> getAllSongs() throws IOException, URISyntaxException { final Collection<Song> chunkedCollection = new ArrayList<Song>(); // Map<String, String> fields = new HashMap<String, String>(); ...
// given final int expectedSongListSize = 3; final String expectedSong3Title = "Song Title, With Comma"; final String expectedSong3Artist = "Artist 2"; final String expectedSong3Album = "Album 2"; final int expectedSong3Year = 2014; final String testData = Files...
3913468_1
class EnvironmentVariablesPropertiesSource implements PropertiesSource { @Override public Map<String,String> getProperties() { Map<String,String> envVars = System.getenv(); if (!Collections.isEmpty(envVars)) { return new LinkedHashMap<String, String>(envVars); } r...
mockStaticPartial(System.class, "getenv"); expect(System.getenv()).andReturn(null); replayAll(); Map<String, String> props = new EnvironmentVariablesPropertiesSource().getProperties(); assertEquals(props.size(), 0); } }
3933009_4
class SpaceCreationInvitationGroupVisibilityPlugin extends GroupVisibilityPlugin { @Override public boolean hasPermission(Identity userIdentity, Group group) { if (userACL.getSuperUser().equals(userIdentity.getUserId()) || userIdentity.getMemberships() .stream() ...
// Given UserACL userACL = mock(UserACL.class); when(userACL.getSuperUser()).thenReturn("john"); SpacesAdministrationService spacesAdministrationService = mock(SpacesAdministrationService.class); when(spacesAdministrationService.getSpacesAdministratorsMemberships()).thenReturn(Arrays.asList(new Memb...
3934425_27
class Utils { public static String getPathOnly(String fullPath) { if (fullPath == null || fullPath.isEmpty()) return fullPath; int index = fullPath.indexOf('?'); if (index == -1) { index = fullPath.indexOf('#'); return index == -1 ? fullPath : fullPath.substring...
assertNull(Utils.getPathOnly(null)); assertTrue(Utils.getPathOnly("").isEmpty()); String path = "/path"; assertEquals(path, Utils.getPathOnly("/path?query#fragment")); assertEquals(path, Utils.getPathOnly("/path?query")); assertEquals(path, Utils.getPathOnly("/path")); assertEq...
3935296_8
class ForumServiceUtils { @SuppressWarnings("unchecked") public static List<String> getUserPermission(String[] userGroupMembership) throws Exception { List<String> users = getFromCache(userGroupMembership); if (users != null) { return users; } users = new ArrayList<String>(); if (userGro...
List<String> emptyList = ForumServiceUtils.getUserPermission(null); assertNotNull(emptyList); assertEquals(0, emptyList.size()); } }
3935748_24
class PermissionsGroupVisibilityPlugin extends GroupVisibilityPlugin { public boolean hasPermission(Identity userIdentity, Group group) { Collection<MembershipEntry> userMemberships = userIdentity.getMemberships(); return userACL.getSuperUser().equals(userIdentity.getUserId()) || userMemberships.stre...
// Given UserACL userACL = mock(UserACL.class); when(userACL.getSuperUser()).thenReturn("root"); when(userACL.getAdminGroups()).thenReturn("/platform/administrators"); GroupVisibilityPlugin plugin = new PermissionsGroupVisibilityPlugin(userACL); Identity userIdentity = new Identity("john", Arra...
3937364_5
class AccountSetupService { public boolean mustSkipAccountSetup() { if (skipSetup == null) { SettingValue accountSetupNode = settingService.get(Context.GLOBAL, Scope.GLOBAL, ACCOUNT_SETUP_NODE); String propertySetupSkip = PropertyManager.getProperty(ACCOUNT_SETUP_SKIP_PROPERTY); if (propertySe...
// Given PropertyManager.setProperty(AccountSetupService.ACCOUNT_SETUP_SKIP_PROPERTY, "true"); AccountSetupService accountSetupService = new AccountSetupService(settingService, organizationService); // When boolean mustSkip = accountSetupService.mustSkipAccountSetup(); // Then assertTrue(...
3943003_2
class FileProvider { public String filePathFromURL(URL url) { if (url == null) { throw new IllegalArgumentException("url is null"); } // Old solution does not deal well with "<" | ">" | "#" | "%" | // <"> "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`" since they may occur // inside an URL b...
// setup: URL url = new URL("file:///With%20Space/File.jar"); // exercise: String actual = (new FileProvider()).filePathFromURL(url); // verify: assertThat( actual, PlatformUtil.onWindows() ? matchesPattern("\\A/[A-Z]:/With Space/File\\.jar\\z") : equalTo(...
3946094_2
class HelloBean implements HelloLocal { @Override public String sayHello() { Pojo pojo = new Pojo(); pojo.version(); return "Hello"; } } class HelloBeanTest { @Test public void testSayHello_String() {
HelloBean b = new HelloBean(); assertTrue(b.sayHello().equals("Hello")); } }
3951979_0
class FetchChartDataHandler implements ActionHandler<FetchChartData, FetchChartData.Result> { protected List<DataPoint> downsample(long duration, Aggregator aggregator, List<DataPoint> points) { List<DataPoint> result = Lists.newArrayList(); int offset = 0; long maxSampleTimestamp = 0; for (int...
FetchChartDataHandler handler = new FetchChartDataHandler(); List<DataPoint> points = Lists.newArrayList(); for (int i = 0; i < 10; i++) { points.add(new DataPoint(i, i * 10)); } List<DataPoint> downsampledPoints = handler.downsample(3, new Aggregators.AvgAggregator(), points); assertEqu...
3978781_357
class LiveDataReactiveStreams { @NonNull public static <T> LiveData<T> fromPublisher(@NonNull Publisher<T> publisher) { return new PublisherLiveData<>(publisher); } private LiveDataReactiveStreams(); @NonNull public static Publisher<T> toPublisher( @NonNull LifecycleOwner lif...
Flowable<String> input = Flowable.just("foo") .concatWith(Flowable.just("bar", "baz").observeOn(sBackgroundScheduler)); LiveData<String> liveData = LiveDataReactiveStreams.fromPublisher(input); liveData.observe(mLifecycleOwner, mObserver); assertThat(mLiveDataOutput, is...
3988459_66
class SetCookieField extends HeaderField { public boolean isHttpOnly() { return httpOnly == null ? false : httpOnly; } public SetCookieField(String name, String value, String domain, String path, DateTimeRFC6265 expiration, Boolean secure, Boolean httpOnly); public ...
// given SetCookieField cookieField = new SetCookieField(null, null, null, null, (String) null, null, Boolean.TRUE); // then assertTrue(cookieField.isHttpOnly()); } }
3993813_9
class NioJournalFileRecord implements NioJournalConstants { public static FindResult findNextRecord(UUID delimiter, ByteBuffer source) { final byte hook = RECORD_DELIMITER_PREFIX[0]; if (source.hasRemaining()) { do { if (source.get() == hook) { int o...
final byte[] chunk = new byte[8 * 1024]; final byte[] recordBytes = recordToBytes(); final ByteBuffer byteBuffer = wrap(chunk); for (int i = (chunk.length - recordBytes.length) + 1; i < chunk.length; i++) { createNoise(chunk); arraycopy(recordBytes, 0, chunk, i,...
3996100_2
class CamelLoader implements Loader { @Override public String key() { return "camel"; } @Override public List<Diagram> load(String input, FileType fileType); private List<Diagram> camelContextToDiagram(String input, FileType fileType); } class CamelLoaderTest { @Test public void get...
Loader loader = LoaderHelper.getLoader("camel"); assertTrue(loader instanceof CamelLoader); assertEquals("camel", loader.key()); } }
3999381_29
class AbstractTrie implements Trie { @Override public int findShortestWord(CharSequence chars, int start, int end, StringBuilder word) { for(int i = start; i < end; i++){ Iterator<String> it = commonPrefixSearch(chars.subSequence(i, end).toString()).iterator(); //* if(it.hasNext()){ if(word != null) word...
String[] expected = { "ソフトウェア", "オープンソース", "ソフトウェア", "Linux", "Linux", "ファイル", "ファイル", "ファイル", "Linux" }; Trie t = trieWithWords("ソフトウェア", "ソフトウェアコンテナ", "オープンソース", "オープンソースソフトウェア", "Linux", "Linuxカーネル", "Linuxコンテナ", "Linuxコンテナ技術", "ファイル", "ファイルシステム"); List<String> actual = new ArrayList<>(...
4001968_2
class Annotation { public java.util.Map<String, AnnotationProperty> getProperties() { return properties; } public Annotation(Class<?> annotationClass, boolean visible, java.util.Map<String, AnnotationProperty> properties); public Class<?> getAnnotationClass(); public boolean isVisible();...
Mirror<ArrayAnnotatedObject> mirror = Mirrors.newMirrorFactory().getMirror(ArrayAnnotatedObject.class); final List<Annotation> annotations = mirror.getProperty("property").getAnnotations(); Assert.assertEquals(1, annotations.size()); final Annotation annotation = annotations.iterator().n...
4016036_0
class DeltaSnapshot { public List<DeltaSQLStatementSnapshot> getDeltaSqlStatementSnapshots() { return deltaSQLStatementSnapshots; } public DeltaSnapshot(); public DeltaSnapshot(Snapshot snapshotA, Snapshot snapshotB, boolean condenseInstances...
Calendar fiveMinutesAgo = new GregorianCalendar(); fiveMinutesAgo.add(Calendar.MINUTE, -5); Calendar now = new GregorianCalendar(); Snapshot snapshotA = new Snapshot(fiveMinutesAgo); Snapshot snapshotB = new Snapshot(now); SQLStatement sqlStatement = SQLHelper.getSQLSta...
4021268_10
class ScaleSymbolList { public String getName() { return name; } public void setName(String value); public String getComment(); public void setComment(String value); public List<String> getScaleSymbol(); public void setScaleSymbol(List<String> aScaleSymbol); } class ScaleSymbolListTest { @Test public ...
try { if (inputElement == null) { unmarshalInput(); } String symbolListName = inputElement.getName(); assertEquals("List name incoorect", "Western Chromatic Symbols", symbolListName); } catch (Exception e) { fail(e.getMessage()); } } }
4023244_0
class ReflectionUtils { public static boolean implementsInterface(final Class type, final Class interfaceClass) { return interfaceClass.isAssignableFrom(type); } public static Field[] getDeclaredAndInheritedFields(final Class type, final boolean returnFinalFields); public static List<Metho...
Assert.assertTrue(ReflectionUtils.implementsInterface(ArrayList.class, List.class)); Assert.assertTrue(ReflectionUtils.implementsInterface(ArrayList.class, Collection.class)); Assert.assertFalse(ReflectionUtils.implementsInterface(Set.class, List.class)); } }
4024302_13
class PojoSlice implements Slice { public void onStart() { if (target instanceof HazelcastInstanceAware) { ((HazelcastInstanceAware) target).setHazelcastInstance(hazelcastInstance); } if (target instanceof SliceLifecycleListener) { ((SliceLifecycleListener) target)....
HazelcastInstanceAware pojo = mock(HazelcastInstanceAware.class); HazelcastInstance hazelcastInstance = null;//Hazelcast.getDefaultInstance(); PojoSlice slice = new PojoSlice(pojo); slice.onStart(); verify(pojo).setHazelcastInstance(hazelcastInstance); verifyNoMoreIntera...
4026983_1
class ControlMessage { public String toJson() { return new Gson().toJson(this); } public ControlMessage(int leftSpeed, int rightSpeed, boolean lights, int panServoAngle, int tiltServoAngle, boolean takePicture, boolean servos, boolean rawValues); private synchronized static int getNextId(); public stat...
String value = "{\"id\":1,\"leftSpeed\":5,\"rightSpeed\":-4,\"panServoAngle\":42,\"tiltServoAngle\":10,\"lights\":true,\"takePicture\":false,\"servos\":true,\"rawValues\":false,\"timestamp\":10}"; assertThat(controlMessage.toJson(), is(value)); } }
4031229_11
class ReporterUtil { public static File getFileOutputDir(final URI baseUri, final File outputDir, final TestRunCoverageStatistics runStats) { final URI relativeTestUri = baseUri.relativize(runStats.test); return new File(outputDir, relativeTestUri.toString()).getParentFile().getAbsoluteFile(); ...
final URI test = URI.create(FILE_PREFIX + Joiner.on("/").join(PARENT_DIR_PATH, "src", "main", "javascript", "MyTest.html")); final TestRunCoverageStatistics stats = new TestRunCoverageStatistics(test); final File actual = getFileOutputDir(BASE_URI, OUTPUT_DIR, stats).getAbsoluteFile(); ...
4057303_5
class Manager { public T getAssociatedInstance(final String typeId) throws DempsyException { if(LOGGER.isTraceEnabled()) LOGGER.trace("Trying to find " + clazz.getSimpleName() + " associated with the transport \"{}\"", typeId); T ret = null; synchronized(registered) { ...
try (final ServiceManager<SomeInterface> manager = new ServiceManager<>(SomeInterface.class);) { manager.start(new TestInfrastructure("testManager", null, null, null)); final SomeInterface retrieved = manager.getAssociatedInstance(typeId); assertEquals(expectedClass, retriev...
4060867_7
class RESTBrowseController extends RESTAbstractController { public void getVideos(HttpServletRequest request, HttpServletResponse response) throws Exception { XMLBuilder builder = createXMLBuilder(request, response, true); builder.add("videos", true); builder.endAll(); response.get...
StringWriter sw = new StringWriter(); HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(response.getWriter()).thenReturn(new PrintWriter(sw)); browseController.getVideos(request, response); ...
4090170_0
class CascadingFieldsGenerator { public void generate(Schema schema, Writer output) throws IOException { final VelocityContext context = new VelocityContext(); context.put("schema", schema); context.put("this", this); engine.mergeTemplate(path + "fields.vm", "UTF-8", context, outpu...
final CascadingFieldsGenerator gen = new CascadingFieldsGenerator(); final Schema schema = getSchema(); final Writer writer = new StringWriter(); gen.generate(schema, writer); writer.close(); final String actual = writer.toString(); final String expected = Resou...
4101951_1
class DtoConfig { public List<DtoProperty> getProperties() { if (properties == null) { properties = list(); final List<PropConfig> pcs = getPropertiesConfig(); if (getDomainType() != null) { addPropertiesFromDomainObject(pcs); addChainedPropertiesFromDomainObject(pcs); } ...
// given two properties oracle.addProperty("com.domain.Foo", "a", "java.lang.String"); oracle.addProperty("com.domain.Foo", "b", "java.lang.String"); // and an override to skip b addDto("FooDto", domain("Foo"), properties("-b, *")); // then we have only 1 final DtoConfig dc = rootConfig.getD...
4103388_44
class JSwordPassageServiceImpl implements JSwordPassageService { @Override public OsisWrapper getOsisText(final String version, final String reference) { return getOsisText(version, reference, new ArrayList<LookupOption>(0), null, NONE); } @Inject public JSwordPassageServiceImpl(final JSwordV...
final Book currentBook = Books.installed().getBook("KJV"); final BookData bookData = new BookData(currentBook, currentBook.getKey("Romans 1:4")); final Element osisFragment = bookData.getOsisFragment(); final XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat()); ...
4112450_11
class UnitsParser { public boolean parse(String input) { String[] split = input.split(" "); if(split.length != 4) { if(LOGGER.isInfoEnabled()) LOGGER.info("Could not parse '"+input+"': 4 tokens expected"); return false; } String u = ...
System.out.println("parse"); String units = "seconds since 1980-1-1 0:0:0"; UnitsParser instance = new UnitsParser(); boolean ret = instance.parse(units); assertTrue(ret); System.out.println(instance); } }
4114494_1
class CoverageClassVisitor extends ClassVisitor implements Opcodes { public int getClassId() { return classId; } public CoverageClassVisitor(ClassVisitor classVisitor, int classId); @Override public void visit(int version, int access, String name, String signature, String superName, String[]...
for(int i = 0; i <= Short.MAX_VALUE;i++) { int cid = Registry.registerClass("class" + i, getClass().getClassLoader(), "class" + i + ".java"); ArrayList<String> methodNames = new ArrayList<String>(); methodNames.add("<init>"); methodNames.add("main"); ...
4117239_0
class Queue extends BaseQueue<VALUE, VALUE> { public Queue(Variable<ImmutableList<VALUE>> input, Variable<ImmutableList<VALUE>> output, Variable<Boolean> frozen) { super(input, output, frozen); } public Queue(Variable<ImmutableList<VALUE>> input, Variable<ImmutableList<VALUE>> output, Variable<Boolean> fro...
DriverFactory<ImmutableList<Integer>> listFactory = new BasicFactory<ImmutableList<Integer>>(); DriverFactory<Boolean> boolFactory = new BasicFactory<Boolean>(); QueueExecutable<Integer> queue = QueueExecutable.getQueueByName("integers", listFactory, boolFactory); queue.append(10); queue.append(11)...
4120901_37
class HadoopWorkflowDirectoryFilter implements InitializingBean { public boolean filter(File file) { return file.getParentFile().getAbsolutePath().contains(springHadoopWorkflowDirectoryName); } public String getSpringHadoopWorkflowDirectoryName(); public void setSpringHadoopWorkflowDirectoryName(String springHa...
String value = "test"; filter.setSpringHadoopWorkflowDirectoryName(value); File file = new File("src/test/resources/org/springframework/data/hadoop/admin/util/test/context.xml"); boolean filtered = filter.filter(file); Assert.assertTrue(filtered); } }
4131741_2
class CacheControlHandlerInterceptor extends HandlerInterceptorAdapter implements HandlerInterceptor { @Override public final boolean preHandle( final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception { this.assignCacheControlHeader(request, respons...
final HandlerMethod handler = new HandlerMethod( controller, controller.getClass().getMethod("handlePubliclyCachedPageAndRevalidatedRequest")); interceptor.preHandle(request, response, handler); System.err.println("CC: " + response.getHeader("Cache-Control")); assertNotNull(response.getHead...
4138309_2
class Event { public static Event<?> fromJson(String json) throws IOException { return JSONUtil.toObject(json, new TypeReference<Event<?>>() {}); } public Event(int eventId, Type type, long timestamp, T payload); private Event(Type type, T payload); public Event(); public int getId(); public Typ...
String json = "{\n" + " \"type\" : \"JOB_STARTED\",\n" + " \"payload\" : {\n" + " \"name\" : \"scope-29\",\n" + " \"job\" : {\n" + " \"runtime\" : \"default\",\n" + " \"id\" : \"job_l...
4139627_0
class StartLetterCountMP implements Cloneable { @Override public StartLetterCountMP clone() throws CloneNotSupportedException { return (StartLetterCountMP)super.clone(); } @MessageHandler public LetterCount handleFirstCharacter(Letter letter); private StartLetterCountMP mp; } class StartLet...
StartLetterCountMP clone1 = mp.clone(); StartLetterCountMP clone2 = mp.clone(); Assert.assertNotNull(clone1); Assert.assertNotNull(clone2); Assert.assertNull(clone1.character); Assert.assertNull(clone2.character); clone1.character = new Character('T'); Assert.asse...
4167742_80
class DefaultValueChecker implements ValueChecker { @Override public AlertType checkValue(BigDecimal value, BigDecimal warn, BigDecimal error) { boolean isHighValueWorse = isTheValueBeingHighWorse(warn, error); if (isBeyondThreshold(value, error, isHighValueWorse)) { ...
assertThat(checker.checkValue(bd("0.16"), bd("0.15"), bd("0.20")), is(AlertType.WARN)); } }
4169493_3
class PreProcessMatrix { public void escapeColNames() throws Exception { ArrayList<String> newColNames = new ArrayList<String>(); for (String s : this.colNames) { newColNames.add(NameConvention.escapeEntityNameStrict(s)); this.colNames = newColNames; } } public PreProcessMatrix(File in); public v...
PreProcessMatrix pm = new PreProcessMatrix(this.testMatrix); pm.escapeColNames(); File result = pm.getResult(); String actual = readFile(result); String expected = "\tcol1\tcol2\tcol3\n"; expected += "234row1\tval1\tval2\tval3\n"; expected += "&row2\tval4\tval5\tval6\n"; expected += "678row3#\tval7\tval...
4180644_100
class HibernateDrugGroupDAO implements DrugGroupDAO { @Override public List<DrugGroup> getDrugGroupByName(String name) throws DAOException { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(DrugGroup.class); criteria.add(Restrictions.like("name", name)); criteria.add(Restrictions.like("ret...
String name = "TestDrugGroup1"; String result = dao.getDrugGroupByName(name).get(0).getName(); assertEquals(name, result); } }
4182801_87
class ConditionalConversion extends FormatConversionBase { @Override public int format(FormatterAPI formatter, Object value, Locale locale, String flags, int width, int precision, String formatString, int position) throws IOException { ensureNoWidth(width); ensureNoPrecision(precision); ...
assertThat(format(null, "[yes][no]"), is("no")); } }