Implement url without end slash - java

I use this Java client to make POST requests:
Implementation
public Mono<PaymentResponse> executeAndReceive(String transaction) {
Mono<String> transactionMono = Mono.just(transaction);
return client.post().uri(gatewayUrl + "{token}", token)
.retrieve()
.bodyToMono(Response.class);
}
I use this code to call the client:
String GATEWAY_PROCESSING_URL = http://www.some_host:8080/rest_api/v1/
String token = 342552334
RestClient client = RestClientBuilder.builder()
.gatewayUrl(GATEWAY_PROCESSING_URL)
.token(token)
.usernamePassword(user_name, password)
.build();
But sometimes I forgot to set / at the end of the URL.
Is there some way to detect this and set it automatically if it's missing?

If all you need is a safety check whether the url ends with a '/' just use the example below.
String url = ... some url ...
if (url.endsWith("/") == false) {
url += "/";
}

Related

How to the get wildcard path variable in the controller

I have a controller:
#PostMapping("/name/**")
public Mono<String> doSomething(HttpEntity<byte[]> requestEntity,
ServerHttpRequest serverHttpRequest) {
String restOfTheUrl = //the ** part is what i need here
return webClient.forwardRequest(requestEntity, serviceUrl + "/" + restOfTheUrl);
}
How do I obtain the URL string (including all query params) thats after the /name/ ?? basically I need the ** part. Of course I can remove the /name/ from serverHttpRequest.getPath(..) but is there a better way?
#PostMapping("/name/{*path}")
public Mono<String> doSomething(#PathVariable("path") String path) {...

How to remove last slash "/" from base url in Retrofit 2

When I Type Base Url="https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg/" with last slash(/) then give me message like this:
Response{protocol=http/1.1, code=500, message=Internal Server Error, url=https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg/?user=XX&pass=r#12&msisdn=0160000000&trxid=6BM3KRWHLB}
After "sendmsg" slash(/) does not need
And When I Type Base Url="https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg" with out last slash(/) then apps unfortunately stop;
For this I Want to remove last "/" any way from Base Url.
private void requestDataForBkashTransaction() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg/")
.addConverterFactory(GsonConverterFactory.create())
.build();
InstituteService api = retrofit.create(InstituteService.class);
String urlString=String.format("?user=Exampll&pass=12345&msisdn=0160000000&trxid=6BM3KRWHLB");
Call<List<Transaction>> call=api.getBkashTrasactionCode(urlString);
call.enqueue(new retrofit2.Callback<List<Transaction>>() {
#Override
public void onResponse(Call<List<Transaction>> call, retrofit2.Response<List<Transaction>> response) {
if(!response.isSuccessful()){
Toast.makeText(PaymentActivity.this, response.code(), Toast.LENGTH_LONG).show();
return;
}
List<Transaction> transactions=response.body();
for(Transaction transaction:transactions){
String content="";
content+=transaction.getTrxId();
textView.append(content);
}
}
#Override
public void onFailure(Call<List<Transaction>> call, Throwable t) {
}
});
}
#GET
Call<List<Transaction>> getBkashTrasactionCode(#Url String url);
This is not how you add query parameters to a call using retrofit. Response code 500 Internal Server Error indicates that. Please refer to this this and add queries properly, then it should work.
To remove last slash,
you have to remove last path from the baseUrl with ../ first, then append it at your urlStirng instead.
String urlString=String.format("../sendmsg?user=Exampll&pass=12345&msisdn=0160000000&trxid=6BM3KRWHLB");
First assign your baseUrl to a String variable and remove the last character as below.
String baseUrl = "https://www.bkashcluster.com:9081/dreamwave/merchant/trxcheck/sendmsg/";
if (baseUrl.endsWith("/")) {
String newBaseUrl = baseUrl.substring(0, baseUrl.length() - 1);
}

MD5 hashcode using spring for http request

i want to generate unique md5 for every http request that will hit REST API.
So far i have just used String requestParameters but actual httpRequest will have many other things.
How can i achieve this ?
public final class MD5Generator {
public static String getMd5HashCode(String requestParameters) {
return DigestUtils.md5DigestAsHex(requestParameters.getBytes());
}
}
My Controller
#RequestMapping(value = { "/dummy" }, method = RequestMethod.GET)
public String processOperation(HttpServletRequest request) {
serviceLayer = new ServiceLayer(request);
return "wait operation is executing";
}
Service layer
private String httpRequestToString() {
String request = "";
Enumeration<String> requestParameters = httpRequest.getParameterNames();
while (requestParameters.hasMoreElements()) {
request += String.valueOf(requestParameters.nextElement());
}
if (!request.equalsIgnoreCase(""))
return request;
else {
throw new HTTPException(200);
}
}
private String getMD5hash() {
return MD5Generator.getMd5HashCode(httpRequestToString());
}
Do you see any issues with generating an UUID for every request and use that instead?
For example, you could generate the UUID and attach it to the request object if you need it during the request life-cycle:
String uuid = UUID.randomUUID().toString();
request.setAttribute("request-id", uuid);
You can combine request time (System.currentTimeMillis()) and remote address from HttpServletRequest. However, if you're expecting high loads, multiple requests may arrive from a particular client in the same millisecond. To overcome this situation, you may add a global atomic counter to your String combination.
Once you generate an MD5 key, you can set it in ThreadLocal to reach afterwards.
You can do this but in future maybe. I search and not found automated way to achieve this
#GetMapping("/user/{{md5(us)}}")

Decode WebTarget URI

I have one property in property file
appointments.deleteAppointmentwithReasonApi=api/appointment/{id}?reason={reason}
URL=http://xyz/etc/
in another file
public static final String DELETE_APPOINTMENT_REASON = PropertiesUtil.getPropertyValueFromKey(REST_WEBSERVICE_URLS_PROP_FILE,
"appointments.deleteAppointmentwithReasonApi"); // To get API name
public static final String URL = ServicesUtil.getURL(); // to get endpoint URL
In my java API call, I gave something like this
WebTarget target = client.target(CommonConstants.URL)
.path(CommonConstants.DELETE_APPOINTMENT_REASON)
.resolveTemplate("id", appointmentID).resolveTemplate("reason", reason);
System.out.println(target);
My response is printing like this...
JerseyWebTarget { http://xyz/etc/api/appointment/abc-123-ced-456%3Freason=Test }
which is not hitting the proper Web Services...I want it to be like this
JerseyWebTarget { http://xyz/etc/api/appointment/abc-123-ced-456?reason=Test }
I know i need to encode URL. I am not able to do it somehow. Any suggestion ?

Play! framework 1.2.5: How to test if response is secure?

A test case for my contact formular page is to make sure it's always in a secure context respectively using SSL. Basically, all I want to know, is that I have a given request where request.secure = true;
The following response does not contain any information about this and its headers are empty:
#Test
public void shouldShowContactForm() {
Response response = GET("/contact");
// How can I ask the response, if the complete URL is in HTTPS?
}
Even if I explicitly set my own request, I cant see the right way to do this:
#Test
public void shouldShowContactFormInSSLContext() {
Request request = newRequest();
request.secure = true;
Response response = GET(request, "/contact");
// Is it now possible?
}
Is this even the right approach to test this or am I simply missing something important about the request/response?
For this question I think what I've done for my apps in the past is have a #before interceptor on all my controllers that looks like this.
#Before
static void checkSSL(){
if(Play.mode.equals(Play.Mode.PROD)){
if(!request.secure) {
Router.ActionDefinition cashTicketDefinition = Router.reverse(request.controller + "." + request.actionMethod);
cashTicketDefinition.absolute();
String url = cashTicketDefinition.url.replaceFirst( "http:", "https:");
redirect(url, true);
}
}
}

Categories

Resources