Jersey: Can I add a cookie in ContainerResponseFilter? - cookies

I have a ContainerResponseFilter and I tried to set a cookie in it as follows:
#Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
String cookieName = "ExampleCookie";
String cookieValue = "SomeData";
logger.info("Setting cookie " + cookieName + " with value " + cookieValue + " into cookies " + JsonUtils.objectToJson(containerResponseContext.getCookies()));
containerResponseContext.getCookies().put(cookieName, new NewCookie(cookieName, cookieValue));
}
But this give the following error:
Caused by: java.lang.UnsupportedOperationException: null
at java.util.AbstractMap.put(AbstractMap.java:203) ~[na:1.7.0_67]
It is not possible to set the cookie here? If it is, how would I do it?

Yeah seems a bit odd that this is not allowed. Not sure why this is not allowed. I've tested both with Jersey and Resteasy. With Resteasy, all that happens is that the cookie is not set (no Exception). I'm thinking some operation sets the cookies as headers, and by the time the filter is reached, no further operation is done with the cookies.
The only work around I can think of is to simply set the header yourself
responseContext.getHeaders().add("Set-Cookie", new NewCookie("Hello", "World"));
The toString() of NewCookie will return how it should look in the header
Set-Cookie: Hello=World;Version=1

Related

Illegal unquoted character ((CTRL-CHAR, code 10))

I’m having issue consuming REST API. Below is my rest client. It fails at the service call with error:
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value; nested exception is com.fasterxml.jackson.core.JsonParseException: Illegal unquoted character ((CTRL-CHAR, code 10)): has to be escaped using backslash to be included in string value
at [Source: java.io.PushbackInputStream#62a8dd06; line: 11, column: 55]
When I use the same json string (printed in the log) in postman, it works. It fails when I fire the request from my client.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Basic " + base64Creds);
try {
request = mapper.constructRequest(txnRequest, params);
logger.debug(method + " Request: " + request);
ObjectMapper map = new ObjectMapper();
logger.debug(method + " Request in json format: " +
map.writeValueAsString(request));
myRequest = new HttpEntity<MyRequest>(request, headers);
response = restTemplate.exchange(url, HttpMethod.POST, myRequest, MyResponse.class);
logger.debug(method + " response: " + response);
} catch(Exception ex) {
ex.printStackTrace();
}
Any help is much appreciated.
I switched to traditional HttpURLConnection to make this work. In this way, I'm able to set the input and output format with utf-8 and it worked. I tried to do the same with rest template, but the issue was persisting. So, I'd to switch my client implementation to HttpURLConnection

Tracking user id from cookie with Google tag manager

I am trying to write my user ID to cookie. I can catch it from dataLayer variable from server when user is login in but user can be already logged in next session. So I tried to create custom JavaScript code that suppose to check if variable is not undefined and write a cookie and if the cookie exist then returns cookie value.
function() {
if ({{UID dataLayer}}) {
var d = new Date();
d.setTime(d.getTime() + 1000 * 60 * 60 * 24 * 365 * 2);
var expiresdate = 'Expires=' + d.toGMTString();
document.cookie = 'UIDcookie=' + {{UID dataLayer}} + '; ' + expiresdate + '; Path=/';
return {{UID dataLayer}};
} else if ({{UID Cookie}}) {
return {{UID Cookie}};
}
return;
}
But it works only when I'm in tagmanager debug mode, when it's off nothing suppose to happen. So my question is what am I doing wrong?
It's probably a question of timing. Try to fire the tag to the page load, in this way the function in JS variable should be able to read the cookie.

mockito NullPointerException

Hi I have the following test and I cannot make it work, its giving NullPointerException:
Method to test :
private ResponseEntity getDefaultCart(HttpEntity<String> request, String zoomQuery) {
LOG.info("Get user's default cart with zoom query" + zoomQuery);
String defaultCartUrl = cortexApiUrl + Constants.CARTS + scope + Constants.DEFAULT + Constants.ZOOM + zoomQuery;
return baseRepository.getCall(defaultCartUrl, request);
}
Junit of this method:
#Test
public void testUpdateCart() {
MockitoAnnotations.initMocks(this);
cortexRepository= new CortexRepositoryImpl("https://abc.juy", "ocean", baseRepositoryImpl);
Mockito.when(baseRepositoryImpl.createRequestHeaders("guestId")).thenReturn(httpHeaders);
JSONObject orderDetails = createCortexCreateOrderObject("cortexCreateOrderResponse.json");
ResponseEntity<JSONObject> entity=new ResponseEntity<JSONObject>(orderDetails,HttpStatus.ACCEPTED);
HttpEntity<String> request = new HttpEntity<String>(httpHeaders);
Mockito.when(baseRepositoryImpl.getCall("http://www.abc.hyh", request)).thenReturn(entity);
cortexRepository.updateCart(updateCartRequest);
}
Method getDefaultCart is calling from updateCart method.The object orderDetails is filling correctly.
NUllPointer is giving on line : baseRepository.getCall(defaultCartUrl, request).
Any suggestion ??
I think that the instance of BaseRepositoryImpl being used when you call baseRepository.getCall(defaultCartUrl, request); is not the same instance being passed to new CortexRepositoryImpl("https://abc.juy", "ocean", baseRepositoryImpl);.
So make sure that you are not creating a new instance of it in CortexRepositoryImpl and are in fact using the object passed into the constructor.
I can't be sure without the source of CortexRepositoryImpl but this seems like the most likely issue.

How to get value of 'CARBON_HOME' in java code

I was trying to implement an Axis2 service that receives user requests and publishes them as events to a CEP using carbon databridge thrift (via 'org.wso2.carbon.databridge.agent.thrift.DataPublisher')
I followed the code sample provided in wso2cep-3.1.0/samples/producers/activity-monitor
please see the following code snippet
public class GatewayServiceSkeleton{
private static Logger logger = Logger.getLogger(GatewayServiceSkeleton.class);
public RequestResponse request(Request request)throws AgentException,
MalformedStreamDefinitionException,StreamDefinitionException,
DifferentStreamDefinitionAlreadyDefinedException,
MalformedURLException,AuthenticationException,DataBridgeException,
NoStreamDefinitionExistException,TransportException, SocketException,
org.wso2.carbon.databridge.commons.exception.AuthenticationException
{
final String GATEWAY_SERVICE_STREAM = "gateway.cep";
final String VERSION = "1.0.0";
final String PROTOCOL = "tcp://";
final String CEPHOST = "cep.gubnoi.com";
final String CEPPORT = "7611";
final String CEPUSERNAME = "admin";
final String CEPPASSWORD = "admin";
Object[] metadata = { request.getDeviceID(), request.getViewID()};
Object[] correlationdata = { request.getSessionID()};
Object[] payloaddata = {request.getBucket()};
KeyStoreUtil.setTrustStoreParams();
KeyStoreUtil.setKeyStoreParams();
DataPublisher dataPublisher = new DataPublisher(PROTOCOL + CEPHOST + ":" + CEPPORT, CEPUSERNAME, CEPPASSWORD);
//create event
Event event = new Event (GATEWAY_SERVICE_STREAM + ":" + VERSION, System.currentTimeMillis(), metadata, correlationdata, payloaddata);
//Publish event for a valid stream
dataPublisher.publish(event);
//stop
dataPublisher.stop();
RequestResponse response = new RequestResponse();
response.setSessionID(request.getSessionID());
response.setDeviceID(request.getDeviceID());
response.setViewID(request.getViewID());
response.setBucket(request.getBucket());
return response;
}
there is also a utility class that set the key store parameters as following
public class KeyStoreUtil {
static File filePath = new File("../../../repository/resources/security");
public static void setTrustStoreParams() {
String trustStore = filePath.getAbsolutePath();
System.setProperty("javax.net.ssl.trustStore", trustStore + "/client-truststore.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
}
public static void setKeyStoreParams() {
String keyStore = filePath.getAbsolutePath();
System.setProperty("Security.KeyStore.Location", keyStore + "/wso2carbon.jks");
System.setProperty("Security.KeyStore.Password", "wso2carbon");
}
}
I uploaded the service into a wso2as-5.2.1, and called the service using SOAPUI
the request returned an error message "cannot borrow client for TCP"
I debug, and found out the problem might lies with the class 'KeyStoreUtil',
where the 'filePath' somehow retuned a 'null',
static File filePath = new File("../../../repository/resources/security");
and caused the failure on this line
DataPublisher dataPublisher = new DataPublisher(PROTOCOL + CEPHOST + ":" + CEPPORT, CEPUSERNAME, CEPPASSWORD);
I guess it could be a better idea if I use the value of "CARBON_HOME" to figure out the location of Key Store
so my question is :
How may I be able to get the value of 'CARBON_HOME' in the Java code?
that said. If you think a bit more:
the service will be called numerous time; whileas the 'setTrustStoreParams' and the 'setKeyStoreParams' will only be needed to executed once at the server/service initiate.
So, are there any even better ways to remove 'setTrustStoreParams' and 'setKeyStoreParams' out of the service code, or implement as configurable items?
Please advise
thanks
so my question is :
How may I be able to get the value of 'CARBON_HOME' in the Java code?
You should use the property carbon.home like following which will retrieve the WSO2 product's home directory.
System.getProperty("carbon.home");

Increment a cookie value by 1

I have a text field and a submit button. User submits an email id and on successful submission a lightbox will load. On successful submission I am setting a cookie and initially assigning a value of 1. Though I am able to set the increment I am not able to assign the incremented value to the cookie value.
var demoCookieCount = getCookie("democount");
$('#online-demo-lightbox-button').click(function (e) {
e.preventDefault();
demoCookiecount++;
});
You have to store the new value in the cookie by using setCookie() or something like
function setCookie(democount, ++demoCookiecount, 1)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
You don't save the new value into the cookie. Try something like that in the end:
document.cookie = cookieName + cookieContent + cookieExpires;
Finally somehow got through. This piece of code worked
//setting the Cookie democount with initial value of 1
setCookie("democount", '1');
//getting the value of 'democount' cookie and assigning it to a variable
var demoCookieCount = getCookie("democount");
$('#sample-button').click(function (e) {
e.preventDefault();
//increment the variable on every click
demoCookieCount++;
//set the incremented value of demoCookieCount variable to democount cookie
setCookie("democount",demoCookieCount);
// assigning the value of demoCookiecount to variable 123
var123 = getCookie("democount");
});