Attachment optional in REST WS - web-services

I have a POST WS in REST, with Attachment file defined like this :
#POST
#ElementClass(request = AWsDTO.class)
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response createA(#Multipart(value = MULTIPART_DTO_PART, type = MediaType.APPLICATION_JSON) AWsDTO aWsDTO,
#Multipart(MULTIPART_FILE_PART) Attachment file) throws Exception {
...
}
I want that attachment is optional. How to do that ?

I found it :
#Multipart(value = MULTIPART_FILE_PART, required = false) Attachment file)

Related

How to attach a list of strings in the body of a web service request using katalon tool and groovy scripting

** I am facing issue in passing list of Strings and attach them in the body of a delete request in katalon using groovy scripts.***
def request = ((findTestObject('API/phone_numbers/phone_numbers.delete_from_database',[('base_url') : base_url,('account_id') : account_id,
('auth_token') : GlobalVariable.auth_token, ('credentials') : GlobalVariable.credentials])) as RequestObject)
List<String> list_Of_Numbers= {}
for (i in numbers)
{
list_Of_Numbers[i] = i
}
String body = """{"data":{"name":"'$list_Of_Numbers'"}}"""
request.setBodyContent(new HttpTextBodyContent(body))
def response = WS.sendRequest(request)

Why is captured azure eventhub information for SystemProperties and Properites empty?

I am using Azure EventHub and capturing the contents to blob storage using https://learn.microsoft.com/en-us/azure/event-hubs/event-hubs-capture-overview.
Now for the generated Avro files, why is the information stored in the properties and System properties fields empty?
NOTE Azure is populating these fields
I publish the data using a POST request with my payload as the body and authorization headers set.
Am I missing additional headers which would be required to make Azure fill these columns?
edit
so the event hub client`s POST method looks like this:
private val SB_URL = "https://$namespace.servicebus.windows.net/$eventHub"
private val HEADER_AUTHORIZATION = AzureUtil.getSasToken(SB_URL, sas_key_name, sas_key)
private val HEADER_CONTENT_TYPE = "application/atom+xml;type=entry;charset=utf-8"
private val REQ_URL = "https://$namespace.servicebus.windows.net/$eventHub/messages"
private val REQ_TIMEOUT = "60"
private val REQ_API_VERSION = "2014-01"
private val client = OkHttpClient()
private val JSON = "application/json; charset=utf-8".toMediaType()
private var callback: Callback? = null
fun registerCallback(cb: Callback) {
callback = cb
}
fun send(message: String) {
val request = Request.Builder()
.url("$REQ_URL?timeout=$REQ_TIMEOUT&api-version=$REQ_API_VERSION")
.addHeader("Content-Type", HEADER_CONTENT_TYPE)
.addHeader("Authorization", HEADER_AUTHORIZATION)
.post(message.toRequestBody(JSON))
.build()
val call = client.newCall(request)
try {
val response = call.execute()
callback!!.onResponse(call, response)
} catch (error: IOException) {
callback!!.onFailure(call, error)
}
}

Vimeo API C# - Uploading a video

I'm following the api's guide about resumable uploads.
I managed to get a response after step 1 ("create the video"),
with a uri and a upload_link.
About the second part, things are not as clear.
It only says which headers should I sent, but there are two things I don't get,
first - where do I need to put the "upload_link"?
Should the call be like this:
/me/{upload_link}? (of course im also adding the access token, etc)
second, what about the actual file? I guess i should send it in the same method, but how? No word about it.
This is the code for the PATCH request:
public string UploadPatch(
string uploadlink,
string method)
{
var headers = new WebHeaderCollection()
{
{ "Tus-Resumable", "1.0.0" },
{ "Upload-Offest", "0" }
};
method = method.ToUpper();
string body = "";
string contentType = "application/offset+octet-stream";
return Helpers.HTTPUpload(uploadlink, method, headers, body, contentType);
}
And HTTPUpload():
public static string HTTPPatch(string url, string method,
WebHeaderCollection headers, string payload,
string contentType)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.CreateHttp(url);
if (Proxy != null) request.Proxy = Proxy;
request.Headers = headers;
request.Method = method;
request.Accept = "application/vnd.vimeo.*+json; version=3.1";
request.ContentType = contentType;
request.KeepAlive = false;
if (!String.IsNullOrWhiteSpace(payload))
{
var streamBytes = Helpers.ToByteArray(payload);
request.ContentLength = streamBytes.Length;
Stream reqStream = request.GetRequestStream();
reqStream.Write(streamBytes, 0, streamBytes.Length);
reqStream.Close();
}
HttpWebResponse response = (HttpWebResponse)(request.GetResponse());
Debug.WriteLine(((HttpWebResponse)response).StatusDescription);
var dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
Debug.WriteLine(String.Format("Response from URL {0}:", url), "HTTPFetch");
Debug.WriteLine(responseFromServer, "HTTPFetch");
return responseFromServer;
}
Thanks
The upload_link is the URL where you upload the video to. In other words, make your call to the https://[...].cloud.vimeo.com/upload?[...] URL instead of the https://api.vimeo.com host that is used for other API requests.
Additionally, when you make a request to that cloud.vimeo.com upload_link, only provide the required headers as specified in the documentation.
https://developer.vimeo.com/api/upload/videos#resumable-approach
The code is VB.Net, but you can change to C#
'Imports / use these classes
'Imports System.Net
'Imports Newtonsoft.Json
'Imports System.IO
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
'Receive the video from File Upload
If Not IsNothing(fuVideo.PostedFile) Then
'You will need this for SSL
System.Net.ServicePointManager.SecurityProtocol = (SecurityProtocolType.Tls Or (SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls12))
'Path to save the video Save
Dim vFilePath As String = Server.MapPath("App_data/Videos")
Dim vFileNameAndPath As String = vFilePath & "/" & fuVideo.PostedFile.FileName
'Save Video
fuVideo.PostedFile.SaveAs(vFileNameAndPath)
'Get the size
Dim vSize As String = New FileInfo(vFileNameAndPath).Length()
'Vimeo URL
Dim vVimeURL As String = "https://api.vimeo.com/me/videos"
Dim wc As WebClient = New WebClient()
wc.Headers.Clear()
wc.Headers.Add("Authorization", "bearer XXXXXXXXXXXXXXXXX") 'Use your App Code
wc.Headers.Add("Content-Type", "application/json")
wc.Headers.Add("Accept", "application/vnd.vimeo.*+json;version=3.4")
wc.Encoding = System.Text.Encoding.UTF8
'txtName is a text box, so you can give a Title to the Video
Dim vData As String = "{ ""upload"": {""approach"": ""tus"",""size"": """ & vSize & """ }, ""name"" : """ & txtName.Text & """ }"
Dim vimeoTicket = JsonConvert.DeserializeObject(wc.UploadString(vVimeURL, "POST", vData))
wc.Headers.Clear()
wc.Headers.Add("Content-Type", "application/offset+octet-stream")
wc.Headers.Add("Accept", "application/vnd.vimeo.*+json;version=3.4")
wc.Headers.Add("Tus-Resumable", "1.0.0")
wc.Headers.Add("Upload-Offset", "0")
Dim vupload_link As String = vimeoTicket("upload")("upload_link").Value 'Json from Vimeo has the upload_link
Dim vResponse As Byte() = wc.UploadFile(vupload_link, "PATCH", vFileNameAndPath)
Response.Write(System.Text.Encoding.Unicode.GetString(vResponse)) ' If everething is ok, vResponse is Nothing
End If
Catch ex As Exception
ltrErro.Text = "Error"
End Try
End Sub
for this may look at the sample code below:-
I am using a nuget library vimeo-dot-net also at https://github.com/mfilippov/vimeo-dot-net, this has a wrapper built around upload, delete etc.
public ActionResult UploadChapterVideoVimeo(HttpPostedFileBase file, string productID = "")
{
if (file != null){
var authCheck = Task.Run(async () => await vimeoClient.GetAccountInformationAsync()).Result;
if (authCheck.Name != null)
{
BinaryContent binaryContent = new BinaryContent(file.InputStream, file.ContentType);
int chunkSize = 0;
int contenetLength = file.ContentLength;
int temp1 = contenetLength / 1024;
if (temp1 > 1)
{
chunkSize = temp1 / 1024;
chunkSize = chunkSize * 1048576;
}
else
{ chunkSize = chunkSize * 1048576; }
binaryContent.OriginalFileName = file.FileName;
var d = Task.Run(async () => await vimeoClient.UploadEntireFileAsync(binaryContent, chunkSize, null)).Result;
vmodel.chapter_vimeo_url = "VIMEO-" + d.ClipUri;
}
return RedirectToAction("ProductBuilder", "Products", new { productId = EncryptedProductID, message = "Successfully Uploaded video", type = 1 });
}
}
catch (Exception exc)
{
return RedirectToAction("ProductBuilder", "Products", new { productId = EncryptedProductID, message = "Failed to Uploaded video " + exc.Message, type = 0 });
}
}
return null; }

adding id of person in the function responsable for creating a Company (JEE - webservice)

I am trying to link my Company with a specific Person, so I decided then to add a parameter in my function (function responsable for creating a Company). Here is the code:
#POST
public Response create(Long idPerson, CompanyDTO company , #Context UriInfo uriInfo) {
if(company == null)
throw ...
if(idPerson == null)
throw ...
CompanyDTO companyUsed = company;
PersonDTO person =
this.servicePerson.searchPersonById(idPerson);
companyUsed.setPerson(person);
Long idCompany =
this.service.saveCompany(companyUsed); //serviceCompany
if(idCompany == null)
throw ...
UriBuilder builder = uriInfo.getAbsolutePathBuilder();
builder.path(Long.toString(idCompany));
return Response.created(builder.build()).build();
}
When I don't use idPerson in parameters it works well but I specify a static idPerson in my code.
public Response create(CompanyDTO company , #Context UriInfo uriInfo) {
...
PersonDTO person =
this.servicePerson.searchPersonById(1L); // I specify it here statically
... }
So here is the problematic I would like to add idPerson in my parameters. If I do that I got a 500 error. Here is a part of my exception:
com.sun.jersey.spi.container.ContainerResponse.mapMappableContainerException
The exception contained within MappableContainerException could not be
mapped to a response, re-throwing to the HTTP container
org.codehaus.jackson.map.JsonMappingException: Can not deserialize
instance of java.lang.Long out of START_OBJECT token
The person identifier could be defined as a path parameter (it will become part of the URL):
#POST
#Path("{idPerson}")
public Response create(#PathParam("idPerson") Long idPerson,
#Context UriInfo uriInfo, CompanyDTO company,) {
...
}

spring mvc controller test org.springframework.web.HttpMediaTypeNotSupportedException

Can someone help on this?
I am getting the below exception(org.springframework.web.HttpMediaTypeNotSupportedException) when I run this test.
In the response I get this Headers.
Headers = {Accept=[application/octet-stream, text/plain;charset=ISO-8859-1, application/xml, text/xml, application/x-www-form-urlencoded, application/+xml, multipart/form-data, application/json;charset=UTF-8, application/+json;charset=UTF-8, /]}
The add method in the controller is
#RequestMapping(value = "/addTrain", method = RequestMethod.POST)
public #ResponseBody void addTrain(#RequestBody Train train) {
trainService.addTrain(train);
}
I am doing JUnit test for a method. Below is my Test class and MockHttpServletRequest and MockHttpSErvletResponse.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/config/webapp-config.xml" })
#WebAppConfiguration
public class TrainControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext wac;
#InjectMocks
TrainController trainController;
#Mock
private TrainService trainService;
private final List<Train> trainList = new ArrayList<Train>();
private Train train;
#Before
public void setUp() throws Exception {
// Process mock annotations
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
train = new Train();
train.setId(12L);
train.setName("chennai");
train.setSpeed(100);
train.setDiesel(true);
Train train1 = new Train();
train1.setId(15L);
train1.setName("kovai");
train1.setSpeed(150);
train1.setDiesel(false);
trainList.add(train);
trainList.add(train1);
}
#Test
public void testAddTrainList() throws Exception {
Mockito.doNothing().when(trainService).addTrain(train);
this.mockMvc.perform(post("/trains/addTrain")).andDo(print()).andExpect(status().isOk());
}
}
The request and reponse are below:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /trains/addTrain
Parameters = {}
Headers = {}
Handler:
Type = com.xvitcoder.angualrspringapp.controller.TrainController
Method = public void com.xvitcoder.angualrspringapp.controller.TrainController.addTrain(com.xvitcoder.angualrspringapp.beans.Train)
Async:
Was async started = false
Async result = null
**Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotSupportedException**
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
**MockHttpServletResponse:
Status = 415
Error message = null**
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Your request has to specify the Content-type header from one of the acceptable ones.
Try changing your mock request as below:
this.mockMvc.perform(post("/trains/addTrain").contentType(MediaType.APPLICATION_JSON)).andDo(print()).andExpect(status().isOk());
Resolved Exception:
Type = org.springframework.http.converter.HttpMessageNotReadableException