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 did the Apple IIe make a hideous noise if you inserted the disk upside down?
Understanding the as-if rule, "the program was executed as written"
Why isn't UDP with reliability (implemented at Application layer) a substitute of TCP?
Rear derailleur got caught in the spokes, what could be a root cause
ATMEGA328P-U vs ATMEGA328-PU
How does the 'five minute adventuring day' affect class balance?
German idiomatic equivalents of 能骗就骗 (if you can cheat, then cheat)
Simplify the code
Do electrons really perform instantaneous quantum leaps?
Tricolour nonogram
What does 'in attendance' mean on an England death certificate?
Any Tips On Writing Extended Recollection In A Novel
Robots in a spaceship
How far can gerrymandering go?
tikz: draw multicolor curve with smooth gradient
Why didn't Avengers simply jump 5 years back?
What happens if a caster is surprised while casting a spell with a long casting time?
Installed software from source, how to say yum not to install it from package?
How can this fractal shape perfectly cover a certain platonic solid?
How is it possible for tall trees to pull water to heights more than 10m?
Having to constantly redo everything because I don't know how to do it
What would you need merely the term "collection" for pitches, but not "scale"?
Why doesn't SpaceX land boosters in Africa?
English idiomatic equivalents of 能骗就骗 (if you can cheat, then cheat)
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
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
.
- RequestMappping
path = /admin/count & RequestParam = url (Here
/user/101) - Then create the
dynamic Request based on RequestParam
http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
Get and Return the Response
of dynamic Request(JSON Object)
and get the value ofCOUNT
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
add a comment |
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
.
- RequestMappping
path = /admin/count & RequestParam = url (Here
/user/101) - Then create the
dynamic Request based on RequestParam
http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
Get and Return the Response
of dynamic Request(JSON Object)
and get the value ofCOUNT
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
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
add a comment |
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
.
- RequestMappping
path = /admin/count & RequestParam = url (Here
/user/101) - Then create the
dynamic Request based on RequestParam
http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
Get and Return the Response
of dynamic Request(JSON Object)
and get the value ofCOUNT
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
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
.
- RequestMappping
path = /admin/count & RequestParam = url (Here
/user/101) - Then create the
dynamic Request based on RequestParam
http://localhost:8080/actuator/metrics/http.server.requests?tag=uri:/user/101
Get and Return the Response
of dynamic Request(JSON Object)
and get the value ofCOUNT
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
java spring spring-boot spring-boot-actuator
edited Jun 4 at 15:47
Patel Romil
asked Mar 25 at 7:03
Patel RomilPatel Romil
1,2461 gold badge7 silver badges19 bronze badges
1,2461 gold badge7 silver badges19 bronze badges
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
add a comment |
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
add a comment |
2 Answers
2
active
oldest
votes
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.
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
|
show 3 more comments
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;
I had similar use case and your post was very helpful.
– Jon Abraham
Jun 4 at 14:24
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
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
|
show 3 more comments
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.
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
|
show 3 more comments
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.
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.
edited Mar 26 at 4:42
answered Mar 25 at 16:35
MyTwoCentsMyTwoCents
3,6952 gold badges11 silver badges31 bronze badges
3,6952 gold badges11 silver badges31 bronze badges
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
|
show 3 more comments
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
|
show 3 more comments
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;
I had similar use case and your post was very helpful.
– Jon Abraham
Jun 4 at 14:24
add a comment |
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;
I had similar use case and your post was very helpful.
– Jon Abraham
Jun 4 at 14:24
add a comment |
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;
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;
answered Mar 26 at 10:18
Patel RomilPatel Romil
1,2461 gold badge7 silver badges19 bronze badges
1,2461 gold badge7 silver badges19 bronze badges
I had similar use case and your post was very helpful.
– Jon Abraham
Jun 4 at 14:24
add a comment |
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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