id
stringlengths
7
14
source
stringlengths
135
41.2k
target
stringlengths
36
20.4k
11543457_128
class FeedLocationStore implements ConfigurationChangeListener { public static FeedLocationStore get(){ return instance; } private FeedLocationStore(); @Override public void onAdd(Entity entity); @Override public void onRemove(Entity entity); @Override public void onChange(Entity old...
Feed f1 = createFeed("f1SameLocations"); int initialSize = FeedLocationStore.get().store.getSize(); f1.getLocations().getLocations().add(createLocation(LocationType.DATA, "/projects/cas/data/hourly/2014/09/09/09")); f1.getLocations().getLocations().add(createLocation(Loca...
11543691_11
class SystemPropertiesConfig implements Config { @Override public List<Path> getClasspath() { String classpath = p.getProperty(CLASSPATH); if (classpath != null) { return parsePathList(classpath); } String classpathFile = p.getProperty(CLASSPATH_FILE); if (cl...
Path file = tempDir.newFile("classpath.txt").toPath(); Files.write(file, Arrays.asList("", "", "")); // empty lines are ignored systemProperties.setProperty(RetrolambdaApi.CLASSPATH_FILE, file.toString()); assertThat("zero values", config().getClasspath(), is(empty())); Files.w...
11558041_0
class MobileVideoService implements VideoService, Serializable { @Override public MobileSeries[] getAllSeries() throws VideoServiceException { try { return httpClient.get(new URL(MOBILE_URL + "keyword=index&d=" + idevice.getDeviceId()), MobileSeries[].class); } catch (MalformedURLException e) { throw ...
MobileSeries[] series = service.getAllSeries(); assertNotNull(series); } }
11566581_2
class MessageProducer extends CamundaBpmProducer { @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public void process(Exchange exchange) throws Exception { String processInstanceId = exchange.getProperty(EXCHANGE_HEADER_PROCESS_INSTANCE_ID, String.class); String businessKey = exch...
Exchange exchange = mock(Exchange.class); Message message = mock(Message.class); ExecutionQuery query = mock(ExecutionQuery.class); Execution execution = mock(Execution.class); when(exchange.getIn()).thenReturn(message); when(exchange.getProperty(eq(EXCHANGE_HEADER_PROCE...
11608365_5
class ResourceRegistrar { public static void unregister(XAResourceProducer producer) { final ProducerHolder holder = new ProducerHolder(producer); if (!resources.remove(holder)) { if (log.isDebugEnabled()) { log.debug("resource with uniqueName '{}' has not been registered", holder.getU...
assertEquals(1, ResourceRegistrar.getResourcesUniqueNames().size()); ResourceRegistrar.unregister(createMockProducer("xa-rp")); assertEquals(0, ResourceRegistrar.getResourcesUniqueNames().size()); } }
11613195_0
class ThumbnailsForCollectionAccessor extends ThumbnailsAccessor { public Map<String, String> getThumbnailsForCollection(int start, int limit, int errorHandlingPolicy) throws TechnicalRuntimeException, IOException, EuropeanaApiProblem { return getThumbnailsForCollection(CommonMetadata.EDM_FIELD_THUMBNAIL_LARGE,...
ThumbnailsForCollectionAccessor tca = new ThumbnailsForCollectionAccessor( TEST_COLLECTION_NAME); //201 = 2* 100 +1 int resultsSize = (2 * ThumbnailsAccessor.DEFAULT_BLOCKSIZE) + 1; //start at second page int startPosition = 0; Map<String, String> thumbnails = tca.getThumbnailsForCollection(startPosi...
11656984_397
class ActionRef { @Override public String toString() { return new StringBuilder().append(getClass().getSimpleName()) .append(" [path=") .append(path) .append(", cancel=") ...
assertEquals("ActionRef [path=path2, cancel=true, refs=[ActionRef [path=path, cancel=false, refs=[]]]]", actionRef2.toString()); } }
11662606_6
class StringUtils { public static String join(Collection<?> collection, String delimiter) { if (collection == null || collection.isEmpty()) { return EMPTY_STRING; } else if (delimiter == null) { delimiter = EMPTY_STRING; } StringBuilder builder = new String...
String string1 = "a"; String string2 = "story"; String string3 = "about"; String string4 = "tests"; String delim = "--"; ArrayList<String> strings = new ArrayList<String>(3); strings.add(string1); strings.add(string2); strings.add(string3); ...
11664357_10
class OSMWithTags { public static boolean isTrue(String tagValue) { return ("yes".equals(tagValue) || "1".equals(tagValue) || "true".equals(tagValue)); } public long getId(); public void setId(long id); public void addTag(OSMTag tag); public void addTag(String key, String value); p...
assertTrue(OSMWithTags.isTrue("yes")); assertTrue(OSMWithTags.isTrue("1")); assertTrue(OSMWithTags.isTrue("true")); assertFalse(OSMWithTags.isTrue("no")); assertFalse(OSMWithTags.isTrue("0")); assertFalse(OSMWithTags.isTrue("false")); assertFalse(OSMWithT...
11666990_3
class EndMeetingPageTransformer implements PageTransformer { @Override public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position < 0) { view.setAlpha(1 + position * 2); } else { view.setAlpha(1); view.set...
out.transformPage(mockView, 0); verify(mockView).setAlpha(1f); verify(mockView).setTranslationX(0.0f); verify(mockView).setScaleX(1f); verify(mockView).setScaleY(1f); } }
11668780_7
class ChangesDetector { public void newData(@Nonnull ChangesAdapter adapter, @Nonnull List<T> values, boolean force) { checkNotNull(adapter); checkNotNull(values); final ImmutableList<H> list = FluentIterable.from(values) .tra...
mDetector.newData(mAdapter, ImmutableList.of(new Cat(2, "two")), false); reset(mAdapter); mDetector.newData(mAdapter, ImmutableList.of(new Cat(1, "one"), new Cat(2, "two")), false); verify(mAdapter).notifyItemRangeInserted(0, 1); } }
11694419_2
class KettleControlBolt extends BaseRichBolt { @Override public void cleanup() { super.cleanup(); notifier.cleanup(); } public KettleControlBolt(String transformationName, Notifier notifier, Set<String> leafSteps); @SuppressWarnings("rawtypes") @Override public void prepare(Map stormConf, To...
KettleControlBolt bolt = new KettleControlBolt(TRANS_NAME, notifier, Collections.singleton(STEP_1)); notifier.cleanup(); EasyMock.expectLastCall(); control.replay(); bolt.cleanup(); control.verify(); } }
11700816_3
class ExampleDataloader implements TGDatasetInterface { @Override public boolean Validator(File file) throws FileNotFoundException, IOException, IllegalAccessException, InstantiationException { // Write your own elaborate validator to see if your LoadFile routine can deal with it String ext = g...
System.out.println("Validator"); ExampleDataloader instance = new ExampleDataloader(); boolean expResult = true; boolean result = instance.Validator(testFile); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. ...
11711223_9
class StringUtil { private static String splitLine(String str, final int col) { if (str.length() < col) { return str; } // scan from `col` to left for (int i = col - 1; i > 0; i--) { if (str.charAt(i) == ' ') { return str.substring(0, i) + "\...
String longLine = "http://www.kframework.org should be splitted"; Assert.assertEquals( "http://www.kframework.org\nshould be\nsplitted", StringUtil.splitLines(longLine, 10)); Assert.assertEquals( "http://www.kframework.org\nshould be splitted", ...
11719739_6
class ResourceFinder { public URL findResource(String resource) throws MojoFailureException { URL res = null; // first search relatively to the base directory try { final Path p = basedir.resolve(resource); res = toURL(p.toAbsolutePath()); } catch (final Inv...
assertNotNull(finder.findResource("test.txt")); } }
11724937_0
class FiberKafkaProducer implements Producer<K, V> { @Override public Future<RecordMetadata> send(ProducerRecord<K, V> record) { return send(record, null); } public FiberKafkaProducer(Producer<K, V> producer); @Override public Future<RecordMetadata> send(ProducerRecord<K, V> record, Call...
Fiber<Void> fiber = new Fiber<>(new SuspendableRunnable() { @Override public void run() throws SuspendExecution, InterruptedException { Future<RecordMetadata> f = fiberProducer.send(new ProducerRecord<>("Topic", "Key".getBytes(), "Value".getBytes())); Futu...
11736323_36
class TypedMap implements Map<String, Object> { public void putAll(Map<? extends String, ? extends Object> arg0) { inner.putAll(convertToTypedObjects(arg0)); } public TypedMap(final RecordType type); public TypedMap(final RecordType type, final Map<? extends String, ? extends Obj...
Map<String, Object> values = new HashMap<String, Object>(); values.put("intValue", 1); values.put("booleanValue", true); String[] stringArray = new String[] { "a", "b", "c" }; values.put("stringArray", stringArray); TypedMap map = new TypedMap(recordType, values); ...
11738699_2
class TimeGenerator implements Runnable { public void stop() { // AstericsErrorHandling.instance.getLogger().fine("Invoking thread // <"+Thread.currentThread().getName()+">, : .stop called"); if (runningTaskFuture != null && !runningTaskFuture.isDone()) { runningTaskFuture.canc...
// fail("Not yet implemented"); } }
11754395_21
class DefaultWhenHttpClient implements WhenHttpClient { @Override public Promise<HttpClientResponseAndBody> requestAbsAndReadBody(HttpMethod method, String absoluteURI) { return requestAbsAndReadBody(method, absoluteURI, null); } @Inject public DefaultWhenHttpClient(Vertx vertx, When when); ...
Promise<HttpClientResponseAndBody> p = whenHttpClient.requestAbsAndReadBody(HttpMethod.GET, absoluteURI); verify(client).requestAbs(any(), eq(absoluteURI)); verifyResponseAndBody(p); } }
11765760_0
class PullRequestChainParser { public void parsePullRequestChains(PullRequests<? extends PullRequest> pullRequests) { Map<String, PullRequest> pullRequestsMap = Maps.newHashMap(); for (PullRequest pullRequest : pullRequests.getPullRequests()) { pullRequestsMap.put(pullRequest.getSource(...
BitbucketPullRequest firstPr = createPr("a", "master"); BitbucketPullRequest secondPr = createPr("b", "a"); BitbucketPullRequests pullRequests = new BitbucketPullRequests(); pullRequests.setPullRequests(asList(secondPr, firstPr)); parser.parsePullRequestChains(pullRequests); ...
11797725_37
class AbstractSessionHandler extends MessageToMessageCodec<FixMessage, FixMessageBuilder> { @Override public void channelInactive(ChannelHandlerContext ctx) { Attribute<FixSession> fixSessionAttribute = ctx.channel().attr(FIX_SESSION_KEY); if (fixSessionAttribute != null) { FixSessi...
when(channel.attr(AbstractSessionHandler.FIX_SESSION_KEY)).thenReturn(null); sessionHandler.channelInactive(ctx); verify(ctx, never()).fireChannelRead(any(LogoutEvent.class)); } }
11799054_68
class HeaderParser { protected static int readAfterString(byte[] header, int off) { int start = readToString(header, off); int len = header[start + 2] & 0xFF; return start + len*2 + 3; } public static CustomHeader parse(File map); public static CustomHeader parse(byte[] map); ...
int expected = -1; int actual = HeaderParser.readAfterString(inputString, 15, "PlayerData"); assertEquals(expected, actual); } }
11816589_0
class Main { void execute() { System.out.println(message); } public Main(String message); public static void main(String args[]); } class MainTest { @Test public void testPrintMessage() {
ByteArrayOutputStream binary = new ByteArrayOutputStream(); PrintStream stream = new PrintStream(binary, true); PrintStream defaultStream = System.out; try { System.setOut(stream); new Main("message").execute(); assertThat(binary.toString(), is("messag...
11851236_37
class ApnsClient { public CompletableFuture<Void> close() { log.info("Shutting down."); final CompletableFuture<Void> closeFuture; if (this.isClosed.compareAndSet(false, true)) { closeFuture = new CompletableFuture<>(); this.channelPool.close().addListener((Generi...
final ApnsClient managedGroupClient = new ApnsClientBuilder() .setApnsServer(HOST, PORT) .setSigningKey(this.signingKey) .build(); assertDoesNotThrow(() -> managedGroupClient.close().get()); } }
11880356_8
class DbfRow { public float getFloat(String fieldName) throws DbfException { return getNumber(fieldName).floatValue(); } public DbfRow(DbfHeader header, Charset defaultCharset, Object[] row); public BigDecimal getBigDecimal(String fieldName); public Date getDate(String fieldName); pu...
float value = 10.004f; DbfRow dbfRow = createRow(null, value); assertEquals(0, dbfRow.getFloat(COLUMN_1), 0.5); assertEquals(value, dbfRow.getFloat(COLUMN_2), 0.5); } }
11896265_5
class CpkApi { @GET @Path( "/default" ) public Response defaultElement() throws IOException { IElement defaultElement = coreService.getDefaultElement(); if ( defaultElement != null ) { try { String url = defaultElement.getPluginId() + API_ROOT + defaultElement.getId(); return CpkUti...
when( cpkApi.coreService.getDefaultElement() ).thenReturn( null ); Response responseResult = null; try { responseResult = cpkApi.defaultElement(); assertEquals( Response.Status.OK.getStatusCode(), responseResult.getStatus() ); assertEquals( cpkApi.DEFAULT_NO_DASHBOARD_MESSAGE, new String( ...
11904180_16
class JDBCFactory { public Scheme createScheme( String format, Fields fields, Properties properties ) { LOG.info( "creating {} format with properties {} and fields {}", format, properties, fields ); String selectQuery = properties.getProperty( FORMAT_SELECT_QUERY ); String countQuery = properties....
JDBCFactory factory = new JDBCFactory(); Fields fields = new Fields( "one", "two", "three" ); Properties schemeProperties = new Properties(); schemeProperties.setProperty( JDBCFactory.FORMAT_COLUMNS, "one:two:three" ); schemeProperties.setProperty( JDBCFactory.FORMAT_SELECT_QUERY, "select one, two,...
11916042_2
class DistributionPomPatcher implements DepgraphPatcher { @Override public void patch( final DiscoveryResult orig, final List<? extends Location> locations, final Map<String, Object> context ) { final DiscoveryResult result = orig; final ProjectVersionRef ref = result...
final Location location = new SimpleLocation( "test-repo", "http://www.nowhere.com/path/to/repo" ); final ProjectVersionRef pvr = new SimpleProjectVersionRef( "group.id", "artifact-id", "1" ); final String pom = BASE + "in-profile-root-provided-dep.pom.xml"; final TestDownload download ...
11943595_64
class MutableSchema extends AbstractSchema implements Serializable, Schema { public MutableSchema addTable(Table table) { _tables.add(table); return this; } public MutableSchema(); public MutableSchema(String name); public MutableSchema(String name, Table... tables); @Override public String getName();...
MutableSchema schema1 = new MutableSchema("foo"); MutableSchema schema2 = new MutableSchema("foo"); assertTrue(schema1.equals(schema2)); assertTrue(schema1.hashCode() == schema2.hashCode()); schema2.addTable(new MutableTable("foo")); assertFalse(schema1.equals(schema2))...
11971122_38
class CoreDepthFirstVoidVisitor extends DepthFirstVoidVisitor { public PaaSInstance getPaaSInstance() { return paaSInstance; } public ApplicationInstance getApplicationInstance(); public UserInstance getUserInstance(); @Override public void visit(ApplicationProfile n); @Override public...
InputStream is = readFile("paasProfile.txt"); cpp.ReInit(is); CoreDepthFirstVoidVisitor visitor = null; try { Scope scope = cpp.Scope(); visitor = new CoreDepthFirstVoidVisitor(); scope.accept(visitor); } catch (Exception e) { ...
11974846_4
class AccessController extends BaseRegionObserver implements MasterObserver, RegionServerObserver, AccessControllerProtocol { @Override public void preModifyColumn(ObserverContext<MasterCoprocessorEnvironment> c, byte[] tableName, HColumnDescriptor descriptor) throws IOException { requirePermission("modi...
final HColumnDescriptor hcd = new HColumnDescriptor(TEST_FAMILY); hcd.setMaxVersions(10); PrivilegedExceptionAction action = new PrivilegedExceptionAction() { public Object run() throws Exception { ACCESS_CONTROLLER.preModifyColumn(ObserverContext.createAndPrepare(CP_ENV, null), TEST...
11992364_6
class FieldInfoResolver { static String cutFieldName(final String string, final int from) { final int nextIndex = from + 1; final int len = string.length(); if (len > nextIndex) { char c = string.charAt(nextIndex); if (c >= 'A' && c <= 'Z') { return s...
assertEquals("a", FieldInfoResolver.cutFieldName("getA", 3)); assertEquals("ab", FieldInfoResolver.cutFieldName("getAb", 3)); assertEquals("AB", FieldInfoResolver.cutFieldName("getAB", 3)); assertEquals("ABc", FieldInfoResolver.cutFieldName("getABc", 3)); assertEquals("ABC", Fiel...
12002935_3
class XmlHelper { protected void applyModifications(Element modificationsRoot, Element targetRoot) { for(Object object : modificationsRoot.elements()){ if(object instanceof Element){ Element modificationElement = (Element) object; String copy = modificationElemen...
Element modificationsRoot = new DefaultElement("project"); Element targetRoot = new DefaultElement("project"); Document target = DocumentFactory.getInstance().createDocument(targetRoot); Document modifications = DocumentFactory.getInstance().createDocument(modificationsRoot); E...
12006992_3
class TrezorMessageUtils { public static TrezorMessage.TxInput newTxInput(Transaction tx, int index) { Preconditions.checkNotNull(tx, "Transaction must be present"); Preconditions.checkElementIndex(index, tx.getInputs().size(), "TransactionInput not present at index " + index); // Input index is valid ...
// Arrange Address ourReceivingAddress = FakeTransactions.getElectrumAddressN(new int[] {0,0}); Address ourChangeAddress = FakeTransactions.getElectrumAddressN(new int[] {0,1}); Address random2Address = FakeTransactions.asMainNetAddress("1MKw8vWxvBnaBcrL2yXvZceqyRMoeG2kRn"); // Build a fake transa...
12046384_0
class ProductCategoryEnricher { public Tuple enrichEvent(Tuple event) { if ("PRODUCT".equals(event.getString("type"))) { List<String> names = new ArrayList<>(event.getFieldNames()); List<Object> values = new ArrayList(event.getValues()); names.add("category"); values.add(getCategory(event.getString("pro...
String event = "{\"user\":\"60571253-8315-40ff-8142-f8d68f9d35f0\",\"product\":\"15\",\"type\":\"PRODUCT\"}"; Tuple enrichedEvent = productCategoryEnricher.enrichEvent(TupleBuilder.fromString(event)); assertEquals("Covers", enrichedEvent.getString("category")); } }
12057541_2
class KoreanCharacterTokenizer extends Tokenizer { @Override public final boolean incrementToken() throws IOException { clearAttributes(); logger.debug("incrementToken"); int length = 0; int start = -1; // this variable is always initialized int end = -1; char[] buffer = termAtt.buffer(); while (...
CharTermAttribute charTermAtt = tokenizer.getAttribute(CharTermAttribute.class); OffsetAttribute offSetAtt = tokenizer.getAttribute(OffsetAttribute.class); while(tokenizer.incrementToken()) { TestToken t = getToken(charTermAtt.toString(), offSetAtt.startOffset(), offSetAtt.endOffset()); System.out.printl...
12067623_0
class MultiplicationOperation implements Operation { @Override public int calculate(int a, int b) { return a * b; } @Override public String name(); } class MultiplicationOperationTest { @Test public void testModulus() {
Operation op = new MultiplicationOperation(); assertThat(op.calculate(5, 2)).isEqualTo(10); assertThat(op.calculate(10, 5)).isEqualTo(50); assertThat(op.calculate(4, 2)).isEqualTo(8); } }
12117077_49
class Carto { public static Style parse(Object css) throws IOException { Reader reader = Convert.toReader(css).get("Unable to handle input: " + css); return new CartoParser().parse(reader); } } class CartoTest { @Test public void testAttachment() throws Exception {
String css = " #states::glow {"+ " polygon-fill: #888888;"+ " polygon-opacity: 0.25;"+ " comp-op: dst;"+ " }"; Style result = Carto.parse(css); Rule r = result.getRules().get(0); assertEquals(new RGB("#888...
12151814_1
class EnumHelper { @SuppressWarnings("unchecked") public static <E extends Enum<? extends Style.HasCssName>> E fromStyleName(final String styleName, final Class<E> enumClass, ...
assertThat(fromStyleName("123 pull-left abc", Pull.class, null), is(Pull.LEFT)); assertThat(fromStyleName("123 pull-right abc", Pull.class, null), is(Pull.RIGHT)); assertThat(fromStyleName("pull-left pull-right abc", Pull.class, null), is(Pull.LEFT)); assertThat(fromStyleName("123 abc", ...
12246820_18
class DelegatingContentHandlerImpl implements FileContentReferenceHandler { @Override public long putFile(File sourceFile, ContentReference targetContentReference) throws ContentIOException { ContentReferenceHandler delegate = getDelegate(targetContentReference); return delegate.putFile(sou...
File sourceFile = new File(this.getClass().getResource( "/content-handler-a/file-a-1.txt").toURI()); String targetFolder = "/content-handler-a"; ContentReference targetContentReference = getTextReference(targetFolder); targetContentReference.setUri(targetContentReference...
12250309_0
class LDAPManager { public void startServer() throws LDAPException { logger.info("Starting LDAP Server Configuration."); File installFile = new File(dataPath); installDir = installFile.getAbsolutePath(); boolean isFreshInstall; if (installFile.exists()) { isFresh...
logger.info("Testing starting and stopping server."); BundleContext mockContext = createMockContext(new File(TMP_FOLDER_NAME)); LDAPManager manager = new LDAPManager(mockContext); HashMap config = new HashMap(); config.put("admin.port", AvailablePortFinder.getNextAvailable()); ...
12255838_2
class GuiceVerticleFactory implements VerticleFactory { public GuiceVerticleFactory setInjector(Injector injector) { this.injector = injector; return this; } public Injector getInjector(); @Override public String prefix(); @Override public Verticle createVerticle(String verticleNam...
assertNull(factory.getInjector()); Injector injector = mock(Injector.class); factory.setInjector(injector); assertEquals(injector, factory.getInjector()); } }
12299144_16
class RepositoryUserDetailsService implements UserDetailsService { @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { LOGGER.debug("Loading user by username: {}", username); User user = repository.findByEmail(username); LOGGER.debug("Fou...
when(repositoryMock.findByEmail(EMAIL)).thenReturn(null); catchException(service).loadUserByUsername(EMAIL); Assertions.assertThat(caughtException()) .isExactlyInstanceOf(UsernameNotFoundException.class) .hasMessage("No user found with username: " + EMAIL) ...
12299794_3
class UrlUtils { public static String combine(final String... parts) { final StringBuilder sb = new StringBuilder(); for (final String part : parts) { if (isHttpUrl(part) || isHttpsUrl(part)) { sb.setLength(0); } else if (!part.startsWith("/")) { ...
final String result = UrlUtils.combine("http://example.com", "/a", "http://test.com", "b/"); assertThat(result).as("Combined Url").isEqualTo("http://test.com/b"); } }
12304596_1
class TemplateEngineRythm implements TemplateEngine { @Override @SuppressWarnings("unchecked") public void invoke(Context context, Result result) { Object object = result.getRenderable(); ResponseStreams responseStreams = context.finalizeHeaders(result); Map map; // if th...
Properties p = new Properties(); p.setProperty("key", "value"); when(ninjaProperties.getAllCurrentNinjaProperties()).thenReturn(p); TemplateEngineRythm rythm = new TemplateEngineRythm(messages, lang, ninjaLogger, exceptionHandler, rythmHelper, templateEng...
12319410_2
class EsMarshalling { public static XContentBuilder marshall(PoliciesBean bean) throws StorageException { try (XContentBuilder builder = XContentFactory.jsonBuilder()) { preMarshall(bean); builder .startObject() .field("organizationId", bean.getOr...
GatewayBean bean = createBean(GatewayBean.class); XContentBuilder builder = EsMarshalling.marshall(bean); Assert.assertEquals("{\"id\":\"ID\",\"name\":\"NAME\",\"description\":\"DESCRIPTION\",\"type\":\"REST\",\"configuration\":\"CONFIGURATION\",\"createdBy\":\"CREATEDBY\",\"createdOn\":1,\"modi...
12343833_0
class PropertyUtils { @SuppressWarnings("unchecked") public static <T> T transform(Class<T> type, String value) throws IllegalArgumentException { if (!VALUE_TRANSFORMER.containsKey(type)) { throw new IllegalArgumentException("unsupported parameter type: " + type); } // since...
Object result = transform(type, val); assertTrue(type.isAssignableFrom(result.getClass())); } }
12473833_38
class Utils { public static int myBinarySearch(int[] indices, int key, int begin, int end) { if (indices.length == 0 || begin == end) { return -1; } end--; int mid = begin; while (begin <= end) { mid = (end + begin) >> 1; if (i...
System.out.println("binarySearch"); int[] index = {10, 13, 15, 17, 19}; int key = 25; int begin = 0; int end = 5; int expResult = -6; int result = Utils.myBinarySearch(index, key, begin, end); assertEquals(expResult, result); } }
12485907_12
class MessageParser { public static String normalizeSubject(String subject) { String s = subject; if (s != null) { s = s.replaceAll("\\[.*?\\][^$]","") // remove any brackets at the beginning except the one having end of line after the "]" .replaceAll("^\\s*(-*\\s*[...
assertEquals("Test subject", MessageParser.normalizeSubject(" [] [x x] Re: Vor: Test RE: subject ")); assertEquals("Test subject", MessageParser.normalizeSubject(" Re: Fw: [] [x x] Test RE: [x] [] subject ")); assertEquals("Web Container Integration testing (WCI)", MessageParser.normalizeSubjec...
12488647_6
class Utils { public static String implode(String separator, List<String> elements){ StringBuffer s = new StringBuffer(); for(int i = 0; i < elements.size(); i++){ if(i > 0){ s.append(" "); } s.append(elements.get(i)); } return s.t...
final String separator = "Bar"; final List<String> elements = new ArrayList<String>(); assertEquals("", Utils.implode(separator, elements)); elements.add("foo"); elements.add("bar"); assertEquals("foo bar", Utils.implode(separator, elements)); } }
12497963_1
class MaxStepCriteria implements IBreakCriteria { @Override public boolean shouldBreak(IHierarchicalNodeLayout layout) { if(layout.getDelegate()==null) // TODO : do not point on delegate but on MultiStepLayout.getCounter return false; if(layout.getDelegate().getCounter()>ma...
IHierarchicalNodeLayout mockLayout = mockLayoutCounter(3); MaxStepCriteria c = new MaxStepCriteria(2); Assert.assertFalse(c.shouldBreak(mockLayout)); // non : 0 > 2 Assert.assertFalse(c.shouldBreak(mockLayout)); // non : 1 > 2 Assert.assertFalse(c.shouldBreak(mockLayout)...
12506813_0
class BM25FQuery extends DisjunctionMaxQuery { public BM25FQuery( Collection<Query> perFieldQueries, Map<String, Float> fieldWeights, Map<String, Float> normFactors) { super(perFieldQueries, 0.0f); this.fieldWeights = fieldWeights; this.normFactors = normFactors; } public BM25FQue...
Directory index = new RAMDirectory(); StandardAnalyzer analyzer = new StandardAnalyzer(); IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_4_10_4, analyzer); IndexWriter w = new IndexWriter(index, config); w.addDocument( doc( 0, "CNT-infused fiber as a ...
12508001_17
class QueuedVCatRenderer implements IVCatRenderer<W> { @Override public RenderedFileInfo render(final AbstractAllParams<W> all) throws VCatException { // Build a Job instance for the parameters. final String jobId = HashHelper.sha256Hex(all.getCombined()); Object lock; // Synchronized to jobs, as all code ...
// Use an artifical delay in the test renderer and try to render 100 times at the same time. // testRenderer.createGraphFile(...) should only be called once. testRenderer.setDelay(1000); TestAllParams params = new TestAllParams(); for (int i = 0; i < 99; i++) { new Thread(() -> { try { underTes...
12520014_8
class SqliteUtil { public static Boolean toBoolean(Integer intValue) { if (intValue == null) { return null; } if (FALSE.equals(intValue)) { return Boolean.FALSE; } return Boolean.TRUE; } private SqliteUtil(); public static void putIfNot...
assertEquals(Boolean.TRUE, SqliteUtil.toBoolean(-1)); } }
12544638_6
class PathBuilder { public static ClassPath buildDefaultClassPath (Application app) { LinkedHashSet<File> classPathEntries = new LinkedHashSet<File>(); for (Resource resource : app.getActiveCodeResources()) { classPathEntries.add(resource.getFinalTarget()); } addClas...
ClassPath classPath = PathBuilder.buildDefaultClassPath(_application); String expectedClassPath = _firstJarFile.getAbsolutePath() + File.pathSeparator + _secondJarFile.getAbsolutePath(); assertEquals(expectedClassPath, classPath.asArgumentString()); } }
12555873_41
class FilterResolver { public boolean hasInsituFilter() { return parameters.getInsitu() != null; } public FilterResolver(IoParameters parameters); boolean shallBehaveBackwardsCompatible(); public boolean hasMobileFilter(); public boolean isMobileFilter(); public boolean isInsitu...
FilterResolver resolver = createResolver(createDefaults()); Assertions.assertFalse(resolver.hasInsituFilter()); } }
12561697_1
class Kelly { private void reloadCacheEntry(CacheEntry cacheEntry) throws ExecutionException, InterruptedException { LoaderCallable<T> loaderCallable = new LoaderCallable<T>(this, cacheProvider, cacheLoader, cacheEntry); executorService.submit(loaderCallable); } @Deprecated public Kelly(C...
CacheProvider<String> cacheProvider = Mockito.mock(CacheProvider.class); CacheLoader<String> cacheLoader = Mockito.mock(CacheLoader.class); CacheEntry<String> cacheEntry = new CacheEntry<String>("dude", "suman karthik", 1); CacheEntry<String> cacheEntry1 = new CacheEntry<String>("dude"...
12578911_0
class BeetlUtil { public static boolean checkNameing(String str) { char[] commonArray = new char[str.length()]; int len = 0; if (str == null || (len = str.length()) == 0) { return false; } str.getChars(0, len, commonArray, 0); int index = 0; char word = commonArray[index++]; //首字母判断 不为数字 , . ...
// for (int i = 0; i < 1000000; i++) { // Assert.assertTrue(condition); // Assert.assertTrue("checkNameing错误,验证:小写字母",BeetlUtil.checkNameing("abcdefghijklmnopqrstuvwxyz")); // Assert.assertTrue("checkNameing错误,验证:大写字母",BeetlUtil.checkNameing("ABCDEFGHIJKLMNOPQRSTUVWXYZ")); // Assert.assertTrue("checkNameing错误,...
12587918_4
class ByteArrayDiffs { public static byte[] undo(byte[] target, byte[] diff) { MemoryDiff md = Serials.deserialize(DefaultSerialization.newInstance(), MemoryDiff.class, diff); return Diffs.apply(new UndoOpQueue(md.queue()), target); } private ByteArrayDiffs(); public static byte[] diff(byte[] orig, byte[] t...
byte[] orig = "Hello World".getBytes(); byte[] target = "Hellish Cruel World".getBytes(); byte[] diff = ByteArrayDiffs.diff(orig, target); byte[] undone = ByteArrayDiffs.undo(target, diff); Assert.assertTrue(Arrays.equals(orig, undone)); } }
12590126_3
class LoggableThreading { @Loggable(Loggable.DEBUG) public int foo() { return 1; } } class LoggableThreadingTest { @Test public void loggableThreadTerminates() throws Exception {
new LoggableThreading().foo(); Thread thread = null; final Set<Thread> keys = Thread.getAllStackTraces().keySet(); final Thread[] threads = keys.toArray(new Thread[keys.size()]); for (int idx = 0; idx < threads.length; idx++) { if (threads[idx].getName().equals("jcabi...
12593159_0
class HttpClientController { public Author getAuthorByURL(String link, Author a) throws IOException, SamlibParseException, SamlibInterruptException { a.setUrl(link); String str = getURL(mSamLibConfig.getAuthorIndexDate(a), new StringReader()); parseAuthorIndexDateData(a, str); ret...
Author author= new Author(); author=httpClientController.getAuthorByURL(AUTHOR_URI,author); assertTrue(author.getBooks().size()>0); assertTrue(author.getGroupBooks().size()>0); } }
12652086_0
class Time implements Comparable<Time> { public static Time fromMillis(long timeInMillis) { int secs = (int) (timeInMillis / 1000); int nsecs = (int) (timeInMillis % 1000) * 1000000; return new Time(secs, nsecs); } public Time(); public Time(int secs, int nsecs); public Time(double secs); p...
assertEquals(new Time(0, 0), Time.fromMillis(0)); assertEquals(new Time(0, 1000000), Time.fromMillis(1)); assertEquals(new Time(1, 0), Time.fromMillis(1000)); assertEquals(new Time(10, 0), Time.fromMillis(10000)); assertEquals(new Time(1, 1000000), Time.fromMillis(1001)); assertEquals(new Time(1...
12652338_12
class OrderCalc { public long getPriceWithVAT(LineItem lineItem) { CalcLineItem calcLineItem = new CalcLineItem(lineItem); return getCalc().getPriceWithVat(calcLineItem).getCents(); } public OrderCalc(Order order); private Calc getCalc(); private static long sumOfAdjustments(Collection<Discount> d...
//no tax rate LineItem lineItem = new LineItem(); lineItem.setPrice(350L); assertEquals(350L, orderCalc.getPriceWithVAT(lineItem)); } }
12686435_0
class ProxyServer { public FutureTask<ProxyServer> run() { FutureTask<ProxyServer> future = new FutureTask<>(new Callable<ProxyServer>() { @Override public ProxyServer call() throws Exception { // Configure the server. bootstrap = new ServerBootstrap...
proxyServer = new ProxyServer(9090).run().get(); assertTrue(proxyServer != null); } }
12768312_22
class EventsIterator implements Iterator<Serializable> { @Override public boolean hasNext() { return it != null; } public EventsIterator(Iterator<T> cit); private void advance(); @Override public Serializable next(); @Override public void remove(); } class EventsIteratorTest { ...
List<ChangeSet> lcs = new ArrayList<>(); for (int i = 0; i < 10; i++) { List<Integer> data = TestUtils.randomdata(0); assertEquals(data.size(), 0); ChangeSet cs = new DefaultChangeSet("BUCKET", "STREAM", 0, UUID.randomUUID().toString(), data); } Events...
12796207_5
class History implements Iterable<Object> { @NonNull public static Builder emptyBuilder() { return new Builder(Collections.emptyList()); } private History(List<Object> history); @NonNull public static History single(@NonNull Object key); private static Iterator<T> iterateFromBottom(List<Object> histor...
try { History.emptyBuilder().pop(); fail("Should throw"); } catch (IllegalStateException e) { // pass } } }
12796568_15
class Pair { public String getKey() { return key; } public Pair(final String key, final String value); public String getValue(); @Override public String toString(); Pair pair; } class PairTest { Pair pair; @Test public void testGetKey() {
assertEquals("key", pair.getKey()); } }
12812578_34
class DependencyUtils { public static boolean hasDependency(final PluginContext context, final EssentialsDependency dependency) { final TargetPom targetPom = dependency.getDependencyTargetPom(); if (targetPom == TargetPom.INVALID) { return false; } final Model model = Pr...
final EssentialsDependency dependency = new DependencyRestful(); dependency.setTargetPom("cms"); dependency.setArtifactId("hippo-plugins-shared"); dependency.setVersion("1.01.00-SNAPSHOT"); dependency.setGroupId("org.onehippo.cms7.essentials"); assertEquals(TargetPom.CMS...
12847265_23
class MeteredStaticMethodWithExceptions { @ExceptionMetered(name = "illegalArgumentExceptionMeteredStaticMethod", cause = IllegalArgumentException.class) public static void illegalArgumentExceptionMeteredStaticMethod(Runnable runnable) { runnable.run(); } @ExceptionMetered(name = "exceptionMet...
final RuntimeException exception = new IllegalStateException("message"); Runnable runnableThatThrowsIllegalStateException = new Runnable() { @Override public void run() { throw exception; } }; // Call the metered method and assert it h...
12854207_1
class DBToolsInit { public void initDBTools(String schemaDir) { DBToolsFiles.copyXsdFileToSchemaDir(schemaDir); DBToolsFiles.copySampleSchemaFileToSchemaDir(schemaDir); } } class DBToolsInitTest { @Test public void testInitDBTools() throws Exception {
String userDir = System.getProperty("user.dir"); String databaseSchemaDir = userDir + "/build/test-src/src/main/database"; DBToolsInit init = new DBToolsInit(); init.initDBTools(databaseSchemaDir); assertTrue("schema.xml exists", new File(databaseSchemaDir, "schema.xml").exists...
12918104_20
class Git { public static String clone(String URL) throws Exception { File tempDirectory = new File(Configuration.getTemporaryDirectory() + "/" + Calendar.getInstance().getTime().getTime() + ""); Main.printLine("[Info] Cloning from \"" +URL+ "\""); ProcessBuilder builder = new ProcessBuilder("git","clone", U...
boolean exceptionThrown = false; try { Git.clone("https://github.com/non-existing-git-repo"); } catch (Exception e) { exceptionThrown = true; } assertTrue(exceptionThrown); } }
12939200_53
class Log4JLogger extends AbstractInternalLogger { public void debug(String msg) { logger.debug(msg); } Log4JLogger(Logger logger); public void debug(String msg, Throwable cause); public void error(String msg); public void error(String msg, Throwable cause); public void info(Str...
Logger mock = createStrictMock(Logger.class); mock.debug("a", e); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.debug("a", e); verify(mock); } }
12953256_122
class LongUtils { public static int unionSize(LongSortedSet a, LongSortedSet b) { return a.size() + b.size() - intersectSize(a, b); } private LongUtils(); public static Long2DoubleSortedMap frozenMap(Map<Long,Double> map); public static LongSortedSet frozenSet(Collection<Long> longs); ...
assertThat(unionSize(LongSortedSets.EMPTY_SET, LongSortedSets.EMPTY_SET), equalTo(0)); } }
12959153_0
class TagTokenizer implements Tokenizer { @Override @NonNull public List<Range> findTokenRanges(CharSequence charSequence, int start, int end) { ArrayList<Range>result = new ArrayList<>(); if (start == end) { //Can't have a 0 length token return result; } ...
String test = "@bears #tokens"; List<Range> ranges = tokenizer.findTokenRanges(test, 0, test.length()); assertEquals(Arrays.asList(new Range(0, 6), new Range(7, 14)), ranges); assertEquals("@bears", test.substring(ranges.get(0).start, ranges.get(0).end)); assertEquals("#tokens", ...
12960439_18
class RedundancyCalculator { public ImmutableList<TransferSegment> createStateList(Layout layout, long trimMark) { return layout.getSegments() .stream() // Keep all the segments after the trim mark, except the open one. .filter(segment -> segment.getEnd() != ...
RedundancyCalculator redundancyCalculator = new RedundancyCalculator("localhost"); Layout layout = createNonPresentLayout(); // node is not present anywhere, trim mark starts from the middle of a second segment -> // transfer half of second and third segments Im...
12962336_18
class TransactionResult implements Comparable<TransactionResult> { public static TransactionResult fromJSON(JSONObject json) { boolean binary; String metaKey = json.has("meta") ? "meta" : "metaData"; String txKey = json.has("transaction") ? "transaction" : json.has(...
TransactionResult tr = TransactionResult.fromJSON(request_tx_binary_result); assertHelper(tr); tr = new TransactionResult(request_tx_binary_result, Source.request_tx_binary); assertHelper(tr); } }
12963511_14
class Jose4jJWTService implements JWTService { @Override public String encode( String jti, String issuer, String subject, Date currentTime, String method, String path, String contentHashAlgorithm, String contentHash ) throws JWTError { JwtClaims jwtClaims = new JwtClaims(); jwtC...
Map<String, Object> expected = new HashMap<>(); expected.put("jti", "Expected JTI"); expected.put("iss", ENTITY_IDENTIFIER); expected.put("sub", null); expected.put("aud", PLATFORM_IDENTIFIER); expected.put("iat", Long.valueOf(platformDate.getTime() / 1000)); exp...
12974177_0
class AffinityLock implements Closeable { @NotNull public static String dumpLocks() { return LOCK_INVENTORY.dumpLocks(); } AffinityLock(int cpuId, boolean base, boolean reservable, LockInventory lockInventory); public static void cpuLayout(@NotNull CpuLayout cpuLayout); @NotNull pub...
LockInventory lockInventory = new LockInventory(VanillaCpuLayout.fromCpuInfo("i7.cpuinfo")); AffinityLock[] locks = { new AffinityLock(0, true, false, lockInventory), new AffinityLock(1, false, false, lockInventory), new AffinityLock(2, false, true, lockIn...
12983151_0
class FS20CommandHelper { public static FS20Command convertHABCommandToFS20Command(Command command) { if (command instanceof UpDownType) { return convertUpDownType((UpDownType) command); } else if (command instanceof OnOffType) { return convertOnOffType((OnOffType) command);...
Command command = new PercentType(80); FS20Command fs20Command = FS20CommandHelper.convertHABCommandToFS20Command(command); // Test for issue: FS20 - Converting Value to raw-message fails #1635 // see: https://github.com/openhab/openhab/issues/1635 assertNotEquals(fs20Command, FS20Command.UNKNOWN); asser...
13028147_119
class ValidationResult { public void assertOk() { if (hasErrors()) { throw new MrrtReportTemplateValidationException(this); } } public ValidationResult(); public List<ValidationError> getErrors(); public void addError(String description, String messageCode); publi...
expectedException.expect(MrrtReportTemplateValidationException.class); validationResultWithErrors.assertOk(); } }
13062062_215
class ExtractOptionsPane extends HBox implements TaskParametersBuildStep<ExtractParametersBuilder>, RestorableView, ResettableView { @Override public void restoreStateFrom(Map<String, String> data) { field.setText(Optional.ofNullable(data.get("pages")).orElse(EMPTY)); } ExtractOptionsPane();...
Map<String, String> data = new HashMap<>(); data.put("pages", "100"); WaitForAsyncUtils.waitForAsyncFx(2000, () -> victim.restoreStateFrom(data)); ValidableTextField field = lookup("#extractRanges").queryAs(ValidableTextField.class); assertEquals("100", field.getText()); } }
13073335_8
class OperatorFormatter { public String formatCondition( Operator op, String objectName, String value, boolean parameterized ) { if ( parameterized ) { value = "[param:" + value.replaceAll( "[\\{\\}]", "" ) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } else if ( op == Operator.IN ) {...
final OperatorFormatter f = new OperatorFormatter(); final String objectName = "[CAT.COL]"; //$NON-NLS-1$ String formatted = f.formatCondition( Operator.IN, objectName, "2| \"value\" ", false ); //$NON-NLS-1$ Assert.assertEquals( "IN([CAT.COL];\"2\";\"value\")", formatted ); //$NON-NLS-1$ } }
13075106_43
class RadixSort { public static void radixSort(int[] input, int n, int[] scratch, int[] countScratch) { if (countScratch.length != 65536) throw new IllegalArgumentException("countScratch.length must be = 65536"); if (input.length < n) throw new IllegalArgumentException("input.length must be >= n");...
Random r = new Random(); final int n = 10000000; int[] test1 = new int[n]; int[] test2 = new int[n]; int[] scratch = new int[n]; int[] countScratch = new int[65536]; for (int z = 0; z < 10; ++z) { for (int i = 0; i < n; i++) { int x = r...
13075200_44
class AbstractGroupsPayload { protected String[] convertToStringArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException { // historically, null values are allowed in the result, reasons unknown return extractNonNullValueFromMapPayload(payload, payloadMapKey, o -> co...
assertThatThrownBy(() -> subclass.convertToStringArray(makeStubMapPayload(MAP_KEY, null), MAP_KEY)) .isInstanceOf(NullPointerException.class) .hasMessageContaining(MAP_KEY); assertThat(subclass.convertToStringArray(makeStubMapPayload(MAP_KEY, singletonList("footest")), MA...
13077546_22
class StringDictionaryEncoder extends DictionaryEncoder { @Override public int size() { return numElements; } public StringDictionaryEncoder(MemoryEstimate memoryEstimate); public StringDictionaryEncoder(boolean sortKeys, boolean sortByStride, MemoryEstimate memoryEstimate); private int getSi...
String [] v = new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"}; StringDictionaryEncoder dict = buildDictionary(v, true); assertEquals(26, dict.size()); checkContent(dict, v, new int[]{0,...
13095397_0
class JdbcTemplateSqlExecutor implements SqlExecutor { public void execute( final String[] sql, final ExecutorCallback callback ) throws DataAccessException { Exception exceptionDuringExecute = null; DatabaseMeta dbMeta = connectionModel.getDatabaseMeta( ); String url = null; try { url = dbMet...
// set up final DatabaseMeta dbMeta = context.mock(DatabaseMeta.class); context.checking(new Expectations() { { one(dbMeta).getName(); will(returnValue("")); one(dbMeta).getXML(); will(returnValue(null)); allowing(dbMeta).getURL(); will(returnValue("jdbc...
13105692_5
class InterfaceReport { public List<Throwable> getErrors() { final List<Throwable> retval = new ArrayList<Throwable>(); for (final TestInfo testInfo : contractTestMap.listTestInfo()) { retval.addAll( testInfo.getErrors() ); } return retval; } public InterfaceRe...
final String[] expectedErrors = { "java.lang.IllegalStateException: Classes annotated with @Contract (class org.xenei.junit.bad.BadNoInject) must include a @Contract.Inject annotation on a public non-abstract declared setter method", }; final ClassPathFilter filter = new NotClassFilter...
13107807_6
class GetStatusSample extends AbstractSample { public static String getUrlString( String realHostname, String port ) { String urlString = "http://" + realHostname + ":" + port + GetStatusServlet.CONTEXT_PATH + "?xml=Y"; urlString = Const.replace( urlString, " ", "%20" ); return urlString; } pu...
assertEquals( "http://sample:1000/kettle/status?xml=Y", GetStatusSample.getUrlString( "sample", "1000" ) ); } }
13126412_15
class Step7Model implements StepModel { public int getHunkSize() { return hunkSize; } public Step7Model(final String sosURL, final File configFile, final boolean generateOfferingFromSensorName, final String offering, final String version, final String binding); public Step7Model(); public Str...
assertThat(model.getHunkSize(), is(5000)); } }
13127985_31
class CustomBaseUrlArchive extends AbstractArchive { @Override public String getExtension() { return delegate.getExtension(); } public CustomBaseUrlArchive(Archive delegate, String baseUrl); @Override protected String getBaseUrl(); @Override public String getArchiveName(); @Override public String ...
when(delegate.getExtension()).thenReturn(EXTENSION); assertThat(archive.getExtension()).isEqualTo(EXTENSION); } }
13133836_7
class MetaEditor implements SelectionListener { String[] getSchemas( Database database, DatabaseMeta databaseMeta ) throws KettleDatabaseException { // This is a hack for PMD-907. A NPE can be thrown on getSchema JDBC's implementations. String[] schemas = null; Exception ex = null; try { schema...
try { when( database.getSchemas() ).thenReturn( null ); when( database.getCatalogs() ).thenReturn( EXPECTED_SCHEMAS ); String[] schemas = metaEditor.getSchemas( database, meta ); assertArrayEquals( EXPECTED_SCHEMAS, schemas ); } catch ( KettleDatabaseException e ) { fail( "Should...
13137355_28
class KeyValueParser { public static Map<String, String> parse(String s) { final Map<String, String> result = new HashMap<>(); if (s == null) return result; // Process each line separated by a newline. for (String line : s.split("\n")) { // Parse the line l...
String msg = "========="; final Map<String, String> result = KeyValueParser.parse(msg); assertTrue(result.size() == 0); } }
13139604_0
class DataUtil { public static void setValueString(DataType d, String value) throws DataException { if (value != null && value.length() > 255) { try { setValue(d, value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); logger.error(FactoryException...
logger.info("Setting short data"); DataType data = new DataType(); boolean error = false; try{ DataUtil.setValueString(data, "Example text"); } catch(DataException de){ error = true; } assertFalse("An error was encountered", error); assertTrue("Short data not set", data.getShortData() != null...
13160719_0
class YamlMetricsAttributeTableLoader { public Table<String, NewRelicMetric, Boolean> loadTable(@Nonnull InputStream inputStream) throws IOException { Map<String, Map<NewRelicMetric, Boolean>> m = objectReader.forType(new TypeReference<Map<String, Map<NewRelicMetric, Boolean>>>() {}) ...
YamlMetricsAttributeTableLoader loader = new YamlMetricsAttributeTableLoader(); InputStream stream = getClass().getResourceAsStream("testing-config.yml"); Table<String, TableMetricAttributeFilter.NewRelicMetric, Boolean> table = loader.loadTable(stream); assertThat(table.get("name2", Ta...
13191344_54
class ModifierHelper { public static boolean matchesModifierLevel(AccessModifier modifierLevelOfElement, AccessModifier modifierLevel) { return (modifierLevelOfElement.getLevel() >= modifierLevel.getLevel()); } private ModifierHelper(); public static boolean matchesModifierLevel(int modifierOfElement, AccessM...
assertThat(ModifierHelper.matchesModifierLevel(Modifier.setPrivate(0), AccessModifier.PUBLIC), is(false)); } }
13217403_10
class GoogleHttpClientEdgeGridInterceptor implements HttpExecuteInterceptor { @Override public void intercept(HttpRequest request) throws IOException { try { binding.sign(request, request); } catch (RequestSigningException e) { throw new RuntimeException(e); } ...
HttpRequestFactory requestFactory = createSigningRequestFactory(); URI uri = URI.create("https://endpoint.net/billing-usage/v1/reportSources"); HttpRequest request = requestFactory.buildGetRequest(new GenericUrl(uri)); request.getHeaders().put("Host", "ignored-hostname.com"); //...
13236207_0
class InStream extends InputStream { public static InStream create(String name, ByteBuffer input, CompressionCodec codec, int bufferSize) throws IOException { if (codec == null) { return new UncompressedStream(n...
OutputCollector collect = new OutputCollector(); CompressionCodec codec = new ZlibCodec(); OutStream out = new OutStream("test", 500, codec, collect); PositionCollector[] positions = new PositionCollector[1024]; for(int i=0; i < 1024; ++i) { positions[i] = new PositionCollector(); out.ge...
13272929_2
class ReadOnlyStyledDocumentBuilder { public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraphs(List<List<SEG>> listOfSegLists, StyleSpans<S> entireDocumentStyleSpans) { return addParagraphList(listOfSegLists, entireDocumentStyleSpans, ignore -> null, Function.identity...
String text = "a"; int textStyle = 1; List<List<String>> singletonList = Collections.singletonList( Collections.singletonList(text) ); int segmentLength = text.length(); int spanLength = segmentLength + 10; StyleSpans<Integer> spans = StyleSpans.s...
13292939_10
class XPathRecord implements Record { @Override public List<Value> getValues(String field) { try { XPathExpression expr = xpath_map.get(field); if (expr == null) { return null; } NodeList lst = (NodeList)expr.evaluate(doc, XPathConstants.N...
List<Value> res3 = rec.getValues("leaf1_attribute"); assertEquals(1, res3.size()); assertEquals("leaf1 attribute", res3.get(0).getAsString()); List<Value> res4 = rec.getValues("all_attributes"); assertEquals(2, res4.size()); assertEquals("leaf1 attribute", res4.get(0).ge...
13317929_25
class NonEmptyStringAnnotationFormatterFactory implements AnnotationFormatterFactory<NonEmpty> { @Override public Parser<String> getParser(NonEmpty annotation, Class<?> fieldType) { return new Parser<String>() { @Override public String parse(String text, Locale locale) ...
// Arrange final String anyString = "Foo"; // Act Parser<String> parser = testee.getParser(null, String.class); // Assert assertThat(parser.parse(null, Locale.getDefault())).isEqualTo(null); assertThat(parser.parse(anyString, null)).isEqualTo(anyString); ...