I am testing a method using JUnit API and I think I am setting all the values but still I am getting NullPointerException. I don't want to catch this but I don't even expect it since I am setting my values. l = appConfigDao.getAppConfig(); is the line which throws exception and I am using Mockito to return List. For getCacheProvider() I am setting the value using setter but while debugging it shows as null but I don't get exception.
Method under test:
public List<AppConfigTO> getAppConfig(boolean ignoreCache ) {
List<AppConfigTO> l = null;
if( !ignoreCache ) {
if( getCacheProvider() != null ) {
l = (List<AppConfigTO>)getCacheProvider().getFromCache( CacheConstants.CONFIG_APPCONFIG, CacheConstants.TABLE_CACHE_KEY );
}
}
if( l == null ) {
l = appConfigDao.getAppConfig();
if( !ignoreCache ) {
if( getCacheProvider() != null ) {
getCacheProvider().addToCache( CacheConstants.CONFIG_APPCONFIG, CacheConstants.TABLE_CACHE_KEY, l );
}
}
}
return l;
}
JUnit test:
private ICacheProvider cacheProvider;
#Test
public void testGetAppConfig() throws Exception {
AppConfigManager configManager = new AppConfigManager();
configManager.setCacheProvider(cacheProvider);
List<AppConfigTO> list = new ArrayList<>();
// Mocking IAppConfigDao
IAppConfigDao configDao = Mockito.mock(IAppConfigDao.class);
Mockito.when(configDao.getAppConfig()).thenReturn(list);
list = configManager.getAppConfig(false);
}
This is just a happy path because I want to see if I am setting all the values correctly and then I will cover branch coverage, but if I stop getting exception.
Thanks,
Related
I'm writing a junit test case for a method in the data access layer, how to stub/verify a complex query using mockito?
checked the following links on how to stub a complex query:
- https://howtodoinjava.com/hibernate/hibernate-criteria-queries-tutorial/
- https://github.com/MorphiaOrg/morphia/issues/933
none of them match my case, and the documentation does not say much about it
https://static.javadoc.io/org.mockito/mockito-core/2.8.9/index.html?org/mockito/Mockito.html
Actual code :
public List<Content> getContentByParams(String entity, String channelId, String sectionId,
Integer limit, String[] retrievedFields) {
Query<Content> query = this.createQuery();
if (StringUtils.isNotBlank(channelId) && StringUtils.isNotBlank(sectionId)) {
query.and(query.criteria("name").equalIgnoreCase(entity),
query.criteria("channel").equal(channelId),
query.criteria("section").equal(sectionId));
System.out.println("after===============");
}
if (retrievedFields != null && retrievedFields.length > 0) {
System.out.println("retrieved fields");
for (String field : retrievedFields) {
query.project(field, true);
}
}
if (limit == null) {
limit = 4;
}
FindOptions findOptions = new FindOptions().limit(limit);
return query.asList(findOptions);
}
Test case :
public void getContentByEntitiesAndPrimaryChannelSection() {
FieldEnd<Criteria> mockFieldEndEntity = mock(FieldEnd.class);
FieldEnd<Criteria> mockFieldEndChannel = mock(FieldEnd.class);
FieldEnd<Criteria> mockFieldEndSection = mock(FieldEnd.class);
// doReturn(mockFieldEndEntity).when(query).criteria("name");
// doReturn(mockFieldEndChannel).when(query).criteria("channel");
// doReturn(mockFieldEndSection).when(query).criteria("section");
contentDAO.getContentByParams(entity, "channel_3", "section_3", 10, mockFields);
for (String field : mockFields) {
verify(query).project(field, true);
}
ArgumentCaptor<FindOptions> argument = ArgumentCaptor.forClass(FindOptions.class);
verify(query).asList(argument.capture());
FindOptions findOptions = argument.getValue();
assertEquals(10, findOptions.getLimit());
PowerMockito.verifyStatic(MongoQueryUtil.class, times(1));
}
I am unsure on how to add a test for the query creation part with the test current status it passes but it is not testing the query creation.
any help will be appreciated or if there is a documentation for it somewhere.
Hi I am using the HttpServletRequest and trying to get the set of headers set.
Here is the code :
public static Map<String, String> getHeaders(HttpServletRequest request) {
Map<String, String> headers = new HashMap<String, String>();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
String header = request.getHeader(headerName);
headers.put(headerName, header);
}
}
return headers;
}
This method seems to be throwing a Null pointer exception at the headerNames.nextElement().
Is it possible that the hasMoreElements check returns true but the element headerNames.nextElement in turn causes the null pointer exception?
Stack Trace :
Stack trace : Caused by: java.lang.NullPointerException at org.apache.tomcat.util.buf.ByteChunk.equalsIgnoreCase(ByteChunk.java:608) at
org.apache.tomcat.util.buf.MessageBytes.equalsIgnoreCase(MessageBytes.java:325)
at org.apache.tomcat.util.http.NamesEnumerator.findNext(MimeHeaders.java:414) at org.apache.tomcat.util.http.NamesEnumerator.nextElement(MimeHeaders.java:438)
at org.apache.tomcat.util.http.NamesEnumerator.nextElement(MimeHeaders.java:396) at generateRequestHeaderMap...
It would be great if you guys could help me out with this issue.
I suspect that the problem is caused by a mangled request. Here is what findNext() is doing (in Tomcat 6.0.18):
private void findNext() {
next=null;
for( ; pos< size; pos++ ) {
next=headers.getName( pos ).toString();
for( int j=0; j<pos ; j++ ) {
if( headers.getName( j ).equalsIgnoreCase( next )) {
// duplicate.
next=null;
break;
}
}
if( next!=null ) {
// it's not a duplicate
break;
}
}
// next time findNext is called it will try the
// next element
pos++;
}
The salient lines are this:
next=headers.getName( pos ).toString();
if( headers.getName( j ).equalsIgnoreCase( next )) {
If the header is mangled then it may be possible for getName(j) to return a null. If that happens, then the ByteChunk path for the equalsIgnoreCase method will throw an NPE.
If you are going to track this down scientifically, you need to:
get hold of the actual raw bytes of the request, and examine them forensically to determine the nature of the corruption (if any)
set up a test harness to allow you to run your app on this request with a debugger attached .... and trap the exception at source.
The non-scientific approach would be to upgrade Tomcat to the most recent patch release of Tomcat 6 ... or a later version. It might fix the problem. Or not.
Here's another report of this problem in Tomcat 6.0.20 from back in 2010:
https://mail-archives.apache.org/mod_mbox/tomcat-users/201002.mbox/%3C4B7EBCE4.1010604#christopherschultz.net%3E
This is how I successfully patched the Apache Tomcat in JBoss 6.1.0 Final (in deploy/jbossweb.sar/jbossweb.jar) based on Apache Tomcat 6.0.20 source code:
org.apache.tomcat.util.http.MimeHeaders.NamesEnumerator.findNext()
private void findNext() {
next=null;
for( ; pos< size; pos++ ) {
// (4 lines changed): check mb for null as suggested here: https://stackoverflow.com/questions/37493552/enumeration-null-pointer-exception/37493888#37493888
MessageBytes mb = headers.getName( pos );
if (mb != null) {
next=mb.toString();
}
for( int j=0; j<pos ; j++ ) {
// (2 lines changed): check mb and nex for null as suggested here: https://stackoverflow.com/questions/37493552/enumeration-null-pointer-exception/37493888#37493888
mb = headers.getName( j );
if(mb != null && next != null && mb.equalsIgnoreCase( next )) {
// duplicate.
next=null;
break;
}
}
// new (just 1 comment line): if mb == null we assume next == null, thus it will be a duplicate (i.e. not found, causing no break)
if( next!=null ) {
// it's not a duplicate
break;
}
}
// next time findNext is called it will try the
// next element
pos++;
}
Sure it does not avoid the non-thread safe implementation mentioned in https://mail-archives.apache.org/mod_mbox/tomcat-users/201002.mbox/%3c27699460.post#talk.nabble.com%3e but at least if avoids the NullPointerException during reading unnecessary headers.
In my code I call this method, as a preprocessing step to 'stem' words:
public void getStem(String word)
{
WordnetStemmer stem = new WordnetStemmer( dict );
List<String> stemmed_words = stem.findStems(word, POS.VERB);
System.out.println( stemmed_words.get(0) );
}
Usually everything is good if it gets a normal word (I'm using the Java Wordnet Interface to handle the stemming). The thing is--> I don't always get a normal word, somethings I get things along the lines of isa which is a conjunction of is and a. In such a case that method will return null and my program will crash. How can I defend against this?
This is how I call that code:
public Sentence(String verb, String object, String subject ) throws IOException
{
WordNet wordnet = new WordNet();
this.verb = verb;
this.object = object;
this.subject = subject;
wordnet.getStem( verb );
}
Eventually I want that to read:
this.verb = wordnet.getStem( verb );
I once heard about doing something with null objects, is that applicable here?
I tried this but it didn't work, but I want to do something like this:
public void getStem(String word)
{
WordnetStemmer stem = new WordnetStemmer( dict );
List<String> stemmed_words = stem.findStems(word, POS.VERB);
if( stemmed_words != null)
System.out.println( stemmed_words.get(0) );
else
System.out.println( word );
}
This is the output:
prevent
contain
contain
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0
at java.util.Collections$EmptyList.get(Collections.java:4454)
at inference_learner.WordNet.getStem(WordNet.java:76)
at inference_learner.Sentence.<init>(Sentence.java:23)
at inference_learner.RegEx.match_regex_patterns(RegEx.java:33)
at inference_learner.ReadFile.readFile(ReadFile.java:30)
at inference_learner.Main.main(Main.java:38)
That won't work because the List is not null, the List is empty.
You have to do the check like this if (stemmed_words.size() > 0)
try
if( stemmed_words != null && stemmed_words.size() > 0))
System.out.println( stemmed_words.get(0) );
else
System.out.println( word );
}
I want to modify an existing *.rptdesign file and save it under a new name.
The existing file contains a Data Set with a template SQL select statement and several DS parameters.
I'd like to use an actual SQL select statement which uses only part of the DS parameters.
However, the following code results in the exception:
Exception in thread "main" `java.lang.RuntimeException`: *The structure is floating, and its handle is invalid!*
at org.eclipse.birt.report.model.api.StructureHandle.getStringProperty(StructureHandle.java:207)
at org.eclipse.birt.report.model.api.DataSetParameterHandle.getName(DataSetParameterHandle.java:143)
at org.eclipse.birt.report.model.api.DataSetHandle$DataSetParametersPropertyHandle.removeParamBindingsFor(DataSetHandle.java:851)
at org.eclipse.birt.report.model.api.DataSetHandle$DataSetParametersPropertyHandle.removeItems(DataSetHandle.java:694)
--
OdaDataSetHandle dsMaster = (OdaDataSetHandle) report.findDataSet("Master");
HashSet<String> bindVarsUsed = new HashSet<String>();
...
// find out which DS parameters are actually used
HashSet<String> bindVarsUsed = new HashSet<String>();
...
ArrayList<OdaDataSetParameterHandle> toRemove = new ArrayList<OdaDataSetParameterHandle>();
for (Iterator iter = dsMaster.parametersIterator(); iter.hasNext(); ) {
OdaDataSetParameterHandle dsPara = (OdaDataSetParameterHandle)iter.next();
String name = dsPara.getName();
if (name.startsWith("param_")) {
String bindVarName = name.substring(6);
if (!bindVarsUsed.contains(bindVarName)) {
toRemove.add(dsPara);
}
}
}
PropertyHandle paramsHandle = dsMaster.getPropertyHandle( OdaDataSetHandle.PARAMETERS_PROP );
paramsHandle.removeItems(toRemove);
What is wrong here?
Has anyone used the DE API to remove parameters from an existing Data Set?
I had similar issue. Resolved it by calling 'removeItem' multiple times and also had to re-evaluate parametersIterator everytime.
protected void updateDataSetParameters(OdaDataSetHandle dataSetHandle) throws SemanticException {
int countMatches = StringUtils.countMatches(dataSetHandle.getQueryText(), "?");
int paramIndex = 0;
do {
paramIndex = 0;
PropertyHandle odaDataSetParameterProp = dataSetHandle.getPropertyHandle(OdaDataSetHandle.PARAMETERS_PROP);
Iterator parametersIterator = dataSetHandle.parametersIterator();
while(parametersIterator.hasNext()) {
Object next = parametersIterator.next();
paramIndex++;
if(paramIndex > countMatches) {
odaDataSetParameterProp.removeItem(next);
break;
}
}
if(paramIndex < countMatches) {
paramIndex++;
OdaDataSetParameter dataSetParameter = createDataSetParameter(paramIndex);
odaDataSetParameterProp.addItem(dataSetParameter);
}
} while(countMatches != paramIndex);
}
private OdaDataSetParameter createDataSetParameter(int paramIndex) {
OdaDataSetParameter dataSetParameter = StructureFactory.createOdaDataSetParameter();
dataSetParameter.setName("param_" + paramIndex);
dataSetParameter.setDataType(DesignChoiceConstants.PARAM_TYPE_INTEGER);
dataSetParameter.setNativeDataType(1);
dataSetParameter.setPosition(paramIndex);
dataSetParameter.setIsInput(true);
dataSetParameter.setIsOutput(false);
dataSetParameter.setExpressionProperty("defaultValue", new Expression("<evaluation script>", ExpressionType.JAVASCRIPT));
return dataSetParameter;
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have this Hash Set code and when I try to run my compile method on it I get the Null Pointer Exception: null error on it. Here is the code:
private void initKeywords() {
keywords = new HashSet<String>();
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}
private boolean isIdent(String t) {
if (keywords.contains(t)) { ***//This is the line I get the Error***
return false;
}
else if (t != null && t.length() > 0 && Character.isLetter(t.charAt(0))) {
return true;
}
else {
return false;
}
}
The other lines that goes along with this error is:
public void compileProgram() {
System.out.println("compiling " + filename);
while (theToken != null) {
if (equals(theToken, "int") || equals(theToken, "final")) {
compileDeclaration(true);
} else {
compileFunction(); //This line is giving an error with the above error
}
}
cs.emit(Machine.HALT);
isCompiled = true;
}
private void compileFunction() {
String fname = theToken;
int entryPoint = cs.getPos();
if (equals(fname, "main")) {
cs.setEntry(entryPoint);
}
if (isIdent(theToken)) theToken = t.token(); ***//This line is giving an error***
else t.error("expecting identifier, got " + theToken);
symTable.allocProc(fname,entryPoint);
accept("(");
compileParamList();
accept(")");
compileCompound(true);
if (equals(fname, "main")) cs.emit(Machine.HALT);
else cs.emit(Machine.RET);
}
Are you sure you're running initKeywords() before isIdent()?
Either keywords or t is null. Using either a debugger or print statements it should be pretty simple to determine. If keywords is null, I'd assume that initKeywords() has not been called yet.
You probably want to call initKeywords from the constructor of this object.
I personally try to stay away from init methods. As previously mentioned, a constructor serves as an initializer, and so does the static block:
private final static Set<String> KEYWORDS = new HashSet<String>();
static {
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}