id stringlengths 7 14 | source stringlengths 135 41.2k | target stringlengths 36 20.4k |
|---|---|---|
13899_11 | class IoUtils {
public static String readString(InputStream in, String charset) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c;
while ((c = in.read()) > 0) {
out.write(c);
}
return new String(out.toByteArray(), charset);
}
private IoUtils();
public static int s... | final String first = "Hi there";
final String second = "Have a nice day!";
byte[] firstBytes = first.getBytes();
byte[] secondBytes = second.getBytes();
byte[] newBytes = new byte[firstBytes.length + secondBytes.length + 1];
System.arraycopy(firstBytes, 0, newBytes, 0, firstBytes.length);
System.arraycopy... |
32578_0 | class LookupManagerImpl implements LookupManager {
public List<LabelValue> getAllRoles() {
List<Role> roles = dao.getRoles();
List<LabelValue> list = new ArrayList<LabelValue>();
for (Role role1 : roles) {
list.add(new LabelValue(role1.getName(), role1.getName()));
}
... | log.debug("entered 'testGetAllRoles' method");
// set expected behavior on dao
Role role = new Role(Constants.ADMIN_ROLE);
final List<Role> testData = new ArrayList<Role>();
testData.add(role);
context.checking(new Expectations() {{
one(lookupDao).getRoles();... |
56670_0 | class ClasspathScanner {
protected String getPackage() {
return pkg;
}
public ClasspathScanner(String pkg, boolean subpackages);
public ClasspathScanner(String pkg);
private void sanitizePackage(String pkgName);
protected ClassLoader getClassLoader();
protected boolean isJARPath... | scanner = new ClasspathScanner("org.hibernate.*");
assertEquals("Package was sanitized", "org/hibernate", scanner.getPackage());
}
} |
56904_58 | class ForeignKeyListHolder {
public List<U> get() {
if (this.loaded == null) {
if (this.parent.isNew() || UnitTesting.isEnabled()) {
// parent is brand new, so don't bother hitting the database
this.loaded = new ArrayList<U>();
} else {
if (!UoW.isOpen()) {
throw new... | DummyDomainObject parent = new DummyDomainObject();
ForeignKeyListHolder<DummyDomainObject, DummyDomainObject> h = //
new ForeignKeyListHolder<DummyDomainObject, DummyDomainObject>(parent, null, null, null);
parent.setId(1l);
Assert.assertEquals(0, h.get().size());
}
} |
74217_5 | class RecordPackageClassScanner {
public List<Class<?>> scan(List<String> packages) {
List<Class<?>> classes = new ArrayList<Class<?>>();
for (String packageName : packages) {
for (Class clazz : findClassesInPackage(packageName)) {
if (hasRecordAnnoation(clazz))
... | RecordPackageClassScanner scanner = new RecordPackageClassScanner();
List<Class<?>> classes = scanner.scan(Arrays.<String>asList("flapjack.test", "flapjack.test2"));
assertNotNull(classes);
assertTrue(classes.contains(User.class));
assertTrue(classes.contains(Phone.class));
... |
88960_47 | class PlainFormatter implements JSLintResultFormatter {
public String format(JSLintResult result) {
StringBuilder sb = new StringBuilder();
for (Issue issue : result.getIssues()) {
sb.append(outputOneIssue(issue));
}
return sb.toString();
}
public String footer(... | String nl = System.getProperty("line.separator");
String name = "foo/bar.js";
Issue issue = new IssueBuilder(name, 0, 0, "oops").evidence("BANG").build();
JSLintResult result = new JSLintResult.ResultBuilder(name).addIssue(issue).build();
StringBuilder sb = new StringBuilder(name... |
97620_0 | class ClassName {
public String get() {
return this.fullClassNameWithGenerics;
}
public ClassName(String fullClassNameWithGenerics);
public String toString();
public String getSimpleName();
public String getPackageName();
public List<String> getGenericsWithoutBounds();
public List<String> getGenericsWithB... | assertThat(//
new ClassName("java.util.Map<K, V>.Entry<K, V>").get(),
is("java.util.Map.Entry<K, V>"));
assertThat(//
new ClassName("java.util.Foo<K extends java.util.Bar<K>>.Entry<K extends java.util.Bar<K>>").get(),
is("java.util.Foo.Entry<K extends java.util.Bar<K>>"));
}
} |
103035_6 | class JMXAgent implements NotificationListener {
public static boolean unregisterMBean(ObjectName oName) {
boolean unregistered = false;
if (null != oName) {
try {
if (mbs.isRegistered(oName)) {
log.debug("Mbean is registered");
mbs.unregisterMBean(oName);
//set flag based on registration st... | logger.info("Default jmx domain: {}", JMXFactory.getDefaultDomain());
JMXAgent agent = new JMXAgent();
agent.init();
MBeanServer mbs = JMXFactory.getMBeanServer();
//create a new mbean for this instance
ObjectName oName = JMXFactory.createMBean(
"org.red5.server.net.rtmp.RTMPMinaConnection",
"connec... |
121672_32 | class Fields implements Comparable, Iterable<Comparable>, Serializable, Comparator<Tuple> {
public Fields appendSelector( Fields fields )
{
return appendInternal( fields, true );
}
protected Fields( Kind kind );
public Fields();
@ConstructorProperties({"fields"}) public Fields( Comparab... | Fields fieldA = new Fields( 0, -1 );
Fields fieldB = new Fields( -1 );
try
{
Fields appended = fieldA.appendSelector( fieldB );
fail();
}
catch( Exception exception )
{
// ignore
}
}
} |
123235_12 | class PubkeyUtils {
public static KeyPair recoverKeyPair(byte[] encoded) throws NoSuchAlgorithmException,
InvalidKeySpecException {
final String algo = getAlgorithmForOid(getOidFromPkcs8Encoded(encoded));
final KeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);
final KeyFactory kf = KeyFactory.getInst... | KeyPair kp = PubkeyUtils.recoverKeyPair(DSA_KEY_PKCS8);
DSAPublicKey pubKey = (DSAPublicKey) kp.getPublic();
assertEquals(DSA_KEY_pub, pubKey.getY());
DSAParams params = pubKey.getParams();
assertEquals(params.getG(), DSA_KEY_G);
assertEquals(params.getP(), DSA_KEY_P);
assertEquals(params.getQ(), DSA_K... |
135867_7 | class LoginController extends UIController {
@SuppressWarnings("unchecked")
public ModelAndView logIn(HttpServletRequest request, HttpServletResponse response, LoginCommand login,
BindException errors) throws Exception {
// Checking whether logged in
ApplicationState state = getAppl... | LoginCommand loginCom = new LoginCommand();
loginCom.setUsername("test1");
loginCom.setPassword("yes");
loginController = (LoginController) context.getBean("loginController");
ModelAndView mav = loginController.logIn(request, response, loginCom, new BindException(loginCom, "test"... |
149511_10 | class SVNState implements State {
public boolean isUnderRevisionControl() {
return true;
}
protected SVNState(String state);
public boolean isCheckedOut();
public boolean isDeleted();
@Override public String toString();
protected boolean contains(String msg, String searchString);
}
class SVNStat... | assertFalse("Files in Unknown State should not be under revision control", SVNState.UNKNOWN.isUnderRevisionControl());
assertTrue("Files in Checked In State should be under revision control", VERSIONED.isUnderRevisionControl());
assertTrue("Files in Added State should be under revision control", SVNState.AD... |
152134_28 | class UserManagerBean implements UserManager {
public User findByUsername(String username) {
Query query = em.createNamedQuery("findUserByUsername");
query.setParameter("username", username);
return (User) query.getSingleResult();
}
public User create(String username, String passwo... | EntityManager em = createMock(EntityManager.class);
Query q = createMock(Query.class);
User user = createDummyUser(username);
expect(em.createNamedQuery("findUserByUsername"))
.andReturn(q);
expect(q.setParameter("username", username)).andReturn(q);
expec... |
160996_95 | class PlainMailboxManager implements MailboxManager {
public void transportMessage( Who recipient, Message msg ) throws Exception
{
if (msg.getMessageId() != null)
throw new IllegalStateException( "message has already been sent" );
msg.setMessageId( idGen.next() );
//Log.report( "MailboxManager.send",... | // test sending a message that has already been sent (has a message id)
assertNull( transport.what );
assertNull( transport.recipient );
assertNull( transport.msg );
Message msg = constructAddMessage();
assertNull( msg.getMessageId() );
msg.setMessageId( 1L );
// this should trigger msg already s... |
160999_86 | class VerifyingFileFactory {
public File create(String path) {
File file = new File(path);
return validate(file);
}
public VerifyingFileFactory(Builder builder);
public File validate(File file);
private void doFailForNonExistingPath(File file);
private void doWarnForRelativeP... | VerifyingFileFactory vff = new VerifyingFileFactory.Builder(log).warnForRelativePath().build();
vff.create("./an/intended/relative/path");
// assertFalse(log.hasWarned);
}
} |
161005_337 | class WikiPermission extends Permission implements Serializable {
public String toString()
{
return "(\"" + this.getClass().getName() + "\",\"" + m_wiki + "\",\"" + getActions() + "\")";
}
public WikiPermission( String wiki, String actions );
public boolean equals( Object obj );
publ... | WikiPermission p1 = new WikiPermission("*", "createPages,createGroups,editProfile");
String result = "(\"org.apache.wiki.auth.permissions.WikiPermission\",\"*\",\"creategroups,createpages,editprofile\")";
Assertions.assertEquals(result, p1.toString());
}
} |
161180_0 | class Convert {
public static final byte[] toBytes(int i){
if(i < INT_N_65535 || i > INT_P_65535) {
return Integer.toString(i).getBytes();
}
final int absi = Math.abs(i);
final byte[] cachedData = i2b_65535[absi];
final byte[] data;
if(cachedData == null) {
data = Integer.toString(absi).getBytes();
... | Log.log("Testing number to bytes conversion ...");
byte[] javadata = null;
byte[] data = null;
// test MIN
int n;
n=Integer.MIN_VALUE;
javadata = Integer.toString(n).getBytes();
data = Convert.toBytes(n);
assertEquals (data.length, javadata.length, "buffer length");
for(int j=0; j<data.length;j++)... |
168535_2 | class GuestbookNavigation {
public Entry getPrevious() {
Entry previous = null;
for (Entry entry : entryDao.readAll()) {
if (entry.getId().equals(current.getId()) && previous != null) {
return previous;
}
previous = entry;
}
return... | expect(daoMock.readAll()).andReturn(new ArrayList<Entry>());
replay(daoMock);
assertNull(classUnderTest.getPrevious());
verify(daoMock);
}
} |
169928_3 | class SeasonPassManager {
public int sizeOfToDoList() {
return toDoList.size();
}
public SeasonPassManager(Schedule schedule);
public void setNumberOfRecorders(int number);
public Program createNewSeasonPass(String programName, int channel);
private boolean conflictsWithExistingSchedule(Program program);
p... | assertEquals(0, seasonPassManager.sizeOfToDoList());
}
} |
175376_3 | class Parser {
Expr parseYieldExpr() {
return new Expr.Yield(parseOptionalTestList());
}
public Parser(Scanner scanner);
private boolean is(String t);
private boolean at(String t);
private Object value();
private void expect(String token);
int line();
Suite parseFileInput();
ExprList pars... | assertEquals("Suite[Expr(Yield(Lit(None)))]", parse("(yield)\n"));
}
} |
184604_0 | class CharacterUtil {
public static int count(String text) {
return text.length();
}
private CharacterUtil();
public static boolean isExceedingLengthLimitation(String text);
}
class CharacterUtilTest {
@Test
void testCount() throws Exception {
| String str;
int expectedLength;
str = "a quick brown fox jumped over the lazy dog.";
expectedLength = str.length();
assertEquals(expectedLength, CharacterUtil.count(str));
str = "café";
expectedLength = 4;
assertEquals(expectedLength, CharacterUtil.count(... |
206320_1 | class AccuRevRemoveCommand extends AbstractAccuRevCommand {
public RemoveScmResult remove( ScmProviderRepository repository, ScmFileSet fileSet, CommandParameters parameters )
throws ScmException
{
return (RemoveScmResult) execute( repository, fileSet, parameters );
}
public AccuRevRe... | final ScmFileSet testFileSet = new ScmFileSet( basedir, new File( "src/main/java/Foo.java" ) );
List<File> removedFiles = Collections.singletonList( new File( "removed/file" ) );
when( accurev.defunct( basedir, testFileSet.getFileList(), "A deleted file" ) ).thenReturn( removedFiles );
... |
206322_31 | class LineEndingsUtils {
@Nullable
public static String getLineEndingCharacters( @Nullable String lineEnding )
throws AssemblyFormattingException
{
String value = lineEnding;
if ( lineEnding != null )
{
try
{
value = LineEndings.val... | assertEquals( null, LineEndings.keep.getLineEndingCharacters() );
}
} |
206350_846 | class CallbackDescriptor implements Serializable {
public LifecycleEvent getCallbackType() {
return callbackType;
}
public CallbackDescriptor(LifecycleEvent callbackType);
public void clear();
public Collection<String> getCallbackMethods();
public void addCallbackMethod(String method... | CallbackDescriptor m = new CallbackDescriptor(LifecycleEvent.POST_LOAD);
assertEquals(LifecycleEvent.POST_LOAD, m.getCallbackType());
}
} |
206364_39 | class DBDictionary implements Configurable, ConnectionDecorator, JoinSyntaxes,
LoggingConnectionDecorator.SQLWarningHandler, IdentifierConfiguration {
public String toSnakeCase(final String name) {
final StringBuilder out = new StringBuilder(name.length() + 3);
final boolean isDelimited = name.... | final DBDictionary dictionary = new DBDictionary();
assertEquals("foo", dictionary.toSnakeCase("foo"));
assertEquals("foo_bar", dictionary.toSnakeCase("fooBar"));
assertEquals("fooba_r", dictionary.toSnakeCase("FoobaR"));
assertEquals("o_f_o_ob", dictionary.toSnakeCase("oFOOb"));... |
206402_426 | class ResponseCachingPolicy {
public boolean isResponseCacheable(final String httpMethod, final HttpResponse response) {
boolean cacheable = false;
if (!HeaderConstants.GET_METHOD.equals(httpMethod) && !HeaderConstants.HEAD_METHOD.equals(httpMethod)) {
if (LOG.isDebugEnabled()) {
... |
Assert.assertFalse(policy.isResponseCacheable("PUT", response));
Assert.assertFalse(policy.isResponseCacheable("get", response));
}
} |
206403_0 | class JsonWriter {
void write(Node node, int maxLevels) throws RepositoryException, IOException {
write(node, 0, maxLevels);
}
JsonWriter(Writer writer);
void write(Collection<Node> nodes, int maxLevels);
private void write(Node node, int currentLevel, int maxLevels);
private void ... | StringWriter writer = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(writer);
Node parent = createMock(Node.class);
Property doubleProperty = createMock(Property.class);
Value doublePropertyValue = createMock(Value.class);
expect(doubleProperty.getType()).and... |
206418_92 | class ParallelBuildsManager implements BuildsManager, Contextualizable {
public void checkoutProject( int projectId, String projectName, File workingDirectory, String scmRootUrl,
String scmUsername, String scmPassword, BuildDefinition defaultBuildDefinition,
... | setupMockOverallBuildQueues();
BuildDefinition buildDef = new BuildDefinition();
buildDef.setId( 1 );
buildDef.setSchedule( getSchedule( 1, 1, 2 ) );
setupCheckoutProjectBuildQueuesAreEmpty();
buildsManager.checkoutProject( 1, "continuum-project-test-1",
... |
206437_62 | class CipherTextHandler {
public byte[] decrypt( EncryptionKey key, EncryptedData data, KeyUsage usage ) throws KerberosException
{
LOG_KRB.debug( "Decrypting data using key {} and usage {}", key.getKeyType(), usage );
EncryptionEngine engine = getEngine( key );
return engine.getDecryp... | CipherTextHandler lockBox = new CipherTextHandler();
KerberosPrincipal principal = new KerberosPrincipal( "erodriguez@EXAMPLE.COM" );
KerberosKey kerberosKey = new KerberosKey( principal, "badpassword".toCharArray(), "DES" );
EncryptionKey key = new EncryptionKey( EncryptionType.DES_CBC_... |
206444_108 | class AcidTxnCleanerService implements MetastoreTaskThread {
@Override
public void run() {
TxnStore.MutexAPI.LockHandle handle = null;
try {
handle = txnHandler.getMutexAPI().acquireLock(TxnStore.MUTEX_KEY.TxnCleaner.name());
long start = System.currentTimeMillis();
txnHandler.cleanEmptyA... | for (int i = 0; i < 5; ++i) {
openNonEmptyThenAbort();
}
Assert.assertEquals(5 + 1, getTxnCount());
Thread.sleep(txnHandler.getOpenTxnTimeOutMillis() * 2);
underTest.run();
// deletes only the initial (committed) TXNS record
Assert.assertEquals(5, getTxnCount());
Assert.assertTru... |
206451_6 | class XPath20ExpressionRuntime implements ExpressionLanguageRuntime {
@SuppressWarnings("unchecked")
public List evaluate(OExpression cexp, EvaluationContext ctx) throws FaultException, EvaluationException {
List result;
Object someRes = null;
try {
someRes = evaluate(cexp, ... | String insertElementName="InsertedNode";
OXPath20ExpressionBPEL20 exp = compile("$reallyEmptyVar/"+insertElementName);
exp.setInsertMissingData(true);
// Setup root node
_rootNode = DOMUtils.stringToDOM("<tns:ApplicationData xmlns:tns=\"http://foobar\"/>");
... |
206452_15 | class UIAction extends ActionSupport implements UIActionPreparable, UISecurityEnforced, RequestAware {
public static String cleanTextKey(String s) {
if (s == null || s.isEmpty()) {
return s;
}
// escape HTML
return StringEscapeUtils.escapeHtml4(cleanExpressions(s));
... | assertEquals(null,UIAction.cleanTextKey(null));
assertEquals("",UIAction.cleanTextKey(""));
assertEquals("a",UIAction.cleanTextKey("a"));
assertEquals("$",UIAction.cleanTextKey("$"));
assertEquals("%",UIAction.cleanTextKey("%"));
assertEquals("%$",UIAction.cleanTextKey("%... |
206483_66 | class ModelMerger {
protected void mergeContributor_Roles( Contributor target, Contributor source, boolean sourceDominant,
Map<Object, Object> context )
{
target.setRoles( merge( target.getRoles(), source.getRoles(), sourceDominant, e -> e ) );
}
publ... | Contributor target = new Contributor();
target.setRoles( Arrays.asList( "first", "second", "third" ) );
Contributor source = new Contributor();
source.setRoles( Arrays.asList( "first", "second", "third" ) );
modelMerger.mergeContributor_Roles( target, source, true, null );
... |
206633_1000 | class BeanFilter {
public Object createFilteredBean(Object data, Set<String> fields) {
return createFilteredBean(data, fields, "");
}
@SuppressWarnings("unchecked") private Object createFilteredBean(Object data, Set<String> fields, String fieldName);
public Set<String> processBeanFields(Collection<String>... | SimpleBean data = new SimpleBean().setI(5);
SimpleBeanInterface dataBean = (SimpleBeanInterface) beanDelegator.createDelegator(data);
SimpleBeanInterface newData = (SimpleBeanInterface) beanFilter.createFilteredBean(
dataBean, ImmutableSet.<String>of("i"));
assertEquals(5, newData.getI());
... |
206635_4 | class PluginMetadataParser {
public Set<MojoDescriptor> parseMojoDescriptors( File metadataFile )
throws PluginMetadataParseException
{
Set<MojoDescriptor> descriptors = new HashSet<>();
try ( Reader reader = ReaderFactory.newXmlReader( metadataFile ) )
{
PluginMet... | File metadataFile = getMetadataFile( "test2.mojos.xml" );
Set<MojoDescriptor> descriptors = new PluginMetadataParser().parseMojoDescriptors( metadataFile );
assertEquals( 1, descriptors.size() );
MojoDescriptor desc = descriptors.iterator().next();
assertTrue( d... |
209853_134 | class BancoDoBrasil extends AbstractBanco implements Banco {
@Override
public String geraCodigoDeBarrasPara(Boleto boleto) {
Beneficiario beneficiario = boleto.getBeneficiario();
String numeroConvenio = beneficiario.getNumeroConvenio();
if (numeroConvenio == null
|| numeroConve... | this.banco = new BancoDoBrasil();
this.boleto = this.boleto.comBanco(this.banco);
assertEquals("3860", this.banco.geraCodigoDeBarrasPara(this.boleto).substring(5, 9));
}
} |
213337_470 | class Domain {
public abstract SortedSetModel<AdverseEvent> getAdverseEvents()public abstract SortedSetModel<AdverseEvent> getAdverseEvents();
public abstract SortedSetModel<AdverseEvent> getAdverseEvents()public abstract List<EntityCategory> getCategories();
public abstract SortedSetModel<AdverseEvent> getAdverseEve... | AdverseEvent ade = new AdverseEvent("a", AdverseEvent.convertVarType(Variable.Type.RATE));
assertEquals(0, d_domain.getAdverseEvents().size());
d_domain.getAdverseEvents().add(ade);
assertEquals(1, d_domain.getAdverseEvents().size());
assertEquals(Collections.singletonList(ade), d_domain.getAdverseEvents());
... |
219850_20 | class WikiParser extends BrainParser {
public void setUseCanonicalFormat(boolean useCanonicalFormat) {
this.useCanonicalFormat = useCanonicalFormat;
}
@Override public Note parse(final InputStream inputStream);
private boolean isEmptyPage(final String page);
private BufferedReader createRe... | wikiParser.setUseCanonicalFormat(true);
List<Note> notes = readNotes("* Arthur Dent\n" +
"\n" +
"He's a jerk.\n" +
"A complete kneebiter.");
assertEquals(1, notes.size());
Note root = notes.get(0);
assertEquals("Arthur Dent", root.g... |
225207_7 | class NMRFaultOutInterceptor extends AbstractPhaseInterceptor<NMRMessage> {
public void handleMessage(NMRMessage message) throws Fault {
message.put(org.apache.cxf.message.Message.RESPONSE_CODE, new Integer(500));
NSStack nsStack = new NSStack();
nsStack.push();
t... | PhaseInterceptor<NMRMessage> interceptor = new NMRFaultOutInterceptor();
try {
NMRMessage msg = new NMRMessage(new MessageImpl());
interceptor.handleMessage(msg);
fail("Should have thrown an exception");
} catch (IllegalStateException e) {
// ok
... |
225211_0 | class OsgiLocator {
public static <T> Class<? extends T> locate(Class<T> factoryId) {
return locate(factoryId, factoryId.getName());
}
private OsgiLocator();
public static void unregister(String id, Callable<Class> factory);
public static void register(String id, Callable<Class> factory)... | System.setProperty(OsgiLocator.TIMEOUT, "0");
System.setProperty("Factory", "org.apache.servicemix.specs.locator.MockCallable");
Class clazz = OsgiLocator.locate(Object.class, "Factory");
assertNotNull("Expected to find a class", clazz);
assertEquals("Got the wrong class", MockCa... |
229738_123 | class Sneaky {
@CheckReturnValue
@Nonnull
public static DummyException throwAnyway(Throwable t) {
if (t instanceof Error) {
throw (Error) t;
}
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
if (t instanceof IOException) {... | RuntimeException rex = new IllegalArgumentException();
assertThatThrownBy(() -> Sneaky.throwAnyway(rex))
.isSameAs(rex);
}
} |
231990_1 | class ContributorHelper {
public static List<String> parseTrack(String track) {
Pattern pattern = Pattern.compile("(.+)(\\((F|f)eat(\\. |\\.| |uring )(.+))\\)");
Matcher matcher = pattern.matcher(track);
boolean matches = matcher.matches();
if (matches) {
String title = ... | assertEquals(singletonList("A"), parseTrack("A"));
assertEquals(asList("A", "B"), parseTrack("A (feat. B)"));
assertEquals(asList("A", "B"), parseTrack("A (Feat. B)"));
assertEquals(asList("A", "B"), parseTrack("A (featuring B)"));
assertEquals(asList("A", "B"), parseTrack("A (Fe... |
235076_9 | class ResourceHashModel implements TemplateHashModelEx, TemplateScalarModel, ResourceTemplate {
@Override
public String getAsString() throws TemplateModelException {
if (resource.getURI() == null) {
return INVALID_URL; // b-nodes return null and their ids are useless
} else... |
Resource resource = ModelFactory.createDefaultModel().createResource();
ResourceHashModel resourceHashModel = new ResourceHashModel(resource);
assertEquals("Unexpected URI", ResourceHashModel.INVALID_URL,
resourceHashModel.getAsString());
}
} |
237920_1 | class CreateDeleteProjectAction extends AvailableLaterObject<Void> {
public void setProjects(Projects projects) {
this.projects = projects;
}
public CreateDeleteProjectAction(ProjectDir dir, boolean delete);
@Override public Void calculate();
private CreateDeleteProjectAction action;
ProjectDir dir;
}
c... | Projects projects = Mockito.mock(Projects.class);
action = new CreateDeleteProjectAction(dir, true);
action.setProjects(projects);
AvailableLaterWaiter.await(action);
Mockito.verify(projects).remove(dir);
Mockito.verifyNoMoreInteractions(projects);
}
} |
240464_2 | class EJBException extends RuntimeException {
public String getMessage() {
if (causeException == null) return super.getMessage();
StringBuilder sb = new StringBuilder();
if (super.getMessage() != null) {
sb.append(super.getMessage());
sb.append("; ");
}
... |
Assert.assertEquals(null, exceptionDefaultConstructor.getMessage());
Assert.assertEquals(null, exceptionWithNullMessage.getMessage());
Assert.assertEquals("msg", exceptionWithMessage.getMessage());
Assert.assertEquals("msg; nested exception is: java.lang.Exception: cause", exceptionW... |
240466_0 | class PropertyEditors {
public static boolean canConvert(final String type, final ClassLoader classLoader) {
if (type == null) {
throw new NullPointerException("type is null");
}
if (classLoader == null) {
throw new NullPointerException("classLoader is null");
... | assertTrue(PropertyEditors.canConvert(Blue.class));
}
} |
247823_30 | class NewCookieHeaderDelegate implements HeaderDelegate<NewCookie> {
public String toString(NewCookie cookie) {
if (cookie == null) {
throw new IllegalArgumentException(Messages.getMessage("cookieIsNull")); //$NON-NLS-1$
}
return buildCookie(cookie.getName(), cookie.getValue(), ... | RuntimeDelegate rd = RuntimeDelegate.getInstance();
HeaderDelegate<NewCookie> newCookieHeaderDelegate =
rd.createHeaderDelegate(NewCookie.class);
if (newCookieHeaderDelegate == null) {
fail("NewCookie header delegate is not regestered in RuntimeDelegateImpl");
}
... |
279216_19 | class Search extends Command<Result> {
public Result send(Connection connection) throws DespotifyException {
/* Create channel callback */
ChannelCallback callback = new ChannelCallback();
byte[] utf8Bytes = query.getBytes(Charset.forName("UTF8"));
/* Create channel and buffer. */
Channel chann... | Result result = (Result)manager.send(new Search(store, "Johnny Cash"));
assertTrue(result.getTotalTracks() > 2000);
assertEquals(100, result.getTracks().size());
// todo assert a bit. at least we know there was no exception.
System.currentTimeMillis();
}
} |
283187_21 | class SLF4JBridgeHandler extends Handler {
public static void install() {
LogManager.getLogManager().getLogger("").addHandler(new SLF4JBridgeHandler());
}
public SLF4JBridgeHandler();
private static java.util.logging.Logger getRootLogger();
public static void uninstall();
public stat... | SLF4JBridgeHandler.install();
String resourceBundleName = "org.slf4j.bridge.testLogStrings";
ResourceBundle bundle = ResourceBundle.getBundle(resourceBundleName);
String resourceKey = "resource_key";
String expectedMsg = bundle.getString(resourceKey);
String msg = resour... |
283325_37 | class TargetLengthBasedClassNameAbbreviator implements Abbreviator {
public String abbreviate(String fqClassName) {
StringBuilder buf = new StringBuilder(targetLength);
if (fqClassName == null) {
throw new IllegalArgumentException("Class name may not be null");
}
int in... | {
TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthBasedClassNameAbbreviator(100);
String name = "hello";
assertEquals(name, abbreviator.abbreviate(name));
}
{
TargetLengthBasedClassNameAbbreviator abbreviator = new TargetLengthB... |
291242_13 | class MessageConveyor implements IMessageConveyor {
public <E extends Enum<?>> String getMessage(E key, Object... args)
throws MessageConveyorException {
Class<? extends Enum<?>> declaringClass = key.getDeclaringClass();
String declaringClassName = declaringClass.getName();
CAL10NBundle rb = ... |
MessageConveyor mc = new MessageConveyor(Locale.CHINA);
try {
mc.getMessage(Colors.BLUE);
fail("missing exception");
} catch (MessageConveyorException e) {
assertEquals(
"Failed to locate resource bundle [colors] for locale [zh_CN] for enum type [ch.qos.cal10n.sample.Colors]",
... |
291570_20 | class AbstractAuthenticator implements Authenticator, LogoutAware {
public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
if (token == null) {
throw new IllegalArgumentException("Method argument (authentication token) cannot be null.");
... | AuthenticationInfo authcInfo = abstractAuthenticator.authenticate(newToken());
assertNotNull(authcInfo);
}
} |
293812_0 | class PrettyFormatter implements Reporter, Formatter {
@Override
public void close() {
out.close();
}
public PrettyFormatter(Appendable out, boolean monochrome, boolean executing);
public void setMonochrome(boolean monochrome);
@Override public void uri(String uri);
@Override pub... | PrintStream out = mock(PrintStream.class);
Formatter formatter = new PrettyFormatter(out, true, true);
formatter.close();
verify(out).flush();
verify(out).close();
}
} |
298328_9 | class AnsiRenderer {
public static String render(final String input) throws IllegalArgumentException {
try {
return render(input, new StringBuilder(input.length())).toString();
} catch (IOException e) {
// Cannot happen because StringBuilder does not throw IOException
... | // Check the ansi() render method.
String str = ansi().render("@|bold Hello|@").toString();
System.out.println(str);
assertEquals(ansi().a(INTENSITY_BOLD).a("Hello").reset().toString(), str);
}
} |
315033_36 | class TransactionalInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
final Method method = invocation.getMethod();
if(method == null) {
return null;
}
Transactional txa = method.getAnnotation(Transactional.class);
if (txa == null... | final MethodInvocation invocation = mockery.mock(MethodInvocation.class);
mockery.checking(new Expectations() {
{
Sequence seq = mockery.sequence("newTx");
exactly(1).of(invocation).getMethod();
will(returnValue(propagtedIsolatedTransaction));
inSequence(seq);
exac... |
320367_0 | class Hello {
public static int times(int x, int y)
{
return new HelloWorldJNI().timesHello(x, y);
}
}
class HelloTest {
@Test public final void testTimes()
{
| Assert.assertEquals(42, Hello.times(3, 14));
}
} |
320690_7 | class ReflectionSourcePropertyFactory implements SourcePropertyFactory {
@Override
public SourceProperty getSourceProperty( String expression ) {
if ( isIdentifier( expression ) ) {
return new ReflectionSourceProperty( expression );
} else {
return null;
}
}
public ReflectionSourcePropertyFactory();
... | assertNull( factory.getSourceProperty( "23skidoo" ) );
}
} |
324985_0 | class MistletoeCore {
public boolean hasAssociatedFailures(Description d) {
List<Failure> failureList = result.getFailures();
for (Failure f : failureList) {
if (f.getDescription().equals(d)) {
return true;
}
if (description.isTest()) {
return false;
}
List<Desc... | MistletoeCore mCore = new MistletoeCore(MyCollection.class);
mCore.run();
Description description = mCore.getDescription();
assertTrue(mCore.hasAssociatedFailures(description));
Map<Description, Boolean> map = new HashMap<Description, Boolean>();
doCheck(map, mCore, description);
f... |
327391_1 | class ArrayBuilder {
@SuppressWarnings({"unchecked"})
public ArrayBuilder<T> add(T... elements) {
if (elements == null) return this;
if (array == null) {
array = elements;
return this;
}
T[] newArray = (T[]) Array.newInstance(array.getClass().getComponent... | assertEquals(new ArrayBuilder<Integer>().add(1, 2).add(3).add(4, 5, 6).get(), new Integer[] {1, 2, 3, 4, 5, 6});
assertEquals(new ArrayBuilder<Integer>().add(1, 2).addNonNulls(3, null, 4, null).get(), new Integer[] {1, 2, 3, 4});
}
} |
327472_155 | class SaveQueryCommand implements DynamicCommand {
@Override
public boolean accept(final ConsoleState state) {
Assertions.checkNotNull("state", state);
if (state.getActiveCommand() == null && state.getInput().trim().startsWith("save ")) { return true; }
return false;
}
@Overrid... | final ConsoleState state = new ConsoleState(null);
state.setInput("add save");
assertThat(command.accept(state), is(false));
}
} |
331792_7 | class NodePath extends ComponentSupport {
@Nullable
public NodePath parent() {
int i = path.lastIndexOf(Node.SEPARATOR);
if (i == 0) {
return this;
}
else if (i == -1) {
return null;
}
else {
return new NodePath(path.substring(0, i));
}
}
public NodePath(final St... | assertNull(new NodePath("foo").parent());
}
} |
335218_30 | class SatzFactory {
public static Satz getSatz(final int satzart) {
return getSatz(new SatzTyp(satzart));
}
private SatzFactory();
private static void registerDefault();
public static void reset();
public static void register(final Class<? extends Satz> clazz, final int satzart);
... | Teildatensatz one = SatzFactory.getSatz(100).getTeildatensatz(4);
Teildatensatz two = SatzFactory.getSatz(100).getTeildatensatz(4);
assertNotSame(one, two);
Feld oneIban = one.getFeld(Bezeichner.IBAN1);
Feld twoIban = two.getFeld(Bezeichner.IBAN1);
assertNotSame(oneIban, ... |
336330_27 | class MatrixView extends AbstractMatrix {
@Override
public Matrix viewPart(int[] offset, int[] size) {
if (offset[ROW] < ROW) {
throw new IndexException(offset[ROW], ROW);
}
if (offset[ROW] + size[ROW] > rowSize()) {
throw new IndexException(offset[ROW] + size[ROW], rowSize());
}
if... | int[] offset = {1, 1};
int[] size = {2, 1};
Matrix view = test.viewPart(offset, size);
int[] c = view.size();
for (int row = 0; row < c[ROW]; row++) {
for (int col = 0; col < c[COL]; col++) {
assertEquals("value[" + row + "][" + col + ']',
values[row + 2][col + 2], view.get... |
338815_32 | class HistoryDialogModel {
protected boolean isCurrentRevisionSelected() {
return myRightRevisionIndex == 0;
}
public HistoryDialogModel(IdeaGateway gw, LocalVcs vcs, VirtualFile f);
public List<Revision> getRevisions();
private void initRevisionsCache();
protected List<Revision> getRevisionsCache()... | m.selectRevisions(1, 2);
assertFalse(m.isCurrentRevisionSelected());
m.selectRevisions(2, 2);
assertTrue(m.isCurrentRevisionSelected());
m.selectRevisions(-1, -1);
assertTrue(m.isCurrentRevisionSelected());
}
} |
339284_3 | class SystemPropertySource extends SourceSupport {
public Model load() throws Exception {
if (name == null) {
throw new MissingPropertyException("name");
}
String value = System.getProperty(name);
if (value == null) {
log.trace("Unable to load; property not set: {}", name);
return... | try {
SystemPropertySource s = new SystemPropertySource();
s.load();
fail();
}
catch (ConfigurationException expected) {
}
}
} |
339856_0 | class FlightToTripNotificationsSplitter {
@Splitter
public List<TripNotification> generateTripNotificationsFrom(FlightNotification flightNotification,
@Header("affectedTrips") List<Trip> affectedTrips) {
List<TripNotification> notifications = new ArrayList<TripNotification>(affectedTrips.size()... | FlightNotification flightNotification = new FlightNotification("Flight is cancelled", mock(Flight.class));
List<Trip> affectedTrips = new ArrayList<Trip>(5);
affectedTrips.add(new Trip(Collections.singletonList(mock(Leg.class))));
List<TripNotification> notifications = splitter.generateT... |
357827_0 | class TiTATimeConverter {
public static Long getString2Duration(String time) throws ParseException {
String[] timeArray = time.split(":");
if (timeArray.length != C_THREE) {
throw new ParseException("", 0);
}
try {
long millis;
millis = Integer.pa... | // CHECKSTYLE:OFF
GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2009, GregorianCalendar.JANUARY, 10, 10, 23, 15);
c2.set(2009, GregorianCalendar.JANUARY, 10, 0, 0, 0);
Long l = c1.getTimeInMillis() - c2.getTimeInMi... |
358370_14 | class JulImportCallable extends AbstractProgressingCallable<Long> {
@Override
@SuppressWarnings({"PMD.AvoidInstantiatingObjectsInLoops", "PMD.CloseResource"})
public Long call()
throws Exception
{
if(!inputFile.isFile())
{
throw new IllegalArgumentException("'" + inputFile.getAbsolutePath() + "' is not a ... | createTempFile("/testcases/log.xml");
AppendOpStub buffer = new AppendOpStub();
JulImportCallable instance = new JulImportCallable(inputFile, buffer);
long result = instance.call();
if(logger.isInfoEnabled()) logger.info("Call returned {}.", result);
if(logger.isDebugEnabled()) logger.debug("Appended events... |
363849_3 | class OAuth {
public static HttpParameters decodeForm(String form) {
HttpParameters params = new HttpParameters();
if (isEmpty(form)) {
return params;
}
for (String nvp : form.split("\\&")) {
int equals = nvp.indexOf('=');
String name;
... | HttpParameters params = OAuth.decodeForm("one=" + reservedCharactersEncoded
+ "&" + "one=another&"
+ reservedCharactersEncoded + "=" + rfc3986UnreservedCharacters);
assertTrue(params.size() == 3);
Iterator<String> iter1 = params.get("one").iterator();
as... |
369176_0 | class ApacheResponse implements Response {
public URI getLocation() {
try {
String location = getHeaders().getFirst("Location");
if(location == null || location.equals(""))
return getRequest().getURI();
else
return new URI(location);
} catch (URISyntaxException e) {
throw new RestfulieExceptio... | URI origin = new URI("http://default.com");
when(request.getURI()).thenReturn(origin);
assertEquals( origin, response.getLocation() );
}
} |
376975_19 | class CollectionUtil {
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
public static Enumeration<T> createEnumerationFromIterator(Iterator<T> it);
public static T first(List<T> list);
}
class CollectionUtilTest {
@Test
public void testIsEmpty_n... | Assert.assertTrue(CollectionUtil.isEmpty(null));
}
} |
403568_5 | class Union extends GeoAggregateFunction {
@Override
protected void add(Geometry geometry) {
if (result == null) {
result = geometry;
} else {
if (geometry != null) {
result = result.union(geometry);
}
}
}
@Override protected ... | union.add(createPoint(3, 5));
union.add(createPoint(5, 3));
Object result = union.getResult();
assertThat(result, is(not(nullValue())));
Geometry geomResult = GeoDB.gFromWKB((byte[]) result);
assertThat(geomResult.getArea(), is(0.0));
assertTrue(geomResult.contai... |
446195_3 | class RangeFunctions {
public static boolean isBetween(long reading, long floor, long ceiling) {
return reading < ceiling && reading > floor;
}
public static boolean isAbove(long reading, long value);
public static boolean isBelow(long reading, long value);
}
class RangeFunctionsTest {
@Test
public void te... | assertThat(RangeFunctions.isBetween(2,1,3), is(true));
assertThat(RangeFunctions.isBetween(1,1,3), is(false));
assertThat(RangeFunctions.isBetween(3,1,3), is(false));
}
} |
459348_101 | class HeaderGenerator {
public void setHeaders(final Message message,
final Map<String, String> msgMap,
final DataType dataType,
final String address,
final @NonNull PersonRecord contact,
... | Message message = new MimeMessage();
Map<String, String> map = new HashMap<String, String>();
Date sent = new Date();
PersonRecord person = new PersonRecord(0, null, null, null);
map.put(Telephony.BaseMmsColumns._ID, "id");
map.put(Telephony.BaseMmsColumns.MESSAGE_TYPE,... |
466802_0 | class UserAccount {
public String getBiography() {
return biography;
}
public UserAccount();
public Long getAccountId();
public void setAccountId(Long accountId);
public Date getAccountCreationDate();
public void setAccountCreationDate(Date accountCreationDate);
public String... | UserAccountManager mgr = new UserAccountManager();
String bio = "Round the rugged rock the ragged rascal ran.";
mgr.createAndStoreUserAccount("johntestbio.smith", "testmyotherpasswordcleartext", "johntestbio@smith.com",
bio);
assertEquals(bio, mgr.getBiography("johntestbi... |
473362_6 | class CollocReducer extends MapReduceBase implements Reducer<GramKey,Gram,Gram,Gram> {
@Override
public void reduce(GramKey key,
Iterator<Gram> values,
OutputCollector<Gram,Gram> output,
Reporter reporter) throws IOException {
Gram.Type keyTyp... | // test input, input[*][0] is the key,
// input[*][1..n] are the values passed in via
// the iterator.
Gram[][] input = {
{new Gram("the", UNIGRAM), new Gram("the", UNIGRAM), new Gram("the", UNIGRAM)},
{new Gram("the", HEAD), new Gram("the best", NGRAM), new Gram("the worst", NGRAM)},
... |
474905_0 | class Customer {
public void setName(String name) {
this.name = name;
}
public Customer();
public Customer(String name);
public Long getId();
public String getName();
public boolean isArchived();
public void setArchived(boolean archived);
private static EntityManagerFactory emf;
private EntityManager ... |
try {
Customer customer = new Customer("Bob");
em.persist(customer);
em.flush();
em.detach(customer);
customer.setName("Bo");
em.merge(customer);
em.flush();
fail("Expected ConstraintViolationException wasn't thrown.");
} catch (ConstraintViolationException e) {
assertEquals(1, e.getCo... |
478661_36 | class CSVParser {
public String[] parseLine(String nextLine) throws IOException {
return parseLine(nextLine, false);
}
public CSVParser();
public CSVParser(char separator);
public CSVParser(char separator, char quotechar);
public CSVParser(char separator, char quotechar, char escap... | csvParser = new CSVParser(CSVParser.DEFAULT_SEPARATOR,
CSVParser.DEFAULT_QUOTE_CHARACTER,
CSVParser.DEFAULT_ESCAPE_CHARACTER,
CSVParser.DEFAULT_STRICT_QUOTES,
CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE,
true);
String testSt... |
489859_415 | class RestAnnotationProcessor implements Function<Invocation, HttpRequest> {
@Override
public GeneratedHttpRequest apply(Invocation invocation) {
checkNotNull(invocation, "invocation");
inputParamValidator.validateMethodParametersOrThrow(invocation);
Optional<URI> endpoint = Optional.absent();... | Invokable<?, ?> method = method(TestFormReplace.class, "oneForm", String.class);
Object form = processor.apply(Invocation.create(method, ImmutableList.<Object> of("robot")))
.getPayload().getRawContent();
assertEquals(form, "x-amz-copy-source=/robot");
}
} |
500697_95 | class TransformedMultivariateNormalSummary extends AbstractObservable implements MultivariateNormalSummary {
public boolean getDefined() {
return d_isDefined;
}
public TransformedMultivariateNormalSummary(MultivariateNormalSummary nested, double[][] matrix);
public double[] getMeanVector();
public double[][]... | TransformedMultivariateNormalSummary summary = new TransformedMultivariateNormalSummary(d_nested , TRANSFORM);
assertFalse(summary.getDefined());
d_results.makeSamplesAvailable();
assertTrue(summary.getDefined());
}
} |
500806_607 | class JmsEndpointComponent extends AbstractEndpointComponent {
@Override
protected Endpoint createEndpoint(String resourcePath, Map<String, String> parameters, TestContext context) {
JmsEndpoint endpoint;
if (resourcePath.startsWith("sync:")) {
endpoint = new JmsSyncEndpoint();
... | JmsEndpointComponent component = new JmsEndpointComponent();
try {
reset(referenceResolver);
component.createEndpoint("jms:queuename?param1=¶m2=value2", context);
Assert.fail("Missing exception due to invalid endpoint uri");
} catch (CitrusRuntimeException... |
508590_3 | class PropertyGraphSail extends SailBase {
void setFirstClassEdges(final boolean firstClassEdges) {
this.firstClassEdges = firstClassEdges;
}
public PropertyGraphSail(final Graph graph);
public PropertyGraphSail(final Graph graph,
final boolean firstClassEdges);
... | sail.setFirstClassEdges(false);
sc.close();
sc = sail.getConnection();
for (Statement st : get(null, null, null)) {
System.out.println("st: " + st);
}
assertEquals(30, sc.size());
assertEquals(30, count(null, null, null));
assertEquals(6, co... |
511297_48 | class CassandraHostConfigurator implements Serializable {
public CassandraHost[] buildCassandraHosts() {
if (this.hosts == null) {
throw new IllegalArgumentException("Need to define at least one host in order to apply configuration.");
}
String[] hostVals = hosts.split(",");
CassandraHost[] cas... | CassandraHostConfigurator cassandraHostConfigurator = new CassandraHostConfigurator("localhost:9170");
CassandraHost[] cassandraHosts = cassandraHostConfigurator.buildCassandraHosts();
assertEquals(1, cassandraHosts.length);
}
} |
520146_100 | class SEAGrid implements PlanetaryGrid {
@Override
public long getBinIndex(double lat, double lon) {
final int row = getRowIndex(lat);
final int col = getColIndex(lon, row);
return baseBin[row] + col;
}
public SEAGrid();
public SEAGrid(int numRows);
public static int... | // 3, 8, 12, 12, 8, 3
SEAGrid grid = new SEAGrid(6);
assertEquals(0, grid.getBinIndex(+75.0, -500.0));
assertEquals(0, grid.getBinIndex(+100, -120.0));
assertEquals(0, grid.getBinIndex(+75.0, -120.0));
assertEquals(2, grid.getBinIndex(+75.0, +120.0));
assertEqual... |
526139_189 | class GeometryTracker {
boolean hasValidArea() {
return area != null && !area.isEmpty();
}
GeometryTracker();
Rectangle2D getArea();
void add(Point2D.Double point);
private GeometryTracker tracker;
}
class GeometryTrackerTest {
private GeometryTracker tracker;
@Test
... | assertFalse(tracker.hasValidArea());
}
} |
533032_1 | class DocIdSetCardinality implements Cloneable, Comparable<DocIdSetCardinality> {
public void orWith(DocIdSetCardinality other) {
min = Math.max(min, other.min);
max = Math.min(1.0, max + other.max);
}
DocIdSetCardinality(double minCardinality, double maxCardinality);
public static DocIdSetCardinal... | DocIdSetCardinality c;
c = new DocIdSetCardinality(0.1, 0.2);
c.orWith(new DocIdSetCardinality(0.1, 0.2));
DocSetAssertions.assertRange(0.1, 0.4, c);
c = new DocIdSetCardinality(0.8, 0.9);
c.orWith(new DocIdSetCardinality(0.8, 0.9));
DocSetAssertions.assertRange(0.8, 1.0, c);
}
} |
536958_2 | class WebXmlIntegrator implements Integrator {
Node createFilterNode(Document doc) {
Node filterNode = doc.createElement("filter");
Node filterNameNode = doc.createElement("filter-name");
filterNameNode.appendChild(doc.createTextNode("infrared"));
Node filterClassNode = doc.createElement("filter-class");
fi... | WebXmlIntegrator web = new WebXmlIntegrator();
Document doc = createEmptyDocument();
Node n = web.createFilterNode(doc);
doc.appendChild(n);
String expected = " <filter><filter-name>infrared</filter-name>"+
"<filter-class>"+WebXmlIntegrator.FILTER_CLASS+"</filter-class>"+
"</filter... |
542927_85 | class Production {
public Object[] getJobIds() {
return workflow.getJobIds();
}
public Production(String id,
String name,
String outputPath,
String stagingPath,
boolean autoStaging,
Produ... | Production production = new Production("9A3F", "Toasting", null, null,
false, new ProductionRequest("test", "ewa"),
new MyWorkflowItem(new JobID("34627985F47", 4)));
assertArrayEquals(new Object[]{new JobID("3... |
551254_19 | class FileUtil {
public static File createTempDirectory() throws IOException {
File tmp = File.createTempFile("bpelunit", "");
tmp.delete();
tmp.mkdir();
return tmp;
}
private FileUtil();
public static byte[] readFile(File f);
public static String getFileNameWithoutSuffix(String fileName);
}
class Fi... | File f = null;
try {
f = FileUtil.createTempDirectory();
assertTrue(f.exists());
assertTrue(f.isDirectory());
assertEquals(0, f.list().length);
} finally {
if (f != null) {
f.delete();
}
}
}
} |
558963_40 | class HTTPCache {
public HTTPResponse execute(final HTTPRequest request) {
return execute(request, helper.isEndToEndReloadRequest(request));
}
public HTTPCache(CacheStorage storage, ResponseResolver resolver);
public void clear();
public CacheStorage getStorage();
public ResponseReso... | URI requestUri = URI.create("http://host1/some");
URI contentLocationUri = URI.create("http://host2/some/content/location");
URI locationUri = URI.create("http://host3/some/location");
HTTPRequest request = new HTTPRequest(requestUri, HTTPMethod.POST);
Headers responseHeaders = ... |
574877_37 | class JsonErrorResponseHandler implements HttpResponseHandler<AmazonServiceException> {
@Override
public AmazonServiceException handle(HttpResponse response) throws Exception {
JsonContent jsonContent = JsonContent.createJsonContent(response, jsonFactory);
byte[] rawContent = jsonContent.getRa... | httpResponse.setStatusCode(500);
expectUnmarshallerMatches();
when(unmarshaller.unmarshall(any(JsonNode.class)))
.thenReturn(new CustomException("error"));
AmazonServiceException ase = responseHandler.handle(httpResponse);
assertEquals(ErrorType.Service, ase.get... |
578435_68 | class Strings {
public static String dasherize(String word) {
return word.replaceAll("_", "-");
}
public static String tableize(String word);
public static String pluralize(String word);
public static String singularize(String word);
public static String underscore(String word);
public static String... | for (Map.Entry<String, String> entry : underscoresToDashes_.entrySet()) {
assertEquals(entry.getValue(), Strings.dasherize(entry.getKey()));
}
}
} |
581866_1 | class Messages {
public static IOTransition.IOLetter fullLetter(String message) {
Matcher matcher = lettersPattern.matcher(message);
if (matcher.matches()) {
if (matcher.group(1).equals("^")) {
if (matcher.group(2) == null) {
return new IOTransition.IOLetter(new Message(matcher.group... | IOTransition.IOLetter letter = Messages.fullLetter("^a<-b.m");
Assertions.assertThat(letter.label.toString()).isEqualTo("b -> a.m");
Assertions.assertThat(letter.type).isEqualTo(IOAlphabetType.INTERNAL);
}
} |
585380_4 | class KUID extends ByteArray<KUID> implements Identifier,
Key<KUID>, Xor<KUID>, Negation<KUID>, Cloneable, Digestable {
public boolean isCloserTo(KUID key, KUID otherId) {
return compareTo(key, otherId) < 0;
}
private KUID(byte[] key);
public static KUID createRandom(int length);
public static KU... | for (int i = 0; i < 1000; i++) {
KUID lookupId = KUID.createRandom(20);
KUID[] contacts = new KUID[] {
KUID.createRandom(lookupId),
KUID.createRandom(lookupId)
};
Arrays.sort(contacts, new XorComparator(lookupId));
TestCase.assertTrue(contacts[0].is... |
589869_0 | class DpmPixel {
public void reset(int i, int j) {
this.i = i;
this.j = j;
x = 0;
y = 0;
detector = 0;
view_zenith = 0.0;
sun_zenith = 0.0;
delta_azimuth = 0.0;
sun_azimuth = 0.0;
mus = 0.0;
muv = 0.0;
airMass = 0.0;
... | final DpmPixel dpmPixel = new DpmPixel(0,0);
dpmPixel.x = 3;
dpmPixel.y = 4;
dpmPixel.i = 5;
dpmPixel.j = 6;
dpmPixel.detector = 7;
dpmPixel.view_zenith = 8.0;
dpmPixel.sun_zenith = 9.0;
dpmPixel.delta_azimuth = 10.0;
dpmPixel.sun_azimuth ... |
590532_4 | class ParticipantIDParser {
public static String encode(String raw) {
String[] parts = parseId(raw);
return shorten(toBigInteger(parts[0])) + "-" +
shorten(toBigInteger(parts[1], parts[2])) + "-" +
shorten(new BigInteger(parts[3]));
}
private static BigInteger toBigInteger(String ip);
private s... |
String raw = "moho://127.0.0.1:8080/call/" + Math.abs(new UUID().getTime());
assertEquals(raw, ParticipantIDParser.decode(ParticipantIDParser.encode(raw)));
raw = "moho://34.67.128.98:80/call/" + Math.abs(new UUID().getTime());
assertEquals(raw, ParticipantIDParser.decode(ParticipantIDParser.encode(raw)))... |
591784_24 | class DefaultUpdateCheckManager implements UpdateCheckManager, Service {
public void checkMetadata( RepositorySystemSession session, UpdateCheck<Metadata, MetadataTransferException> check )
{
if ( check.getLocalLastUpdated() != 0
&& !isUpdatedRequired( session, check.getLocalLastUpdated(), ... | UpdateCheck<Metadata, MetadataTransferException> check = newMetadataCheck();
check.setPolicy( RepositoryPolicy.UPDATE_POLICY_NEVER );
session.setNotFoundCachingEnabled( true );
check.getFile().delete();
assertEquals( check.getFile().getAbsolutePath(), false, check.getFile().exis... |
597631_48 | class FractionalIdentityScorer extends AbstractScorer implements PairwiseSequenceScorer<S, C> {
@Override
public int getMinScore() {
return 0;
}
public FractionalIdentityScorer(PairwiseSequenceAligner<S, C> aligner);
public FractionalIdentityScorer(SequencePair<S, C> pair);
@Overrid... | assertEquals(scorer1.getMinScore(), 0);
assertEquals(scorer2.getMinScore(), 0);
}
} |
608316_15 | class StateManagerImpl implements StateManager {
@Override
public boolean isNew(Persistent persistent) {
return isNew;
}
public StateManagerImpl();
public void setManagedPersistent(Persistent persistent);
@Override public void setNew(Persistent persistent);
@Override public void clearNew(Persisten... | //newly created objects should be new
Assert.assertTrue(persistent.isNew());
}
} |
608843_3 | class OSMemory implements IMemorySystem {
IndexOutOfBoundsExceptionpublic native void setIntArray(int address, int[] ints, int offset,
int length, boolean swap) throws NullPointerException,
IndexOutOfBoundsException;
IndexOutOfBoundsExceptionprivate OSMemory();
... | )
public void testSetIntArray() {
IMemorySystem memory = Platform.getMemorySystem();
int[] values = { 3, 7, 31, 127, 8191, 131071, 524287, 2147483647 };
int[] swappedValues = new int[values.length];
for (int i = 0; i < values.length; ++i) {
swappedValues[i] =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.