add parameter to an http header using java webservice - java

i have this http header :
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Tue, 15 Mar 2016 17:08:29 GMT
And what i want is to add 2 parameter: mytotalcount and mytotalresult.
i have to add this into my response however it's not working i can't do:
response.Headers.Add("mytotalcount", "10");
Also can't do
request.setAttribute("mytotalcount","10");
So i am blocked any ideas please ? Thanks for your help !
Here is the part of the code:
public class SitesResponse {
private Result result;
private List<GeographicSite> site;
public SitesResponse () {
this.result = new Result();
this.site = new ArrayList<GeographicSite>();
}
public List<GeographicSite> getSite() {
return site;
}
public void setSite(List<GeographicSite> site) {
this.site = site;
}
}
Ensuite l'autre classe qui utilise SitesResponse
SitesResponse response = new SitesResponse();
et
if (testiing) {
try {response = siteManager.geographicSitesAPIV1(args);
response.getResult().setCode("error");
response.getResult().setLabel("no addr found");
And this is what i tried ... earlier
System.out.println(response.toString().getBytes().toString()+"azezae");
// request.Headers.Add("headername", "headervalue");
// request.setAttribute("X-Total-Count","10");
//response.setAttribute("X-Result-Count", "7");
//response.setIntHeader("mytotalcount", 5);
//////////////////////////////////////////////////:::::::
In picture where i want to add my two parameters result from SOAPui

Hello again Thank you for your time,
i was trying to edited the wrong class so what i did you just
resp.addIntHeader(att, 10);
resp.addIntHeader(att2, 5);
Thank you for your time and answers!

Related

Request method 'PUT' not supported StatusCode: 405

I get this warning
2017-05-25 00:48:43.125 WARN 7104 --- [nio-8080-exec-4] o.s.web.servlet.PageNotFound : Request method 'PUT' not supported
in intelliJ when I'm trying to do an update from c# (Visual Studio). But when I'm doing that update from Java, it works.
update method in Java:
#RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public Proba update(#RequestBody Proba proba) {
System.out.println("Updating proba ...");
try{
probaRepository.update(proba.getIdProba(),proba);
} catch (Exception e){
e.printStackTrace();
}
return proba;
}
C# method
static async Task<string> UpdateProbaAsync(string path, Proba proba)
{
string res = null;
HttpResponseMessage response = await client.PutAsJsonAsync(path, proba);
if (response.IsSuccessStatusCode)
{
res = await response.Content.ReadAsStringAsync();
}
return res;
}
and here is how I call UpdateProbaAsync
var rezU = await UpdateProbaAsync("http://localhost:8080/concurs/probe", new Proba(9, "cautare comori UPDATE", "3-5 ani", 0));
var probeUpdate = await GetProbaAsync("http://localhost:8080/concurs/probe");
foreach (var proba in probeUpdate)
{
Console.WriteLine(proba.ToString());
}
this is what I get for HttpResponseMessage response
+ response {StatusCode: 405, ReasonPhrase: '', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
Transfer-Encoding: chunked
Connection: close
Date: Wed, 24 May 2017 21:57:39 GMT
Allow: POST
Allow: GET
Content-Type: application/json; charset=UTF-8
}} System.Net.Http.HttpResponseMessage
I guess you are missing the attribute from the c#
[HttpPut] //or [HttpPost]
[Route("/{path}")]
async Task<string> UpdateProbaAsync(string path, Proba proba)
{
}
default is GET and you are trying to put onto a GET API

Retrofit error: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

The Java:
private void apiPasswordReset(final String msisdn) {
showLoading();
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(Constants.API_THREADPOOL_SIZE));
ListenableFuture<ResponseBase> response = service.submit(new Callable<ResponseBase>() {
#Override
public ResponseBase call() throws Exception {
return webService.passwordReset(
Constants.RESPONSE_TYPE_APPLICATION_JSON,
getResources().getString(R.string.api_key),
getResources().getString(R.string.channel_id),
getResources().getString(R.string.app_id),
getResources().getString(R.string.base_url),
getResources().getString(R.string.base_url_port),
getResources().getString(R.string.api_version_string),
msisdn
);
}
});
Futures.addCallback(response, new FutureCallback<ResponseBase>() {
#Override
public void onSuccess(final ResponseBase result) {
Log.i(TAG, "onSuccess()");
}
#Override
public void onFailure(Throwable t) {
Log.e(TAG, t.getMessage());
}
});
}
Response Model:
public class ResponseBase {
private boolean success;
private String response_code;
private String api_version;
private String message;
private String base_url;
}
The call:
#GET("/{endpoint}:{endpointPort}/api/{apiVersion}/users/{msisdn}/edit")
ResponseBase passwordReset(
#Header("Content-type") String contentType,
#Header("x-api-key") String apiKey,
#Header("channel-id") String channelId,
#Header("app-id") String appId,
#Path("endpoint") String endpoint,
#Path("endpointPort") String endpointPort,
#Path("apiVersion") String apiVersion,
#Path("msisdn") String msisdn
);
Request:
---> HTTP GET
x-api-key: 5ffc84c4-d1ad-29e8-4114-d84708bf96ac
channel-id: 1
app-id: android_001
Content-Type: application/json
---> END HTTP (no body)
Response:
<--- HTTP 200 (1013ms)
: HTTP/1.1 200 OK
Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 217
Content-Type: application/json
Date: Mon, 11 Apr 2016 08:31:40 GMT
Keep-Alive: timeout=5, max=100
Server: Apache/2.4.7 (Ubuntu)
Set-Cookie: XSRF-TOKEN=eyJpdiI6Ikt5RWM4UFhDc1hrVytNRkNlc0QySVE9PSIsInZhbHVlIjoiVmZ4KzF5bVdkY2xwbmJsaGZMbDZ1NldpNVp6bGsyemIyVGVKUzhcLzIrZDN3R3pGRWRVd0FWdnlnTjhaZCtyQ2JacTcybllvMW1ZOElaMU5TZUNpYUp3PT0iLCJtYWMiOiI3YjBiZDM4MjM4OWMxMDRlOThiODU5ZDc1M2RhZTA5YmYyNDM0ZGE1NDQ0ZjQ0YWRmOTM5MjQ1NTI0ODkwNTAxIn0%3D; expires=Mon, 11-Apr-2016 10:31:40 GMT; Max-Age=7200; path=/
Set-Cookie: laravel_session=eyJpdiI6ImsyVXcrRHpHY2FOakhZZDhIYjRnR1E9PSIsInZhbHVlIjoiQTRcL2g0c1Ztdk9MbTl3MlNTblwvdHhicStrTHMzYlZmb3I2ZVc1NjBwNWIwYWQ5NjB2UXVyQzZBSUpLTzRcL0dta0gxUVR2ZnhaWnFoQStEUm93Q0lESlE9PSIsIm1hYyI6ImQxYmY4NDk2OTgzNDZlZDVlMmM0MTUyMzMzN2ZhMmQ3YzY1ZWYyMTZlMDA4NWY3ZDc1ZTIzMTc1NzdmMzM3YjkifQ%3D%3D; expires=Mon, 11-Apr-2016 10:31:40 GMT; Max-Age=7200; path=/; httponly
X-Android-Received-Millis: 1460363500117
X-Android-Response-Source: NETWORK 200
X-Android-Sent-Millis: 1460363499337
X-Powered-By: PHP/5.5.9-1ubuntu4.14
Version OK 5.5.9-1ubuntu4.14
{"success":true,"response_code":"OK","api_version":1,"message":"PASSWORD RESET NOTIFICATION SENT SUCCESSFULLY","error":[],"base_url":"http:\/\/apiserver.com","data":[]}
The response data seems to fit the model. When I run this call with postman it returns valid json aswell. I have commented out all fields in the model and still get the same error.
Any help would be appreciated :)
Versions:
Android studio 2.0
Gradle 2.0
Retrofit 1.9.0
Guava 19.0
FIX:
Due to my own stupidity :|
Server was including text ouside the object in the response that should be part of the header. Thanks for the assist guys!
Postman response:
Version OK 5.5.9-1ubuntu4.14
{"success":true,"response_code":"OK","api_version":1,"message":"PASSWORD RESET NOTIFICATION SENT SUCCESSFULLY","error":[],"base_url":"http:\/\/apiserver.com","data":[]}

Jersey declarative linking doesn't work

I try to make a restfull web service with Jersey. I would like to give a link in the response of that request :
GET /mac/ws/gtm HTTP/1.1
Host: localhost:8080
Accept: application/json
Cache-Control: no-cache
I want the response to be :
HTTP/1.1 200 OK
link: </dossiers>;rel=dossiers
{
"message": "Hello"
}
But the response is :
HTTP/1.1 200 OK
{
"message": "Hello"
}
The link is not produce !
Look my Gtm Resource :
#Component
#Path("/gtm")
public class GTmRessource
{
#GET
#Produces(MediaType.APPLICATION_JSON)
public GTm getJson()
{
GTm gtm = new GTm();
return gtm;
}
}
And my Gtm entity
#XmlRootElement()
#Link(value = #Ref(value = "/dossiers", method = "get"), rel = "dossiers")
public class GTm
{
String message = "Hello";
public String getMessage()
{
return message;
}
public void setMessage(String message)
{
this.message = message;
}
}
What's wrong ?
Thanks for help.
By
See Declarative Hyperlinking: Configuration
You need to add the LinkFilter either programmatically:
resourceConfig.getContainerResponseFilters().add(LinkFilter.class);
or through web.xml
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.sun.jersey.server.linking.LinkFilter</param-value>
</init-param>
C:\>curl -i http://localhost:8080/gtm
HTTP/1.1 200 OK
Content-Type: application/json
Link: </dossiers>;rel=dossiers
Date: Thu, 04 Dec 2014 12:38:06 GMT
Transfer-Encoding: chunked
{"message":"Hello"}

soap response encoding '?' characters in all strings instead of russian .Net proxy, Java server(?)

I generate proxy classes with wsdl.exe to request web-services, that are probably build at java platform. The problem is with encoding of response. I get '?' instead of russian letters.(for example '????26' instead of 'АН26')
I also use soapUI and everything works well there. I am not experienced at configuring .Net clients. So how I could determine and configure proper encoding for response. I already played with app.config as next:
I attach headers information here. I don't wee encoding info at responce headers...
request headers:
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "urn:#DCSSci_ListFlight_5"
Content-Length: 641
Host: 109.73.1.66:23022
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
response headers:
HTTP/1.1 200 OK
Date: Thu, 06 Sep 2012 03:47:52 GMT
Server: Apache/2.2.10 (Linux/SUSE)
200 OKX-FidelXML-Version: 2.0
Content-length: 15464
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive
Content-Type: text/xml
Solution:
public class TraceExtension : SoapExtension
{
Stream oldStream;
Stream newStream;
public override Stream ChainStream(Stream stream)
{
oldStream = stream;
newStream = new MemoryStream();
return newStream;
}
public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
{
return null;
}
public override object GetInitializer(Type WebServiceType)
{
return null;
}
public override void Initialize(object initializer)
{
}
public override void ProcessMessage(SoapMessage message)
{
switch (message.Stage)
{
case SoapMessageStage.BeforeSerialize:
break;
case SoapMessageStage.AfterSerialize:
newStream.Position = 0;
Copy(newStream, oldStream);
break;
case SoapMessageStage.BeforeDeserialize:
message.ContentType = "application/soap+xml; utf-8";
Copy(oldStream, newStream);
newStream.Position = 0;
break;
case SoapMessageStage.AfterDeserialize:
break;
}
}
void Copy(Stream from, Stream to)
{
TextReader reader = new StreamReader(from, System.Text.Encoding.GetEncoding("utf-8"));
TextWriter writer = new StreamWriter(to, System.Text.Encoding.GetEncoding("utf-8"));
writer.WriteLine(reader.ReadToEnd());
writer.Flush();
}
}
[AttributeUsage(AttributeTargets.Method)]
public class TraceExtensionAttribute : SoapExtensionAttribute
{
private int priority;
public override Type ExtensionType
{
get { return typeof(TraceExtension); }
}
public override int Priority
{
get { return priority; }
set { priority = value; }
}
}
And than just add
[TraceExtension()]
attribute for proxy invoke method
You can override GetWebResponse of your proxy and change the encoding
public class YourProxyClass : SoapHttpClientProtocol
{
protected override WebResponse GetWebResponse(WebRequest request)
{
var response = base.GetWebResponse(request);
response.Headers["Content-Type"] = "text/xml; charset=utf-8"; //<==
return response;
}
}

SIP servlets, chatserver

I'm trying to get a SIP servlet chat server working, together with the textclient found here.
When I use 2 clients to send messages to eachother (peer to peer), everything goes well. But when I use one or more clients together with my server, I have to wait exactly 32 seconds before the server picks up any new messages in the doMessage() method.
I'm using Netbeans together with Sailfin as my SIP server. Is there some kind of limitation or configurable delay or timeout between requests or responses in Sailfin I'm looking over?
I can post the server code, if needed.
Thanks
Here is the code of the server, i'll try to make a wireshark trace later.
public class ChatroomSipServlet extends SipServlet {
public final static String USER_LIST = "userList";
public final static String CHATROOM_SERVER_NAME = "chatroomservername";
public String serverAddress;
public SipFactory factory;
#Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init(servletConfig);
System.out.println("Chatroom sip servlet is gestart!");
try {
factory = (SipFactory) getServletContext().getAttribute("javax.servlet.sip.SipFactory");
System.out.println("Sip Factory: " + factory);
} catch (Exception e) {
throw new ServletException("Factory probleem!", e);
}
getServletContext().setAttribute(USER_LIST, new ArrayList<String>());
serverAddress = getServletConfig().getInitParameter(CHATROOM_SERVER_NAME);
System.out.println("serverAddress is: " + serverAddress);
}
#Override
public void destroy() {
try {
sendToAll(serverAddress, "Server sluit af!");
} catch (Throwable e) {
e.printStackTrace();
}
super.destroy();
}
protected void doMessage(SipServletRequest request) throws ServletException, IOException {
System.out.println(getDateTime() + " Bericht ontvangen");
request.createResponse(SipServletResponse.SC_OK).send();
String message = request.getContent().toString();
String from = ((SipURI) request.getFrom().getURI()).toString();
if (message.equalsIgnoreCase("/quit")) {
sendToUser(from, "Bye");
removeUser(from);
return;
}
if (!containsUser(from)) {
sendToUser(from, "Welkom in de chatroom. Typ '/quit' om af te sluiten.");
addUser(from);
}
if (message.equalsIgnoreCase("/who")) {
String users = "Lijst van de gebruikers:\n";
List<String> list = (List<String>) getServletContext().getAttribute(USER_LIST);
for (String user : list) {
users += user + "\n";
}
sendToUser(from, users);
return;
}
if (message.equalsIgnoreCase("/join")) {
return;
}
sendToAll(from, message);
}
protected void doErrorResponse(SipServletResponse response) throws ServletException, IOException {
// String receiver = response.getTo().toString();
String receiver = ((SipURI) response.getTo().getURI()).toString();
System.out.println(getDateTime() + " Errorresponse voor " + receiver);
removeUser(receiver);
}
protected void doSuccessResponse(SipServletResponse response) throws ServletException, IOException {
response.getApplicationSession().invalidate();
}
private void sendToAll(String from, String message) throws ServletParseException, IOException {
List<String> list = (List<String>) getServletContext().getAttribute(USER_LIST);
for (String user : list) {
SipApplicationSession session = factory.createApplicationSession();
System.out.println(getDateTime() + " Session created voor " + user);
SipServletRequest request = factory.createRequest(session, "MESSAGE", serverAddress, user);
String msg = from + " stuurt: \n" + message;
request.setContent(msg.getBytes(), "text/plain");
request.send();
}
}
private void sendToUser(String to, String message) throws ServletParseException, IOException {
SipApplicationSession session = factory.createApplicationSession();
SipServletRequest request = factory.createRequest(session, "MESSAGE", serverAddress, to);
request.setContent(message.getBytes(), "text/plain");
request.send();
}
private boolean containsUser(String from) {
List<String> list = (List<String>) getServletContext().getAttribute(USER_LIST);
return list.contains(from);
}
private void addUser(String from) {
List<String> list = (List<String>) getServletContext().getAttribute(USER_LIST);
list.add(from);
}
private void removeUser(String from) {
System.out.println(getDateTime() + " " + from + " wordt verwijderd uit de lijst.");
List<String> list = (List<String>) getServletContext().getAttribute(USER_LIST);
list.remove(from);
}
#Override
protected void doRegister(SipServletRequest req) throws ServletException, IOException {
System.out.println("Register request ontvangen: " + req.getTo());
int response = SipServletResponse.SC_OK;
SipServletResponse resp = req.createResponse(response);
resp.send();
}
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("[" + "HH:mm:ss" + "]");
Date date = new Date();
return dateFormat.format(date);
}
}
And the sip.xml
<sip-app>
<app-name>sip.chatvoorbeeld.ChatServer</app-name>
<display-name>Chatroom Sip Servlet</display-name>
<description>Chatroom Sip Servlet</description>
<servlet-selection>
<main-servlet>
ChatroomSipServlet
</main-servlet>
</servlet-selection>
<session-config>
<session-timeout>5</session-timeout>
</session-config>
<servlet>
<servlet-name>ChatroomSipServlet</servlet-name>
<display-name>ChatroomSipServlet</display-name>
<description>Chatroom SIP servlet</description>
<servlet-class>
sip.chatvoorbeeld.ChatroomSipServlet
</servlet-class>
<init-param>
<param-name>chatroomservername</param-name>
<param-value>sip:chatserver#192.168.56.1:5060</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
</sip-app>
I also tried an empty servlet, just with a doMessage() method that just prints out "message received". Same 32 seconds delay...
Wireshark gives me:
I send the message "test" to the server:
MESSAGE sip:chatserver#192.168.56.1:5060;transport=udp SIP/2.0
Call-ID: aba00c2646a9b4e6df3b15df19dbf58d#192.168.56.101
CSeq: 1 MESSAGE
From: "bobby" <sip:bobby#192.168.56.101:5095>;tag=textclientv1.0
To: "chatserver" <sip:chatserver#192.168.56.1:5060>
Via: SIP/2.0/UDP 192.168.56.101:5095;branch=branch1
Max-Forwards: 70
Contact: "bobby" <sip:bobby#192.168.56.101:5095>
Content-Type: text/plain
Content-Length: 4
test
Server sends back:
SIP/2.0 200 OK
Content-Length: 0
To: "chatserver"<sip:chatserver#192.168.56.1:5060>;tag=g9vdns7u-e
Cseq: 1 MESSAGE
Via: SIP/2.0/UDP 192.168.56.101:5095;branch=branch1
From: "bobby"<sip:bobby#192.168.56.101:5095>;tag=textclientv1.0
Call-Id: aba00c2646a9b4e6df3b15df19dbf58d#192.168.56.101
Server: Glassfish_SIP_2.0.0
MESSAGE sip:bobby#192.168.56.101:5095 SIP/2.0
Max-Forwards: 69
Content-Length: 43
To: <sip:bobby#192.168.56.101:5095>
Cseq: 1 MESSAGE
Via: SIP/2.0/UDP 192.168.56.1:5060;branch=z9hG4bKdaacb7673c871796474ca951221a6643db6c
Content-Type: text/plain
Call-Id: 192.168.56.1_11_6595680936174578736
From: <sip:chatserver#192.168.56.1:5060>;tag=g9vdns7u-g
sip:bobby#192.168.56.101:5095 stuurt:
test
Then my client again answers with an OK:
SIP/2.0 200 OK
To: <sip:bobby#192.168.56.101:5095>;tag=888
CSeq: 1 MESSAGE
Via: SIP/2.0/UDP 192.168.56.1:5060;branch=z9hG4bKdaacb7673c871796474ca951221a6643db6c;received=192.168.56.1
Call-ID: 192.168.56.1_11_6595680936174578736
From: <sip:chatserver#192.168.56.1:5060>;tag=g9vdns7u-g
Content-Length: 0
So far so good, everything works well.
But now I send a second message to the server "test2" and I get this:
Client to server:
MESSAGE sip:chatserver#192.168.56.1:5060;transport=udp SIP/2.0
Call-ID: 95ad65365378b9b6b5bd7ad3629f7b02#192.168.56.101
CSeq: 1 MESSAGE
From: "bobby" <sip:bobby#192.168.56.101:5095>;tag=textclientv1.0
To: "chatserver" <sip:chatserver#192.168.56.1:5060>
Via: SIP/2.0/UDP 192.168.56.101:5095;branch=branch1
Max-Forwards: 70
Contact: "bobby" <sip:bobby#192.168.56.101:5095>
Content-Type: text/plain
Content-Length: 5
test2
Then the server does respond with:
SIP/2.0 200 OK
Content-Length: 0
To: "chatserver"<sip:chatserver#192.168.56.1:5060>;tag=g9vdns7u-e
Cseq: 1 MESSAGE
Via: SIP/2.0/UDP 192.168.56.101:5095;branch=branch1
From: "bobby"<sip:bobby#192.168.56.101:5095>;tag=textclientv1.0
Call-Id: aba00c2646a9b4e6df3b15df19dbf58d#192.168.56.101
Server: Glassfish_SIP_2.0.0
But then the communication stops... I get a 200 OK, but the println() in my doMessage() method is not passed.
32 seconds is the normal timeout for transactions (denoted 64*T1 in RFC3261, where the default for T1 is 500ms.)
I have no direct idea for a solution to your problem, except that the timeout is very likely NOT a misconfiguration in SailFin. So please provide a wireshark trace and the server code!
To answer my own question, if someone ever encounters the same problem, i found this is a bug in the textclient against the following section 8.1.1.7 of RFC 3261.
The branch parameter value MUST be
unique across space and time for all
requests sent by the UA. The
exceptions to this rule are CANCEL and
ACK for non-2xx responses. As
discussed below, a CANCEL request will
have the same value of the branch
parameter as the request it cancels.
As discussed in Section 17.1.1.3, an
ACK for a non-2xx response will also
have the same branch ID as the INVITE
whose response it acknowledges.
The uniqueness property of the branch
ID parameter, to facilitate its use as
a transaction ID, was not part of RFC
2543.
The branch ID inserted by an element
compliant with this specification MUST
always begin with the characters
"z9hG4bK".
The following line in SipLayer.java
ViaHeader viaHeader = headerFactory.createViaHeader(getHost(),
getPort(), "udp", "branch1");
Will create every message with the "branch1" parameter. Making this parameter unique fixes the problem.

Categories

Resources