I would like mock DefaultHttpClient.java and execute method in AbstractHttpClient.java, DefaultHttpClient extends AbstractHttpClient java class, and execute method is final method, so i need to powermock to mock final method.
#RunWith(PowerMockRunner.class)
#PrepareForTest(DefaultHttpClient.class)
//#PrepareForTest(AbstractHttpClient.class)
public class RestClientTest {
DefaultHttpClient client;
RestClient restClient = new RestClient();
#Test
public void getAll() throws Exception{
client = PowerMockito.spy(new DefaultHttpClient());
//PowerMockito.mock(DefaultHttpClient.class);
//Mockito.mock(DefaultHttpClient.class);
HttpResponse response = PowerMockito.mock(HttpResponse.class);
MarketplaceTO sampleData = new MarketplaceTO();
sampleData.setName("name");
//String endpoint = "";
//ProtocolVersion protoCol = new ProtocolVersion("HTTP", 2, 1);
//StatusLine status = new BasicStatusLine(protoCol, HttpStatus.SC_OK, null);
//HttpResponse response = new BasicHttpResponse(status);
BasicHttpEntity entity = new BasicHttpEntity();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(sampleData);
oos.flush();
oos.close();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
entity.setContent(is);
entity.setContentLength(is.available());
response.setEntity(entity);
//PowerMockito.doNothing().when((AbstractHttpClient)client).execute(Mockito.any(HttpUriRequest.class),Mockito.any(HttpContext.class));
PowerMockito.doReturn(response).when(client).execute(Mockito.any(HttpUriRequest.class));
//HttpGet getRequest = new HttpGet(endpoint);
//PowerMockito.when(client.execute(Mockito.any(HttpGet.class))).thenReturn(response);
//Mockito.stub(client.execute(getRequest)).toReturn(response);
//System.out.println("code "+response.getStatusLine().getStatusCode());
EMResponse<MarketplaceTO> responseData = restClient.getAll("", MarketplaceTO.class);
//System.out.println("name is "+responseData.getModelObject().getName());
Assert.assertEquals("name", responseData.getModelObject().getName());
}
}
and RestClient.java has
public <T> EMResponse<T> getAll(String entity, Class<T> entityClass) {
StringBuffer bufferedReader = null;
String output = "";
EMResponse<T> emResponse = null;
EMError emError = null;
ObjectMapper objectMapper = new ObjectMapper();
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
bufferedReader = new StringBuffer();
String endpoint = /*EntityManagerProperties
.get(EntityManagerProperties.ENTITY_MANAGER_SERVICE_URL)
+ "/" + entity*/"http://google.com/abcd";
HttpGet getRequest = new HttpGet(endpoint);
HttpResponse response = httpClient.execute(getRequest);
System.out.println("code "+response.getStatusLine().getStatusCode());
return getEntityObjects(response, entityClass, true);
} catch (ClientProtocolException e) {
logger.error("Exception", e);
} catch (IOException e) {
logger.error("Exception", e);
} finally {
//httpClient.getConnectionManager().shutdown();
}
return emResponse;
}
if i call after mocking execute method, then also it is calling actual method.
Please help me. sorry for my english.
Reason why its calling original execute method is because you have used a constructor
DefaultHttpClient httpClient = new DefaultHttpClient();
in RestClient.java class.
so you should must mock the constructor and return your mocked object
Add this line
whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(client);
before using:
PowerMockito.doReturn(response).when(client)
.execute(Mockito.any(HttpUriRequest.class));
and
Change #PrepareForTest(DefaultHttpClient.class) to #PrepareForTest({DefaultHttpClient.class, RestClient.class})
This will solve your problem.
Related
I have been trying to display nearby locations from my current location. But when i run it and click the button to view the nearby locations nothing appears. The first time i ran it, it displayed but when i backed out and came back in, it didnt display anything. i tried cleaning the project and other methods.
this is the method in my main class:
public void findRestaurants(View v){
StringBuilder stringBuilder = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
stringBuilder.append("location="+latLngCurrent.latitude + "," +latLngCurrent.longitude);
stringBuilder.append("&radius="+5000);
stringBuilder.append("&keyword="+"restaurant");
stringBuilder.append("&key="+getResources().getString(R.string.google_map_keyy));
String url = stringBuilder.toString();
Object dataTransfer[] = new Object[2];
dataTransfer[0] = mMap;
dataTransfer[1] = url;
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
}
public class getNearbyPlaces extends AsyncTask<Object,String,String> {
GoogleMap mMap;
String url;
InputStream is;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String data;
#Override
protected String doInBackground(Object... objects) {
mMap = (GoogleMap)objects[0];
url = (String)objects[1];
try {
URL myurl = new URL(url);
HttpURLConnection httpURLConnection = (HttpURLConnection) myurl.openConnection();
httpURLConnection.connect();
is = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
stringBuilder = new StringBuilder();
while((line = bufferedReader.readLine() ) != null){
stringBuilder.append(line);
}
data = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
try {
JSONObject parentObject = new JSONObject(s);
JSONArray resultsArray = parentObject.getJSONArray("results");
for (int i = 0; i<resultsArray.length(); i++){
JSONObject jsonObject = resultsArray.getJSONObject(i);
JSONObject locationObj = jsonObject.getJSONObject("geometry").getJSONObject("location");
String latitude = locationObj.getString("lat");
String longitude = locationObj.getString("lng");
JSONObject nameObject = resultsArray.getJSONObject(i);
String name_restaurant = nameObject.getString("name");
String vicinity = nameObject.getString("vicinity");
LatLng latLng = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
MarkerOptions markeroptions = new MarkerOptions();
markeroptions.title(vicinity);
markeroptions.position(latLng);
mMap.addMarker(markeroptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
it worked the first time when i lunched it. Did i do something wrong?
hope you are doing fine. Can you replace the lines
new getNearbyPlaces().execute(dataTransfer);
instead of these 2 lines
getNearbyPlaces getnearbyPlaces = new getNearbyPlaces();
getnearbyPlaces.execute(dataTransfer);
I am not sure whether this is going to impact much, but this is the way AsyncTask class should be called.
If this is not working, can you share the entire code of this java page, so we can look at how findRestaurant() method is called.
Question: This doesn't seem to work.
#Post("/register")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#View("register")
#Error(exception = ConstraintViolationException.class)
def register(HttpRequest<?> request, ConstraintViolationException constraintViolationException) {
Optional<RegisterFormData> registerFormDataOptional = request.getBody(RegisterFormData.class)
Map<String, Object> map = new HashMap<>()
if(registerFormDataOptional.isPresent()){
RegisterRequest registerRequest = new RegisterRequest(registerFormDataOptional.get().properties)
registerRequest.returnSecureToken = true
try {
def registerResponse = firebaseClient.register(registerRequest, this.firebaseApiKey).blockingSingle()
SendEmailVerificationRequest sendEmailVerificationRequest = new SendEmailVerificationRequest()
sendEmailVerificationRequest.requestType = 'VERIFY_EMAIL'
sendEmailVerificationRequest.idToken = registerResponse.idToken
firebaseClient.sendEmailVerification(sendEmailVerificationRequest, this.firebaseApiKey)
HttpResponse.redirect(URI.create('/register-success'))
}catch(HttpClientResponseException ex){
map.put('errors', [ex.message])
return map
}
}else{
map.put('errors', violationMessageSource.violationsMessages(constraintViolationException.constraintViolations))
return map
}
}
gives me a
{"message":"Required argument [ConstraintViolationException constraintViolationException] not specified","path":"/constraintViolationException","_links":{"self":{"href":"/auth/register","templated":false}}}
Currently using Micronaut and Thymeleaf. Anyone know what else am I missing? I was following the examples from https://guides.micronaut.io/micronaut-error-handling/guide/index.html
The whole point here is to pass some error messages from the controller back to the UI when constraint violations happen. The default one that uses annotations #Body and #Valid don't work since it returns json errors without any views.
#Inject
Validator validator
#Inject
ViolationMessageSource violationMessageSource
#Post("/register")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
def register(HttpRequest<?> request, #Body RegisterFormData registerFormData) {
//validate registerformdata object
Map<String, Object> map = new HashMap<>()
Set<ConstraintViolation<RegisterFormData>> violations = validator.validate(registerFormData)
if (violations.size() > 0) {
map.put('registerFormData', registerFormData)
map.put('errors', violationMessageSource.violationsMessages(violations))
HttpResponse.redirect(URI.create('/register')).body(map)
} else {
RegisterRequest registerRequest = new RegisterRequest(registerFormData.properties)
registerRequest.returnSecureToken = true
try {
def registerResponse = firebaseClient.register(registerRequest, this.firebaseApiKey).blockingSingle()
SendEmailVerificationRequest sendEmailVerificationRequest = new SendEmailVerificationRequest()
sendEmailVerificationRequest.requestType = 'VERIFY_EMAIL'
sendEmailVerificationRequest.idToken = registerResponse.idToken
firebaseClient.sendEmailVerification(sendEmailVerificationRequest, this.firebaseApiKey)
HttpResponse.redirect(URI.create('/register-success'))
} catch (HttpClientResponseException ex) {
map.put('errors', [ex.message])
HttpResponse.redirect(URI.create('/register')).body(map)
}
}
}
where I have injected a validator bean in Micronaut like so
#Factory
class ValidatorConfig {
Validator validator
#PostConstruct
void initialize(){
ValidatorFactory factory = Validation.buildDefaultValidatorFactory()
validator = factory.getValidator()
}
#Bean
Validator getValidator(){
return validator
}
}
and my message source like so
#Singleton
public class ViolationMessageSource {
public List<String> violationsMessages(Set<ConstraintViolation<?>> violations) {
return violations.stream()
.map(ViolationMessageSource::violationMessage)
.collect(Collectors.toList());
}
private static String violationMessage(ConstraintViolation violation) {
StringBuilder sb = new StringBuilder();
Path.Node lastNode = lastNode(violation.getPropertyPath());
if (lastNode != null) {
sb.append(lastNode.getName());
sb.append(" ");
}
sb.append(violation.getMessage());
return sb.toString();
}
private static Path.Node lastNode(Path path) {
Path.Node lastNode = null;
for (final Path.Node node : path) {
lastNode = node;
}
return lastNode;
}
}
The answers are based on the fundamentals on javax validation https://www.baeldung.com/javax-validation and error handling in micronaut https://guides.micronaut.io/micronaut-error-handling/guide/index.html
Trying to fetch the response using spring web client, but the result response is getting truncated as the response size is more than that of string class. Is there any other way to get the response without being truncated?
LinkedMultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<String, Object>();
//String response = "";
try{
File tempFile = File.createTempFile("ccda", "File");
FileOutputStream out = new FileOutputStream(tempFile);
IOUtils.copy(ccdaFile.getInputStream(), out);
requestMap.add("ccdaFile", new FileSystemResource(tempFile));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity =
new HttpEntity<LinkedMultiValueMap<String, Object>>(requestMap, headers);
RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter formConverter = new FormHttpMessageConverter();
formConverter.setCharset(Charset.forName("UTF8"));
restTemplate.getMessageConverters().add(formConverter);
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
String response = restTemplate.postForObject("localhost:8080",
requestEntity, String.class);
tempFile.delete();
}catch(Exception exc)
{
exc.printStackTrace();
}
You may use an InputStream
I think you may do in this way:
InputStream is = rt.execute("localhost:8080", HttpMethod.POST, requestCallback, responseExtractor);
Where requestCallback is an implementation of org.springframework.web.client.RequestCallback like this one
public class MyRequestCallback implements RequestCallback
{
#Override
public void doWithRequest(ClientHttpRequest request) throws IOException
{
request.getHeaders().add(HttpHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON_VALUE);
request.getHeaders().add(HttpHeaders.ACCEPT, MimeTypeUtils.APPLICATION_JSON_VALUE);
}
}
While responseExtractor may by an instance of this class
public class MyResponseExtractor implements ResponseExtractor<InputStream>
{
#Override
public Boolean extractData(ClientHttpResponse response) throws IOException
{
HttpStatus status = response.getStatusCode();
switch (status)
{
case OK:
return response.getBody();
default:
return null;
}
}
}
Once obtained the InputStream you can manage it
Hope it is usefull
I am using HttpClient and defaultHttpClient Methods in getInternetData function on android studi. but these methods are no longer part of the SDK 23. how can i overcome this problem.i have used dependencies in build.gradle too , but still error remains here. Kindly tell me are there any other methods to call.?
public class GetMethodEx {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://api.twitter.com/1/statuses/public_timeline.json");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
}finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
I'm trying to post to a server via Asynchronous Task and while converting Hashmap to String, this error occurred. What does that Error mean. Why does it occour ? How do I resolve this ?
here is my code:
public class NetworkAccess extends AsyncTask<HashMap<String,String>,Void,String> {
private URL url;
private HttpURLConnection con;
private OutputStream os;
#Override
protected String doInBackground(HashMap<String, String>... vals) {
String response = "";
try {
url = new URL("http://192.168.0.3/chow/user-login.php");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setConnectTimeout(1000);
OutputStream os = con.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String pd = getPostDataString(vals); //Error
writer.write(pd);
writer.flush();
writer.close();
BufferedInputStream bis = new BufferedInputStream(con.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(bis));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
response = total.toString();
}
catch (Exception e){
e.printStackTrace();
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
The error which you got shows that you're directly trying to create a array of HashMap, rather you can create just Array of String, iterate the Collection and insert the HashMap objects into it.
Inside the getPostDataString(), change the code to
StringBuilder[] sb = new StringBuilder[100];
and check if it works.