count views using actuator for each endpointsJSONException: Value of type java.lang.String cannot be converted to JSONObjectSpring Boot Actuator /env endpoint returning data as XML - why?spring boot actuator endpoint mapping root classSpring Boot Actuator - override management.context-path for one actuator endpointSpring Boot doesn't render views properlySpringBoot 2.0.2.RELEASE with amqp misses metrics actuator endpointExposing endpoint URL in testsSpring actuator shutdown-endpoint cannot stop java processHow can you configure the base url for Spring Boot Actuator so it is returned by the base endpoint?Spring Boot application endpoint returns 403Spring-boot Application Throwing Error on Actuator Port

Why don't countries like Japan just print more money?

Justifying Affordable Bespoke Spaceships

Why does independence imply zero correlation?

How can I ping multiple IP addresses at the same time?

What is the most suitable position for a bishop here?

macOS: How to take a picture from camera after 1 minute

Why don't we have a weaning party like Avraham did?

Why do you need to heat the pan before heating the olive oil?

What was the flower of Empress Taytu?

Warnings using NDSolve on wave PDE. "Using maximum number of grid points" , "Warning: scaled local spatial error estimate"

Extending prime numbers digit by digit while retaining primality

Am I legally required to provide a (GPL licensed) source code even after a project is abandoned?

What does it cost to buy a tavern?

What happened to Hopper's girlfriend in season one?

Second 100 amp breaker inside existing 200 amp residential panel for new detached garage

Has a life raft ever been successfully deployed on a modern commercial flight?

Why isn't my calculation that we should be able to see the sun well beyond the observable universe valid?

What mathematical theory is required for high frequency trading?

How can a warlock learn from a spellbook?

How do internally carried IR missiles acquire a lock?

How does join() produce different results depending on the arguments?

What does this Swiss black on yellow rectangular traffic sign with a symbol looking like a dart mean?

Why does Linux list NVMe drives as /dev/nvme0 instead of /dev/sda?

Should I include an appendix for inessential, yet related worldbuilding to my story?



count views using actuator for each endpoints


JSONException: Value of type java.lang.String cannot be converted to JSONObjectSpring Boot Actuator /env endpoint returning data as XML - why?spring boot actuator endpoint mapping root classSpring Boot Actuator - override management.context-path for one actuator endpointSpring Boot doesn't render views properlySpringBoot 2.0.2.RELEASE with amqp misses metrics actuator endpointExposing endpoint URL in testsSpring actuator shutdown-endpoint cannot stop java processHow can you configure the base url for Spring Boot Actuator so it is returned by the base endpoint?Spring Boot application endpoint returns 403Spring-boot Application Throwing Error on Actuator Port






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have a requirement to count the views on each endpoint. The idea is to create one common Request Count Mapping for all endpoints which should return the view count based on a dynamically entred endpoint.



Let's say someone wants to check the view counts on http://localhost:8080/user/101.



  1. RequestMappping path = /admin/count & RequestParam = url (Here
    /user/101)


  2. Then create the dynamic Request based on RequestParam
    http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101


  3. Get and Return the Response of dynamic Request (JSON Object) and get the value of COUNT


I stuck on how to send a dynamic request to
http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
and return the response of it and get the count value





@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public JSONObject count(@RequestParam(name="url") final String url)//@PathVariable(name="url") final String url

String finalURL = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + url + "";
return sendRequestToURL(finalURL);




@RequestMapping(path="/finalURL",method=RequestMethod.GET)
public JSONObject sendRequestToURL(@PathVariable("finalURL") String url)

//How to return the response Here




This is what I get when Directly fire the URL




GET: http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101




 
"name": "http.server.requests",
"description": null,
"baseUnit": "seconds",
"measurements": [

"statistic": "COUNT",
"value": 1
,

"statistic": "TOTAL_TIME",
"value": 0.3229436
,

"statistic": "MAX",
"value": 0.3229436

],
"availableTags": [

"tag": "exception",
"values": [
"None"
]
,

"tag": "method",
"values": [
"GET"
]
,

"tag": "outcome",
"values": [
"SUCCESS"
]
,

"tag": "status",
"values": [
"200"
]

]




Environment:



 `spring boot 2.1.2.RELEASE`
<java.version>1.8</java.version>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>









share|improve this question
























  • So what's issue. This URL http.server.requests?tag=uri:/user/101 gives you detail. Parse it and store.

    – MyTwoCents
    Mar 25 at 10:19











  • @MyTwoCents Thanks for the response, Please Refer the updated Question

    – Patel Romil
    Mar 25 at 15:08


















1















I have a requirement to count the views on each endpoint. The idea is to create one common Request Count Mapping for all endpoints which should return the view count based on a dynamically entred endpoint.



Let's say someone wants to check the view counts on http://localhost:8080/user/101.



  1. RequestMappping path = /admin/count & RequestParam = url (Here
    /user/101)


  2. Then create the dynamic Request based on RequestParam
    http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101


  3. Get and Return the Response of dynamic Request (JSON Object) and get the value of COUNT


I stuck on how to send a dynamic request to
http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
and return the response of it and get the count value





@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public JSONObject count(@RequestParam(name="url") final String url)//@PathVariable(name="url") final String url

String finalURL = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + url + "";
return sendRequestToURL(finalURL);




@RequestMapping(path="/finalURL",method=RequestMethod.GET)
public JSONObject sendRequestToURL(@PathVariable("finalURL") String url)

//How to return the response Here




This is what I get when Directly fire the URL




GET: http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101




 
"name": "http.server.requests",
"description": null,
"baseUnit": "seconds",
"measurements": [

"statistic": "COUNT",
"value": 1
,

"statistic": "TOTAL_TIME",
"value": 0.3229436
,

"statistic": "MAX",
"value": 0.3229436

],
"availableTags": [

"tag": "exception",
"values": [
"None"
]
,

"tag": "method",
"values": [
"GET"
]
,

"tag": "outcome",
"values": [
"SUCCESS"
]
,

"tag": "status",
"values": [
"200"
]

]




Environment:



 `spring boot 2.1.2.RELEASE`
<java.version>1.8</java.version>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>









share|improve this question
























  • So what's issue. This URL http.server.requests?tag=uri:/user/101 gives you detail. Parse it and store.

    – MyTwoCents
    Mar 25 at 10:19











  • @MyTwoCents Thanks for the response, Please Refer the updated Question

    – Patel Romil
    Mar 25 at 15:08














1












1








1








I have a requirement to count the views on each endpoint. The idea is to create one common Request Count Mapping for all endpoints which should return the view count based on a dynamically entred endpoint.



Let's say someone wants to check the view counts on http://localhost:8080/user/101.



  1. RequestMappping path = /admin/count & RequestParam = url (Here
    /user/101)


  2. Then create the dynamic Request based on RequestParam
    http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101


  3. Get and Return the Response of dynamic Request (JSON Object) and get the value of COUNT


I stuck on how to send a dynamic request to
http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
and return the response of it and get the count value





@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public JSONObject count(@RequestParam(name="url") final String url)//@PathVariable(name="url") final String url

String finalURL = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + url + "";
return sendRequestToURL(finalURL);




@RequestMapping(path="/finalURL",method=RequestMethod.GET)
public JSONObject sendRequestToURL(@PathVariable("finalURL") String url)

//How to return the response Here




This is what I get when Directly fire the URL




GET: http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101




 
"name": "http.server.requests",
"description": null,
"baseUnit": "seconds",
"measurements": [

"statistic": "COUNT",
"value": 1
,

"statistic": "TOTAL_TIME",
"value": 0.3229436
,

"statistic": "MAX",
"value": 0.3229436

],
"availableTags": [

"tag": "exception",
"values": [
"None"
]
,

"tag": "method",
"values": [
"GET"
]
,

"tag": "outcome",
"values": [
"SUCCESS"
]
,

"tag": "status",
"values": [
"200"
]

]




Environment:



 `spring boot 2.1.2.RELEASE`
<java.version>1.8</java.version>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>









share|improve this question
















I have a requirement to count the views on each endpoint. The idea is to create one common Request Count Mapping for all endpoints which should return the view count based on a dynamically entred endpoint.



Let's say someone wants to check the view counts on http://localhost:8080/user/101.



  1. RequestMappping path = /admin/count & RequestParam = url (Here
    /user/101)


  2. Then create the dynamic Request based on RequestParam
    http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101


  3. Get and Return the Response of dynamic Request (JSON Object) and get the value of COUNT


I stuck on how to send a dynamic request to
http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
and return the response of it and get the count value





@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public JSONObject count(@RequestParam(name="url") final String url)//@PathVariable(name="url") final String url

String finalURL = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + url + "";
return sendRequestToURL(finalURL);




@RequestMapping(path="/finalURL",method=RequestMethod.GET)
public JSONObject sendRequestToURL(@PathVariable("finalURL") String url)

//How to return the response Here




This is what I get when Directly fire the URL




GET: http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101




 
"name": "http.server.requests",
"description": null,
"baseUnit": "seconds",
"measurements": [

"statistic": "COUNT",
"value": 1
,

"statistic": "TOTAL_TIME",
"value": 0.3229436
,

"statistic": "MAX",
"value": 0.3229436

],
"availableTags": [

"tag": "exception",
"values": [
"None"
]
,

"tag": "method",
"values": [
"GET"
]
,

"tag": "outcome",
"values": [
"SUCCESS"
]
,

"tag": "status",
"values": [
"200"
]

]




Environment:



 `spring boot 2.1.2.RELEASE`
<java.version>1.8</java.version>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>






java spring spring-boot spring-boot-actuator






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 4 at 15:47







Patel Romil

















asked Mar 25 at 7:03









Patel RomilPatel Romil

1,2241719




1,2241719












  • So what's issue. This URL http.server.requests?tag=uri:/user/101 gives you detail. Parse it and store.

    – MyTwoCents
    Mar 25 at 10:19











  • @MyTwoCents Thanks for the response, Please Refer the updated Question

    – Patel Romil
    Mar 25 at 15:08


















  • So what's issue. This URL http.server.requests?tag=uri:/user/101 gives you detail. Parse it and store.

    – MyTwoCents
    Mar 25 at 10:19











  • @MyTwoCents Thanks for the response, Please Refer the updated Question

    – Patel Romil
    Mar 25 at 15:08

















So what's issue. This URL http.server.requests?tag=uri:/user/101 gives you detail. Parse it and store.

– MyTwoCents
Mar 25 at 10:19





So what's issue. This URL http.server.requests?tag=uri:/user/101 gives you detail. Parse it and store.

– MyTwoCents
Mar 25 at 10:19













@MyTwoCents Thanks for the response, Please Refer the updated Question

– Patel Romil
Mar 25 at 15:08






@MyTwoCents Thanks for the response, Please Refer the updated Question

– Patel Romil
Mar 25 at 15:08













2 Answers
2






active

oldest

votes


















1














So you want to encapsulate actuator/metrics with /admin/count



There are many ways and library for calling Rest API in Java



I will add the simplest one



Something like this



public JSONObject sendRequestToURL(@PathVariable("finalURL") String urlToRead)

StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();
return new JSONObject(result.toString()); // org.json



Edit 1:



You are almost there. Just need to parse String to JSONObject. Try this maybe



String strJson = result.toString().replace("\"","'");
JSONObject jo = new JSONObject(strJson.substring(1,json.length()-1));
return jo;


Edit 2:



I guess you have Spring Security in place.



And when you are calling an API internally, Spring is treating as an external call which requires Authentication.



As a workaround, you can exclude /actuator API from security context.



@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable().authorizeRequests()
.antMatchers("/actuator*").permitAll()

...



or in XML



<security:http auto-config="true" use-expressions="true" >
<security:intercept-url pattern="/actuator*" access="permitAll"/>

...
</security:http>


And hopefully Spring security will ignore this URL and you will not get Login Form.






share|improve this answer

























  • Thanks @MyTwoCents I have tried this but it gives Value <html><head>< of type java.lang.String cannot be converted to JSONObject

    – Patel Romil
    Mar 25 at 16:56











  • can you check if urlToRead is same as localhost:8080/actuator/metrics/http.server.requests?tag=uri:/…

    – MyTwoCents
    Mar 25 at 16:58











  • yes urlToRead is correct and gives the output

    – Patel Romil
    Mar 25 at 17:04











  • Added more detail

    – MyTwoCents
    Mar 25 at 17:12











  • Thanks for your efforts but still the same error (in Line 2)

    – Patel Romil
    Mar 25 at 17:16



















1














The idea is you will get the endPoint from user to display to show the view counts which will be done using @RequestParam. Based on the request endPoint create the URLtoMap according to your requirements



(i.e methods, status, outcome, exception etc, e.g. http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101&tag=method:GET).




@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public int count(@RequestParam(name="endPoint") final String endPoint) throws IOException, JSONException

final String URLtoMap = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + endPoint + "";
return sendRequestToURL(URLtoMap);




Now Based on the URLtoMap send Request using HttpURLConnection and get the output using BufferedReader. As I am using Spring Security I was redirected to Login Page. To solve the problem I have added antMatchers in SecurityConfig file as below. If you facing JSONException: Value of type java.lang.String cannot be converted to JSONObject then refer this



public int sendRequestToURL(@PathVariable("URLtoMap") String URLtoMap) throws IOException, JSONException

int count = 0;
StringBuilder result = new StringBuilder();
URL url = new URL(URLtoMap);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();

try
JSONObject jsonObject =new JSONObject(result.toString().replace(""", ""));
JSONObject jsonCountObject = new JSONObject(jsonObject.getJSONArray("measurements").get(0).toString());
count =(int) jsonCountObject.get("value");

catch (JSONException e)
e.printStackTrace();


return count;





SecurityConfig




@Override
protected void configure(HttpSecurity http) throws Exception

http
.csrf().disable()
.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers(HttpMethod.GET,"/actuator/**").permitAll()
.antMatchers(HttpMethod.POST,"/actuator/**").permitAll()




pom.xml




<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>



Import the Correct Packages




import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;





share|improve this answer























  • I had similar use case and your post was very helpful.

    – Jon Abraham
    Jun 4 at 14:24











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55332664%2fcount-views-using-actuator-for-each-endpoints%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














So you want to encapsulate actuator/metrics with /admin/count



There are many ways and library for calling Rest API in Java



I will add the simplest one



Something like this



public JSONObject sendRequestToURL(@PathVariable("finalURL") String urlToRead)

StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();
return new JSONObject(result.toString()); // org.json



Edit 1:



You are almost there. Just need to parse String to JSONObject. Try this maybe



String strJson = result.toString().replace("\"","'");
JSONObject jo = new JSONObject(strJson.substring(1,json.length()-1));
return jo;


Edit 2:



I guess you have Spring Security in place.



And when you are calling an API internally, Spring is treating as an external call which requires Authentication.



As a workaround, you can exclude /actuator API from security context.



@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable().authorizeRequests()
.antMatchers("/actuator*").permitAll()

...



or in XML



<security:http auto-config="true" use-expressions="true" >
<security:intercept-url pattern="/actuator*" access="permitAll"/>

...
</security:http>


And hopefully Spring security will ignore this URL and you will not get Login Form.






share|improve this answer

























  • Thanks @MyTwoCents I have tried this but it gives Value <html><head>< of type java.lang.String cannot be converted to JSONObject

    – Patel Romil
    Mar 25 at 16:56











  • can you check if urlToRead is same as localhost:8080/actuator/metrics/http.server.requests?tag=uri:/…

    – MyTwoCents
    Mar 25 at 16:58











  • yes urlToRead is correct and gives the output

    – Patel Romil
    Mar 25 at 17:04











  • Added more detail

    – MyTwoCents
    Mar 25 at 17:12











  • Thanks for your efforts but still the same error (in Line 2)

    – Patel Romil
    Mar 25 at 17:16
















1














So you want to encapsulate actuator/metrics with /admin/count



There are many ways and library for calling Rest API in Java



I will add the simplest one



Something like this



public JSONObject sendRequestToURL(@PathVariable("finalURL") String urlToRead)

StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();
return new JSONObject(result.toString()); // org.json



Edit 1:



You are almost there. Just need to parse String to JSONObject. Try this maybe



String strJson = result.toString().replace("\"","'");
JSONObject jo = new JSONObject(strJson.substring(1,json.length()-1));
return jo;


Edit 2:



I guess you have Spring Security in place.



And when you are calling an API internally, Spring is treating as an external call which requires Authentication.



As a workaround, you can exclude /actuator API from security context.



@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable().authorizeRequests()
.antMatchers("/actuator*").permitAll()

...



or in XML



<security:http auto-config="true" use-expressions="true" >
<security:intercept-url pattern="/actuator*" access="permitAll"/>

...
</security:http>


And hopefully Spring security will ignore this URL and you will not get Login Form.






share|improve this answer

























  • Thanks @MyTwoCents I have tried this but it gives Value <html><head>< of type java.lang.String cannot be converted to JSONObject

    – Patel Romil
    Mar 25 at 16:56











  • can you check if urlToRead is same as localhost:8080/actuator/metrics/http.server.requests?tag=uri:/…

    – MyTwoCents
    Mar 25 at 16:58











  • yes urlToRead is correct and gives the output

    – Patel Romil
    Mar 25 at 17:04











  • Added more detail

    – MyTwoCents
    Mar 25 at 17:12











  • Thanks for your efforts but still the same error (in Line 2)

    – Patel Romil
    Mar 25 at 17:16














1












1








1







So you want to encapsulate actuator/metrics with /admin/count



There are many ways and library for calling Rest API in Java



I will add the simplest one



Something like this



public JSONObject sendRequestToURL(@PathVariable("finalURL") String urlToRead)

StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();
return new JSONObject(result.toString()); // org.json



Edit 1:



You are almost there. Just need to parse String to JSONObject. Try this maybe



String strJson = result.toString().replace("\"","'");
JSONObject jo = new JSONObject(strJson.substring(1,json.length()-1));
return jo;


Edit 2:



I guess you have Spring Security in place.



And when you are calling an API internally, Spring is treating as an external call which requires Authentication.



As a workaround, you can exclude /actuator API from security context.



@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable().authorizeRequests()
.antMatchers("/actuator*").permitAll()

...



or in XML



<security:http auto-config="true" use-expressions="true" >
<security:intercept-url pattern="/actuator*" access="permitAll"/>

...
</security:http>


And hopefully Spring security will ignore this URL and you will not get Login Form.






share|improve this answer















So you want to encapsulate actuator/metrics with /admin/count



There are many ways and library for calling Rest API in Java



I will add the simplest one



Something like this



public JSONObject sendRequestToURL(@PathVariable("finalURL") String urlToRead)

StringBuilder result = new StringBuilder();
URL url = new URL(urlToRead);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();
return new JSONObject(result.toString()); // org.json



Edit 1:



You are almost there. Just need to parse String to JSONObject. Try this maybe



String strJson = result.toString().replace("\"","'");
JSONObject jo = new JSONObject(strJson.substring(1,json.length()-1));
return jo;


Edit 2:



I guess you have Spring Security in place.



And when you are calling an API internally, Spring is treating as an external call which requires Authentication.



As a workaround, you can exclude /actuator API from security context.



@Override
protected void configure(HttpSecurity http) throws Exception
http.csrf().disable().authorizeRequests()
.antMatchers("/actuator*").permitAll()

...



or in XML



<security:http auto-config="true" use-expressions="true" >
<security:intercept-url pattern="/actuator*" access="permitAll"/>

...
</security:http>


And hopefully Spring security will ignore this URL and you will not get Login Form.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 26 at 4:42

























answered Mar 25 at 16:35









MyTwoCentsMyTwoCents

3,65021131




3,65021131












  • Thanks @MyTwoCents I have tried this but it gives Value <html><head>< of type java.lang.String cannot be converted to JSONObject

    – Patel Romil
    Mar 25 at 16:56











  • can you check if urlToRead is same as localhost:8080/actuator/metrics/http.server.requests?tag=uri:/…

    – MyTwoCents
    Mar 25 at 16:58











  • yes urlToRead is correct and gives the output

    – Patel Romil
    Mar 25 at 17:04











  • Added more detail

    – MyTwoCents
    Mar 25 at 17:12











  • Thanks for your efforts but still the same error (in Line 2)

    – Patel Romil
    Mar 25 at 17:16


















  • Thanks @MyTwoCents I have tried this but it gives Value <html><head>< of type java.lang.String cannot be converted to JSONObject

    – Patel Romil
    Mar 25 at 16:56











  • can you check if urlToRead is same as localhost:8080/actuator/metrics/http.server.requests?tag=uri:/…

    – MyTwoCents
    Mar 25 at 16:58











  • yes urlToRead is correct and gives the output

    – Patel Romil
    Mar 25 at 17:04











  • Added more detail

    – MyTwoCents
    Mar 25 at 17:12











  • Thanks for your efforts but still the same error (in Line 2)

    – Patel Romil
    Mar 25 at 17:16

















Thanks @MyTwoCents I have tried this but it gives Value <html><head>< of type java.lang.String cannot be converted to JSONObject

– Patel Romil
Mar 25 at 16:56





Thanks @MyTwoCents I have tried this but it gives Value <html><head>< of type java.lang.String cannot be converted to JSONObject

– Patel Romil
Mar 25 at 16:56













can you check if urlToRead is same as localhost:8080/actuator/metrics/http.server.requests?tag=uri:/…

– MyTwoCents
Mar 25 at 16:58





can you check if urlToRead is same as localhost:8080/actuator/metrics/http.server.requests?tag=uri:/…

– MyTwoCents
Mar 25 at 16:58













yes urlToRead is correct and gives the output

– Patel Romil
Mar 25 at 17:04





yes urlToRead is correct and gives the output

– Patel Romil
Mar 25 at 17:04













Added more detail

– MyTwoCents
Mar 25 at 17:12





Added more detail

– MyTwoCents
Mar 25 at 17:12













Thanks for your efforts but still the same error (in Line 2)

– Patel Romil
Mar 25 at 17:16






Thanks for your efforts but still the same error (in Line 2)

– Patel Romil
Mar 25 at 17:16














1














The idea is you will get the endPoint from user to display to show the view counts which will be done using @RequestParam. Based on the request endPoint create the URLtoMap according to your requirements



(i.e methods, status, outcome, exception etc, e.g. http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101&tag=method:GET).




@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public int count(@RequestParam(name="endPoint") final String endPoint) throws IOException, JSONException

final String URLtoMap = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + endPoint + "";
return sendRequestToURL(URLtoMap);




Now Based on the URLtoMap send Request using HttpURLConnection and get the output using BufferedReader. As I am using Spring Security I was redirected to Login Page. To solve the problem I have added antMatchers in SecurityConfig file as below. If you facing JSONException: Value of type java.lang.String cannot be converted to JSONObject then refer this



public int sendRequestToURL(@PathVariable("URLtoMap") String URLtoMap) throws IOException, JSONException

int count = 0;
StringBuilder result = new StringBuilder();
URL url = new URL(URLtoMap);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();

try
JSONObject jsonObject =new JSONObject(result.toString().replace(""", ""));
JSONObject jsonCountObject = new JSONObject(jsonObject.getJSONArray("measurements").get(0).toString());
count =(int) jsonCountObject.get("value");

catch (JSONException e)
e.printStackTrace();


return count;





SecurityConfig




@Override
protected void configure(HttpSecurity http) throws Exception

http
.csrf().disable()
.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers(HttpMethod.GET,"/actuator/**").permitAll()
.antMatchers(HttpMethod.POST,"/actuator/**").permitAll()




pom.xml




<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>



Import the Correct Packages




import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;





share|improve this answer























  • I had similar use case and your post was very helpful.

    – Jon Abraham
    Jun 4 at 14:24















1














The idea is you will get the endPoint from user to display to show the view counts which will be done using @RequestParam. Based on the request endPoint create the URLtoMap according to your requirements



(i.e methods, status, outcome, exception etc, e.g. http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101&tag=method:GET).




@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public int count(@RequestParam(name="endPoint") final String endPoint) throws IOException, JSONException

final String URLtoMap = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + endPoint + "";
return sendRequestToURL(URLtoMap);




Now Based on the URLtoMap send Request using HttpURLConnection and get the output using BufferedReader. As I am using Spring Security I was redirected to Login Page. To solve the problem I have added antMatchers in SecurityConfig file as below. If you facing JSONException: Value of type java.lang.String cannot be converted to JSONObject then refer this



public int sendRequestToURL(@PathVariable("URLtoMap") String URLtoMap) throws IOException, JSONException

int count = 0;
StringBuilder result = new StringBuilder();
URL url = new URL(URLtoMap);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();

try
JSONObject jsonObject =new JSONObject(result.toString().replace(""", ""));
JSONObject jsonCountObject = new JSONObject(jsonObject.getJSONArray("measurements").get(0).toString());
count =(int) jsonCountObject.get("value");

catch (JSONException e)
e.printStackTrace();


return count;





SecurityConfig




@Override
protected void configure(HttpSecurity http) throws Exception

http
.csrf().disable()
.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers(HttpMethod.GET,"/actuator/**").permitAll()
.antMatchers(HttpMethod.POST,"/actuator/**").permitAll()




pom.xml




<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>



Import the Correct Packages




import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;





share|improve this answer























  • I had similar use case and your post was very helpful.

    – Jon Abraham
    Jun 4 at 14:24













1












1








1







The idea is you will get the endPoint from user to display to show the view counts which will be done using @RequestParam. Based on the request endPoint create the URLtoMap according to your requirements



(i.e methods, status, outcome, exception etc, e.g. http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101&tag=method:GET).




@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public int count(@RequestParam(name="endPoint") final String endPoint) throws IOException, JSONException

final String URLtoMap = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + endPoint + "";
return sendRequestToURL(URLtoMap);




Now Based on the URLtoMap send Request using HttpURLConnection and get the output using BufferedReader. As I am using Spring Security I was redirected to Login Page. To solve the problem I have added antMatchers in SecurityConfig file as below. If you facing JSONException: Value of type java.lang.String cannot be converted to JSONObject then refer this



public int sendRequestToURL(@PathVariable("URLtoMap") String URLtoMap) throws IOException, JSONException

int count = 0;
StringBuilder result = new StringBuilder();
URL url = new URL(URLtoMap);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();

try
JSONObject jsonObject =new JSONObject(result.toString().replace(""", ""));
JSONObject jsonCountObject = new JSONObject(jsonObject.getJSONArray("measurements").get(0).toString());
count =(int) jsonCountObject.get("value");

catch (JSONException e)
e.printStackTrace();


return count;





SecurityConfig




@Override
protected void configure(HttpSecurity http) throws Exception

http
.csrf().disable()
.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers(HttpMethod.GET,"/actuator/**").permitAll()
.antMatchers(HttpMethod.POST,"/actuator/**").permitAll()




pom.xml




<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>



Import the Correct Packages




import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;





share|improve this answer













The idea is you will get the endPoint from user to display to show the view counts which will be done using @RequestParam. Based on the request endPoint create the URLtoMap according to your requirements



(i.e methods, status, outcome, exception etc, e.g. http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101&tag=method:GET).




@RequestMapping(path="/admin/count",method=RequestMethod.POST)
public int count(@RequestParam(name="endPoint") final String endPoint) throws IOException, JSONException

final String URLtoMap = "http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:" + endPoint + "";
return sendRequestToURL(URLtoMap);




Now Based on the URLtoMap send Request using HttpURLConnection and get the output using BufferedReader. As I am using Spring Security I was redirected to Login Page. To solve the problem I have added antMatchers in SecurityConfig file as below. If you facing JSONException: Value of type java.lang.String cannot be converted to JSONObject then refer this



public int sendRequestToURL(@PathVariable("URLtoMap") String URLtoMap) throws IOException, JSONException

int count = 0;
StringBuilder result = new StringBuilder();
URL url = new URL(URLtoMap);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null)
result.append(line);

rd.close();

try
JSONObject jsonObject =new JSONObject(result.toString().replace(""", ""));
JSONObject jsonCountObject = new JSONObject(jsonObject.getJSONArray("measurements").get(0).toString());
count =(int) jsonCountObject.get("value");

catch (JSONException e)
e.printStackTrace();


return count;





SecurityConfig




@Override
protected void configure(HttpSecurity http) throws Exception

http
.csrf().disable()
.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers(HttpMethod.GET,"/actuator/**").permitAll()
.antMatchers(HttpMethod.POST,"/actuator/**").permitAll()




pom.xml




<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>



Import the Correct Packages




import org.json.JSONException;
import org.json.JSONObject;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 26 at 10:18









Patel RomilPatel Romil

1,2241719




1,2241719












  • I had similar use case and your post was very helpful.

    – Jon Abraham
    Jun 4 at 14:24

















  • I had similar use case and your post was very helpful.

    – Jon Abraham
    Jun 4 at 14:24
















I had similar use case and your post was very helpful.

– Jon Abraham
Jun 4 at 14:24





I had similar use case and your post was very helpful.

– Jon Abraham
Jun 4 at 14:24

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55332664%2fcount-views-using-actuator-for-each-endpoints%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해