javax.naming.CommunicationException: Connection reset [Root exception is java.net.SocketException: Connection reset]; remaining name - ldap

I am getting socket exception when I try to connect LDAP. Here is my sample code. I am seeing this issue in java 8. I never observed this issue in the earlier java versions.
public static DirContext getDirectoryContext() throws NamingException {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,
Common.getProperty("ldap.context.factory"));
env.put(Context.PROVIDER_URL,
Common.getProperty("ldap.provider.url"));
env.put(Context.SECURITY_AUTHENTICATION,
Common.getProperty("ldap.security.authentication"));
env.put(Context.SECURITY_PRINCIPAL,
Common.getProperty("ldap.security.principal"));
env.put(Context.SECURITY_CREDENTIALS,
Common.getProperty("ldap.security.credential"));
context = new InitialDirContext(env);
log.debug("NamingContext Initialized");
return context;
}
context = getDirectoryContext();
I am using the same context for all LDAP calls.
private NamingEnumeration getResultsFromLdap(String searchFilter) {
NamingEnumeration results = null;
try {
// Getting the list from LDAP matching the given filter
SearchControls sControls = new SearchControls();
sControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String baseContext = Common.getProperty("ldap.base.context");
results = context.search(baseContext, searchFilter, sControls);
} catch (Exception e) {
log.error("EXCEPTION IN getLDAPConnection METHOD, searchFilter : "
+ searchFilter + " : Exception Message : " + e.getMessage());
}
return results;
} // End of getLDAPConnection_SearchResults
Can someone help?

Related

javax.net.ssl.sslpeerunverifiedexception no peer certificate Error In lifelogApi

We are getting SSL peer unverified error while fetching the access token from Lifelog api. I am able to get the authcode, but when i am trying to get access token, it is giving me SSL peer error. It works fine with few device, but most of the device it is giving SSL error.
private void getAccessToken(final String authCode)
{
final String finalUrl = String.format("https://platform.lifelog.sonymobile.com/oauth/2/token?client_id=%s&client_secret=%s&code=%s",CLIENT_ID,CLIENT_SECRET,authCode);
Thread networkThread = new Thread(new Runnable() {
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(finalUrl);
// Add your data
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("client_id", CLIENT_ID));
nameValuePairs.add(new BasicNameValuePair("client_secret", CLIENT_SECRET));
nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
nameValuePairs.add(new BasicNameValuePair("code", authCode));
AbstractHttpEntity ent=new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
post.setEntity(ent);
// Execute HTTP Post Request
HttpResponse response =null;
try {
response = client.execute(post);
Log.d("Response:" , response.toString());
} catch (IOException e) {
e.printStackTrace();
}
String dataObject = response.toString();
JSONObject obj;
if(dataObject != null) {
obj = null;
try {
String json_string = EntityUtils.toString(response.getEntity());
// displayToast(json_string);
obj = new JSONObject(json_string);
SharedPreferences prefs =getSharedPreferences("Myprefs", Context.MODE_PRIVATE);
prefs.edit().putString("Access_token", obj.getString("access_token"));
// prefs.edit().putString(AUTH_REFRESH_TOKEN, obj.getString(AUTH_REFRESH_TOKEN));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
});
networkThread.start(); }
The problem may be with your use of HttpClient. It looks like Google has removed support for this call in Android 6.0.
http://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
You should be able to use HttpsURLConnection instead of Httpclient to access the Lifelog Web Service.
I'm using google-oauth-client, I was able to use on Android 5.x with this initialization for
import com.google.api.client.http.HttpTransport;
private void initializeSocketFactory() {
if (Build.VERSION.SDK_INT >= 23) {
HTTP_TRANSPORT = new NetHttpTransport();
} else {
//Android 5 and bellow needs this SSL Socket factory initialization
try {
SSLContext sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(null, null, null);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
NetHttpTransport.Builder netTransportBuilder = new NetHttpTransport.Builder();
netTransportBuilder.setSslSocketFactory(socketFactory);
HTTP_TRANSPORT = netTransportBuilder.build();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
Log.e(LOG_TAG, "Problem instantiating cipher for ssl socket", e);
}
}
}
You use HTTP_TRANSPORT to instantiate:
import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;

SpringLdap 2 over ldaps

I've followed an interesting webinar about springLdap and I'm planning to migrate my current Ldap interface to SpringLdap. However I haven't seen any easy way to connect to an LDAPS server. In my current implementation I had to do something like:
String nextToken = stCc.nextToken();
Properties envP = initializeEnv(nextToken, userPassword);
try
{
LdapContext ctx = new InitialLdapContext(envP, null);
//System.out.println(nextToken + " successfully validation");
return ctx;
}
and
private Properties initializeEnv(String userName, String userPassword) throws IOException
{
Properties envP = new Properties();
envP.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
envP.put(Context.PROVIDER_URL, (String) properties.get("ldap.server.url"));
if (userName != null)
envP.setProperty(Context.SECURITY_PRINCIPAL, userName);
if (userPassword != null)
envP.setProperty(Context.SECURITY_CREDENTIALS, userPassword);
envP.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
envP.setProperty("java.naming.security.protocol", "ssl");
envP.setProperty("com.sun.jndi.ldap.connect.pool", "true");
envP.put("java.naming.ldap.factory.socket", "org.mycompany.ldap.CustSSLSocketFactory");
return envP;
}
and more:
public EmblSSLSocketFactory()
{
try
{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]
{
new DummyTrustmanager()
}, new SecureRandom());
socketFactory = ctx.getSocketFactory();
}
catch (Exception ex)
{
ex.printStackTrace(System.err); /* handle exception */
}
}
Which is the equivalent (and possibly easier) way to do such authentication over TLS with SPRING-LDAP 2?
Thanks

Client giving error when invoking a secured web service

I have written a client that invokes webservice. My client is:
String publisherEPR = "https://abc:8280/services/ProviderPublication";
protected void publicationOpenSession(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("Inside publicationOpenSession");
date = new Date();
namespace = "http://www.openoandm.org/xml/ISBM/";
fac = OMAbstractFactory.getOMFactory();
OMNamespace ns = fac.createOMNamespace(namespace, "ns1");
OMElement result = null;
channelURI = request.getParameter("TxtPublisher1ChannelURI");
textfield = request.getParameter("TxtAreaServicePublisherLog");
String finalChannelURI = "";
int count = 0;
try {
if (channelURI != null && (channelURI.indexOf(".") > -1)) {
System.out.println("Inside If Checking Channel URI");
String[] tempChannelURI = channelURI.split("\\.");
for (count = 0; count < tempChannelURI.length - 1; count++) {
finalChannelURI = finalChannelURI + tempChannelURI[count];
if (count < tempChannelURI.length - 2) {
finalChannelURI = finalChannelURI + ".";
}
}
System.out.println("Inside If Checking Channel URI : " + finalChannelURI);
}
System.out.println("OpenPublicationSession" + finalChannelURI);
System.out.println(publisherEPR);
OMElement OpenPublicationSessionElement = fac.createOMElement("OpenPublicationSession", ns);
OMElement ChannelURIElement = fac.createOMElement("ChannelURI", ns);
ChannelURIElement.setText(finalChannelURI);
OpenPublicationSessionElement.addChild(ChannelURIElement);
String webinfFolder = request.getSession().getServletContext().getRealPath("/WEB-INF");
ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(
webinfFolder, webinfFolder + "/conf/axis2.xml");
Options options = new Options();
ServiceClient client = new ServiceClient(ctx, null);
EndpointReference targetEPR = new EndpointReference(publisherEPR);
options.setTo(targetEPR);
options.setAction("urn:OpenPublicationSession");
options.setManageSession(true);
options.setUserName(user_name);
java.util.Map<String, Object> m = new java.util.HashMap<String, Object>();
/*m.put("javax.net.ssl.trustStorePassword", "wso2carbon");
m.put("javax.net.ssl.trustStore", "wso2carbon.jks");
*/
System.out.println(new Date() + " Checkpoint1");
// We are accessing STS over HTTPS - so need to set trustStore parameters.
System.setProperty("javax.net.ssl.trustStore", "client.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "apache");
/*m.put("javax.net.ssl.trustStore", "client.jks");
m.put("javax.net.ssl.trustStorePassword", "apache");*/
/*m.put("org.apache.ws.security.crypto.provider","org.apache.ws.security.components.crypto.Merlin");
m.put("org.apache.ws.security.crypto.merlin.keystore.type", "jks");
m.put("org.apache.ws.security.crypto.merlin.keystore.password","apache");
m.put("org.apache.ws.security.crypto.merlin.file", "client.jks");*/
//options.setProperties(m);
System.out.println(new Date() + " Checkpoint2");
client.setOptions(options);
MessageContext messageContext = new MessageContext();
messageContext.setOptions(options);
messageContext.setMessageID("MyMessageID");
System.out.println("provider:user_name: " + user_name);
messageContext.setProperty("username", user_name);
messageContext.setProperty("password", user_password);
MessageContext.setCurrentMessageContext(messageContext);
messageContext.setProperty("myproperty", "mypropertyvalue");
String falconNS = "http://cts.falcon.isbm";
falcon = fac.createOMNamespace(falconNS, "falcon");
OMElement falconUserElement = fac.createOMElement("FalconUser", falcon);
falconUserElement.setText(user_name);
client.addHeader(falconUserElement);
// invoke web-service
try {
errorText = "Client Didnt Respond.";
result = client.sendReceive(OpenPublicationSessionElement);
System.out.println(result.toString());
OMElement SessionIDElement = null;
SessionIDElement = result.getFirstChildWithName(new QName(namespace, "SessionID"));
SessionID = SessionIDElement.getText();
request.setAttribute("PublisherSession", SessionID);
StringBuffer text = new StringBuffer();
text.append((request.getParameter("TxtAreaServicePublisherLog")).trim());
text.trimToSize();
SessionID = SessionIDElement.getText();
StringBuffer publisherLog = new StringBuffer();
publisherLog.append((request.getParameter("TxtAreaServicePublisherLog")).trim());
publisherLog.trimToSize();
System.out.println("Checkpoint1");
publisherLog.append("\n" + new Date().toString() + " " + PUBLISHER_SESSION_SUCCESS_MSG + SessionID);
request.setAttribute("textMessageService2", publisherLog);
request.setAttribute("PublisherSession", SessionID);
System.out.println("Checkpoint3");
RequestDispatcher rd = request.getRequestDispatcher("/Provider.jsp");// hard-coded
try {
rd.forward(request, response);
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ServletException se) {
se.printStackTrace();
}
} catch (Exception e) {
errorText = "Client not responding";
buildErrorLog(request, response, e);
e.printStackTrace();
}
//buildCallLog(request, response, result);
} catch (Exception e) {
e.printStackTrace();
buildErrorLog(request, response, e);
}
}
And i have a proxy service upon which i have implemented security and its url is:
https://abc:8280/services/ProviderPublication.
My handle method inside callback handler is:
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
System.out.println("\n \n " + new Date() + " ISBMClient.PWCBHandler.handle");
if(MessageContext.getCurrentMessageContext() == null){
System.out.println("CurrentMessageContext is null");
}else{
//get the credentials from the jsp
System.out.println("MessageID: " + MessageContext.getCurrentMessageContext().getMessageID());
dynamicUser = MessageContext.getCurrentMessageContext().getProperty("username").toString();
dynamicPassword = MessageContext.getCurrentMessageContext().getProperty("password").toString();
System.out.println("MessageContext user_name: " + dynamicUser);
System.out.println("MessageContext user_password: " + dynamicPassword);
}
for (int i = 0; i < callbacks.length; i++) {
WSPasswordCallback pwcb = (WSPasswordCallback)callbacks[i];
pwcb.setIdentifier(dynamicUser);
String id = pwcb.getIdentifier();
System.out.println("Invoking service with user: " + id);
if(dynamicUser.equals(id)){
pwcb.setPassword(dynamicPassword);
}
}
}
Now the problem is when i invoke this proxy service through my client code i am getting exception as
[INFO] Unable to sendViaPost to url[https://abc:8280/services/ProviderPublication]
org.apache.axis2.AxisFault: Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document).
at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:78)
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:84)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:621)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:555)
at org.apache.axis2.client.ServiceClient.sendReceive(ServiceClient.java:531)
at cts.falcon.isbm.client.Provider.publicationOpenSession(Provider.java:557)
at cts.falcon.isbm.client.Provider.doPost(Provider.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.xml.stream.XMLStreamException: Trying to write END_DOCUMENT when document has no root (ie. trying to output empty document).
at com.ctc.wstx.sw.BaseStreamWriter.throwOutputError(BaseStreamWriter.java:1473)
at com.ctc.wstx.sw.BaseStreamWriter.reportNwfStructure(BaseStreamWriter.java:1502)
at com.ctc.wstx.sw.BaseStreamWriter.finishDocument(BaseStreamWriter.java:1663)
at com.ctc.wstx.sw.BaseStreamWriter.close(BaseStreamWriter.java:288)
at org.apache.axiom.util.stax.wrapper.XMLStreamWriterWrapper.close(XMLStreamWriterWrapper.java:46)
at org.apache.axiom.om.impl.MTOMXMLStreamWriter.close(MTOMXMLStreamWriter.java:222)
at org.apache.axiom.om.impl.llom.OMSerializableImpl.serializeAndConsume(OMSerializableImpl.java:192)
at org.apache.axis2.transport.http.SOAPMessageFormatter.writeTo(SOAPMessageFormatter.java:74)
... 38 more
But the same code is working for another web service written in eclipse. What am i doing wrong? Looking forward to your answers. Thanks in advance
You need to set SOAP envelope along with SOAP body which carries your payload from Service Client. I think that cause this problem. Please refer this blog post and refactor your code to add that.
http://amilachinthaka.blogspot.com/2009/09/sending-arbitrary-soap-message-with.html
A little late on the response here, but I ran into the same error message and after further digging it was due to some SSL certificate failures.
There were 2 ways to fix this:
Adding trusted certificate to Java using the keytool command.
OR
Using your own custom code to accept all certs (ex. below with a acceptallCerts() method)
public class SslUtil {
private static class SmacsTrustManager implements X509TrustManager {
#Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
#Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
public static void acceptAllCerts(){
try{
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new SmacsTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
}catch (Exception e){
}
}
}

ldap Naming Exception

am trying to get the user details from ADAM Active Directory.
i used the following java code.
import javax.naming.*;
import javax.naming.directory.*;
import java.util.Hashtable;
public class SimpleQuery {
public static void main(String[] args) {
StringBuffer output = new StringBuffer();
attribute="street";
query="(&(cn=ldap1))";
try {
String url = "ldap://172.16.12.178:389/cn=users,dc=sharepoint,dc=com";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
DirContext context = new InitialDirContext(env);
String[] attributeFilter = {"cn", "givenName", "SN", "street", "streetAddress", "postalAddress", "postOfficeBox", "l", "st", "postalCode", "c", "telephoneNumber", "homePhone", "mobile", "pager", "mail", "objectCategory", "objectClass", "userAccountControl"};
SearchControls ctrl = new SearchControls();
ctrl.setReturningAttributes(attributeFilter);
ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
NamingEnumeration enumeration = context.search("", query, ctrl);
while (enumeration.hasMore()) {
SearchResult result = (SearchResult) enumeration.next();
Attributes attribs = result.getAttributes();
NamingEnumeration values = ((BasicAttribute) attribs.get(attribute)).getAll();
while (values.hasMore()) {
if (output.length() > 0) {
output.append("|");
}
output.append(values.next().toString());
}
}
} catch (Exception e) {
System.out.println("Exception : "+e);
e.printStackTrace();
}
System.out.print(output.toString());
}
public SimpleQuery() {}}
and am getting this exception:
javax.naming.NamingException: [LDAP: error code 1 - 000004DC: LdapErr: DSID-0C09
06DC, comment: In order to perform this operation a successful bind must be comp
leted on the connection., data 0, v1db0 ]; remaining name ''
Is there any attribute i need to put?.
Please guide me.
Thanks
You're attempting the operation anonymously and it isn't permitted. You need to set Context.SECURITY_PRINCIPAL/SECURITY_CREDENTIALS in the env before attempting the operation.

Powermock: ProcessBuilder redirectErrorStream giving nullPointerException

I am using powermock to mock some native command invocation using process builder. the strange thing is these test pass sometimes and fail sometimes giving a NPE. Is this a powermock issue or some gotcha in the program.
Here is a snippet of the class I am testing:
public void method1(String jsonString, String filename) {
try {
JSONObject jObj = new JSONObject(jsonString);
JSONArray jArr = jObj.getJSONArray("something");
String cmd = "/home/y/bin/perl <perlscript>.pl<someConstant>" + " -k " + <someConstant> + " -t " + <someConstant>;
cmd += vmArr.getJSONObject(i).getString("jsonKey");
ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
pb.redirectErrorStream(false);
Process shell = pb.start();
shell.waitFor();
if (shell.exitValue() != 0) {
throw new RuntimeException("Error in Collecting the logs. cmd="+cmd);
}
StringBuilder error = new StringBuilder();
InputStream iError = shell.getErrorStream();
BufferedReader bfr =
new BufferedReader(
new InputStreamReader(iError));
String line = null;
while ((line = bfr.readLine()) != null) {
error.append(line + "\n");
}
if (!error.toString().isEmpty()) {
LOGGER.error(error`enter code here`);
}
iError.close();
bfr.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
and the unit test case is:
#PrepareForTest( {<Classtobetested>.class, ProcessBuilder.class,Process.class, InputStream.class,InputStreamReader.class, BufferedReader.class} )
#Test(sequential=true)
public class TestClass {
#Test(groups = {"unit"})
public void testMethod() {
try {
ProcessBuilder prBuilderMock = createMock(ProcessBuilder.class);
Process processMock = createMock(Process.class);
InputStream iStreamMock = createMock(InputStream.class);
InputStreamReader iStrRdrMock = createMock(InputStreamReader.class);
BufferedReader bRdrMock = createMock(BufferedReader.class);
String errorStr =" Error occured";
String json = <jsonStringInput>;
String cmd = "/home/y/bin/perl <perlscript>.pl -k "+<someConstant>+" -t "+<someConstant>+" "+<jsonValue>;
expectNew(ProcessBuilder.class, "bash", "-c", cmd).andReturn(prBuilderMock);
expect(prBuilderMock.redirectErrorStream(false)).andReturn(prBuilderMock);
expect(prBuilderMock.start()).andReturn(processMock);
expect(processMock.waitFor()).andReturn(0);
expect(processMock.exitValue()).andReturn(0);
expect(processMock.getErrorStream()).andReturn(iStreamMock);
expectNew(InputStreamReader.class, iStreamMock)
.andReturn(iStrRdrMock);
expectNew(BufferedReader.class, iStrRdrMock)
.andReturn(bRdrMock);
expect(bRdrMock.readLine()).andReturn(errorStr);
expect(bRdrMock.readLine()).andReturn(null);
iStreamMock.close();
bRdrMock.close();
expectLastCall().once();
replayAll();
<ClassToBeTested> instance = new <ClassToBeTested>();
instance.method1(json, fileName);
verifyAll();
} catch (Exception e) {
Assert.fail("failed while collecting log.", e);
}
}
I get an error on execution and the test case fails..
Caused by: java.lang.NullPointerException
at java.lang.ProcessBuilder.start(ProcessBuilder.java:438)
Note: I do not get this error on all executions. Sometimes it passes and sometimes it fails. I am not able to understand this behavior. Also, I have camouflaged some variable names because of the copyright issues.
Since your are mocking the constructor call you have to prepare your code as wall. This is because the constructor invocation is part of your code. Read more in the PowerMock documentation:
http://code.google.com/p/powermock/wiki/MockConstructor