How to generate swagger document for akka http web socket route ?
I have able to write akka Http get,put,post,delete. for example
#Path("/postPing")
#ApiOperation(value = "Find a ping", notes = "Returns a pong",
httpMethod = "POST",response = classOf[String])
#ApiImplicitParams(Array(
new ApiImplicitParam(name = "data", value = "\"data\" to sum", required = true,
dataType = "string", paramType = "query"),
new ApiImplicitParam(name = "file", required = true,
dataType = "file", paramType = "query")
))
#ApiResponses(Array(
new ApiResponse(code = 404, message = "websocket not found"),
new ApiResponse(code = 200, message = "websocket found"),
new ApiResponse(code = 400, message = "Invalid websocket supplied")))
def postRoute = path("postPing") {
complete("post pong")
}
But I need for Akka web socket
def webSocketRoute: Route = path("websocket") {
handleWebSocketMessages(broadcast)
}
def broadcast: Flow[Message, Message, Any] = {
Flow[Message].mapConcat {
case tm: TextMessage =>
TextMessage(tm.textStream) :: Nil
}
}
For example
To connect with websocket server
/connect ws://echo.websocket.org/websocket
To send data to websocket server
/send Hello\ world
Thanks in Advance
Related
I tried to send request to another service containing enum #RequestParam but it always fails.
Here's the example of my request;
fun upsertExclusionOverride(
request: request
): ExcOve? {
val builder = UriComponentsBuilder.fromUriString("/v1/p-b/e/bulk")
val httpEntity = RestTemplateUtils.getHttpEntityCustomHeaders(request, headers)
try {
val body = restTemplate
.exchange(
builder.toUriString(),
HttpMethod.POST,
httpEntity,
Response::class.java
)
.body
?: throw Exception("Fail")
return body.toDomain()
} catch (e: RestClientException) {
log.error(e.message)
throw Exception("Fail")
}
}
This is the other microservice;
#PostMapping("/e/bulk")
#ApiOperation("Exclude")
fun exclusionsInBulk(
#RequestParam(name = "operation", required = true) operation: Operation,
#RequestPart("file") #ApiParam(
value = "File",
required = true,
format = "byte"
) file: MultipartFile
): ResponseEntity<Response> {
.....
}
How should I prevent 400 Bad Request?
I added enum converter but it didn't work.
I expect it to not to get 400 Bad Request.
In my APIendpoint class, I have 2 PUT methods lets say updateA and UpdateB but when I'm trying to hit UpdateB using swagger it resolves to a UpdateA everytime. I dunno what I'm doing wrong because the code seems ok to me. Any help is appreciated.
#Api(value = "/connectroutes", produces = "application/json", consumes = "application/json",
authorizations = Array(new Authorization(value = "")))
#Produces(Array(MediaType.APPLICATION_JSON))
def routes: Route = {
pathPrefix("sampleroute") {
authenticateBasic(realm = "sample realm", authenticator) { authenticationResult =>
updateA ~
updateB
}
}
#PUT
#Path("{name}")
#Produces(Array(MediaType.APPLICATION_JSON))
#Operation(summary = "sample", description = "UPDATE A",
parameters = Array(new Parameter(name = "name", in = ParameterIn.PATH, description = "updateA name", required = true)),
requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[A]), mediaType = MediaType.APPLICATION_JSON))),
)
def updateA: Route = {
path(Segment) { name =>
put {
entity(as[A]) { a: A => {
complete(updateAMethod(name, a))
}
}
}
}
}
#PUT
#Path("updateb")
#Produces(Array(MediaType.APPLICATION_JSON))
#Authorization("basicAuth")
#Operation(summary = "Sample", description = "Update B",
requestBody = new RequestBody(content = Array(new Content(schema = new Schema(implementation = classOf[String]), mediaType = MediaType.APPLICATION_JSON))),
)
def updateB: Route = {
path("updateb" / Segment) { namespace =>
put {
entity(as[String]) { updatedval: String => {
complete(updatedVal))
}
}
}
}
}
I am new to Jersey and to REST in general, so this might be a stupid question....
In my code, I send a request (TemplateValidationRequest) to try to validate an object. If the object fails to validate, I want to return a String. How do I do this?
In the second code snippet at the bottom, you can see that I'm looking for TemplateValidationResponse object. How can I change my code so that:
I can return a string, and
I can get a String instead of a TemplateValidationResponse object.
Is this possible?
#POST
#Path("validate/modelTemplate")
#Produces({MediaType.APPLICATION_JSON})
#Consumes({MediaType.APPLICATION_JSON})
#Operation(
summary = "Convert model template to AMBOS interaction model and validate the result",
tags = { BLUEPRINTS_TAG },
requestBody = #RequestBody(
content = #Content(
schema = #Schema(
implementation = TemplateValidationRequest.class
)
)
),
responses = {
#ApiResponse(
responseCode = "200",
description = "Success.",
content = #Content(
schema = #Schema(
implementation = TemplateValidationResponse.class
)
)
),
#ApiResponse(
responseCode = "400",
description = "Failure",
content = #Content(
schema = #Schema(
implementation = String.class
)
)
)
}
)
#CustomerIdentityRequired
#AcceptsLanguageRequired
#AAA(serviceName = SERVICE_NAME, operationName = BLUEPRINTS_GET)
ModelTemplateValidationResponse validateModelTemplate(TemplateValidationRequest);
fun validateModelTemplate(modelTemplate: InteractionModel,
sampleData: Map<String, Any>): TemplateValidationResponse {
val request = TemplateValidationRequest()
request.modelTemplate = modelTemplate
request.sampleData = sampleData
return temp.validateModelTemplate(request)//this is where I call the above code
//If this request fails and results in a 400 error, I want to get a String
}
What about something like:
public Class YourResponse {
private boolean isError;
private String setThisWhenThereIsError;
private YourObject setThisWhen200;
}
I am sending a post to /document (swagger), which should upload a document using the body content of
{
"Application": "tickets",
"File": "some binary data"
}
The back in is using swagger /document so I believe my headers are not coming over correctly.
The problem is I am not getting the correct combination of the headers that need to be sent over:
Authorization : xxxx;
Content-Type : multipart/form-data;
Content-Type : image/png;
Content-Type : application/json;
FileName : file_name
Response:
415 Unsupported Media Type
FileInfo fi = new FileInfo(#"file");
byte[] fileContents = File.ReadAllBytes(fi.FullName);
ByteArrayContent byteArrayContent = new ByteArrayContent(fileContents);
byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
byteArrayContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = fi.Name,
};
MultipartFormDataContent multiPartContent = new MultipartFormDataContent();
multiPartContent.Add(new StringContent("document storage"), "Application");
multiPartContent.Add(byteArrayContent, "File");
string header = string.Format("WRAP access_token=\"{0}\"", "xxxx");
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/document");
request.Headers.Add("Authorization", header);
request.Content = multiPartContent;
HttpClient httpClient = new HttpClient();
try
{
Task<HttpResponseMessage> httpRequest = httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
HttpResponseMessage httpResponse = httpRequest.Result;
HttpStatusCode statusCode = httpResponse.StatusCode;
HttpContent responseContent = httpResponse.Content;
if (responseContent != null)
{
Task<String> stringContentsTask = responseContent.ReadAsStringAsync();
String stringContents = stringContentsTask.Result;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
I am trying to get xml data from apache ranger using it's rest api. Here is my code
val httpclient = new DefaultHttpClient()
val auth=new AuthScope(host,AuthScope.ANY_PORT)
val credentials=new UsernamePasswordCredentials(username, password)
httpclient.getCredentialsProvider()
.setCredentials(auth, credentials)
val httpget = new HttpGet("http://localhost:6080/service/public/api/repository/1")
httpget.setHeader("Accept", "application/xml")
val response = httpclient.execute(httpget)
val entity = response.getEntity
if (entity != null) {
val in = new BufferedReader(new InputStreamReader(entity.getContent()))
var line = in.readLine()
var response = new StringBuffer()
while (line != null) {
response.append(line)
line = in.readLine()
}
in.close()
println(response.toString())
}
If i hit this url from browser it shows result fine. But in case of code it returns html.
Any help?
Try this code
val httpclient = new DefaultHttpClient()
val httpget = new HttpGet("url")
httpget.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials("user", "pass"),
"UTF-8", false))
httpget.setHeader("Accept", "application/json")
val response = httpclient.execute(httpget)
EntityUtils.toString(response.getEntity())
setting authentication in the request.
Thanks