I am using java.net.CookieManager & java.net.CookieHandler to track cookies. I need to remove one but keep all others. The problem is that the List return from the using cookieManger.getCookieStore().getCookies() is unmodifiable and therefore throws an exception when I attempt to remove the cookie.
Here is the code regarding cookies:
public HttpProxy(String host, String port) {
cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
//other irrelevant code
}
private CookieManager cookieManager;
public void deleteGameCookie() {
CookieStore cookieStore = cookieManager.getCookieStore();
List<HttpCookie> cookieList = cookieStore.getCookies();
HttpCookie temp = null;
// iterate HttpCookie object
for (HttpCookie cookie : cookieList) {
try {
String name = URLDecoder.decode(cookie.getName().replace("+", "%2B"), "UTF-8").replace("%2B", "+");
if(name.equals("catan.game")) {
System.out.println("catan.game cookie found");
temp = cookie;
}
} catch (UnsupportedEncodingException e) {
//System.out.println("Error decoding cookie... bummer...");
e.printStackTrace();
}
}
cookieList.remove(temp);
}
Is there a way around this or a better way to do this?
I found a similar question about unmodifiable collections here but it hasn't been answered. Thanks for your help!
you probably want to use one of the remove methods on cookie store not try and work with the list directly. see:
http://docs.oracle.com/javase/7/docs/api/java/net/CookieStore.html
Here is a code that should do the trick:
public void deleteGameCookie() {
CookieStore cookieStore = cookieManager.getCookieStore();
List<HttpCookie> cookiesToRemove = new ArrayList<>();
for (HttpCookie cookie : cookieStore.getCookies()) {
try {
String name = URLDecoder.decode(cookie.getName().replace("+", "%2B"), "UTF-8").replace("%2B", "+");
if (name.equals("catan.game")) {
cookiesToRemove.add(cookie);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
for (HttpCookie cookie : cookiesToRemove) {
cookieStore.remove(null, cookie);
}
}
The code should also handle situation where no cookie was found and when there is more than one cookie matching your criteria.
Related
I am new to OpenTelemetry word. I have created spans for my services separately, but when i am try to combine spans of two different services, using context propogation, I am not able to do it successfully.
I have used following code:
// at client side:
public static void sendContext(String resource) {
TextMapSetter<HttpURLConnection> setter =
new TextMapSetter<HttpURLConnection>() {
#Override
public void set(HttpURLConnection carrier, String key, String value) {
carrier.setRequestProperty(key, value);
}
};
HttpURLConnection transportLayer = null;
String urlString = "http://127.0.0.1:8080" + resource;
try {
URL url = new URL(urlString);
transportLayer = (HttpURLConnection) url.openConnection();
} catch (MalformedURLException ex) {
System.out.println(ex.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
GlobalOpenTelemetry.getPropagators()
.getTextMapPropagator()
.inject(Context.current(), transportLayer, setter);
}
// at server side:
public static Context getContext(HttpServletRequest request) {
TextMapGetter<HttpServletRequest> getter =
new TextMapGetter<HttpServletRequest>() {
#Override
public String get(HttpServletRequest carrier, String key) {
Enumeration<String> headerNames = carrier.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
System.out.println("headerNames.nextElement(): " + headerName);
if (headerName.equals(key)) {
String headerValue = request.getHeader(headerName);
System.out.println("headerValue): " + headerValue);
return headerValue;
}
}
}
return null;
}
#Override
public Iterable<String> keys(HttpServletRequest carrier) {
Set<String> set = new HashSet<String>();
Enumeration<String> headerNames = carrier.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
set.add(headerNames.nextElement());
}
}
return set;
}
};
Context extractedContext =
GlobalOpenTelemetry.getPropagators()
.getTextMapPropagator()
.extract(Context.current(), request, getter);
At server, i am not able to get parent span.
Kindly help on this.
You can refer to OpenTelemetry main documentation from here. It contains the context propagation part but I used HttpHeader type getter as the TextMapGetter with the same functionality which shows in the doc and instead of using
Scope scope = extractedContext.makeCurrent()
as the scope to create a child span, better to use directly without the scope,
tracer.spanBuilder(spanName).setParent(extractedContext)
Because sometimes the automated way to propagate the parent span on the current thread does not work fine.
I am trying to do a simple script that will convert any possible HTML link into HTTP URL, such as
http://example.com //example.com /index.html ./index.html index.html
I already tried function that I found in another answer:
public static Integer isAbsoluteURL (String url) throws java.net.MalformedURLException {
final URL baseHTTP = new URL("http://example.com");
final URL baseFILE = new URL("file:///");
if (url.length() > 0) {
if (url.substring(0, 1) == "/") {
return 0;
}
}
URL frelative;
URL hrelative;
try {
frelative = new URL(baseFILE, url);
hrelative = new URL(baseHTTP, url);
} catch (MalformedURLException e) {
System.out.println("MalformedURLException found");
return 3;
}
if (frelative.equals(hrelative)) {
return 0;
} else {
return 1;
}
}
I want to get absolute links, but the code don't work for ./, //(without http[s]).
Thanks.
I'd prefer to use spring's UriComponentBuilder which will take care about everything:
https://www.baeldung.com/spring-uricomponentsbuilder
I used android.webkit.CookieManager.
I want to get all data about cookie.
But I got only cookie's name and value.
How do I get expires or other data.
Especially, I need expires of cookies.
Thank you.
Here is My Code
public void updateCookie(String url) {
String allCookie = null;
String[] cookies = null;
String cookieNameTmp = null;
String cookieContetTmp = null;
cookieNames.clear();
cookieValue.clear();
if(!m_adapter.isEmpty()) {
m_adapter.clear();
}
try {
allCookie = CookieManager.getInstance().getCookie(url);
if(allCookie != null) {
allCookie = allCookie.replace(" ", "");
cookies = allCookie.split(";");
for (String cookie : cookies) {
cookieNameTmp = cookie.split("=")[0];
m_adapter.add(cookieNameTmp);
cookieContetTmp = cookie.replace(cookieNameTmp+"=", "");
cookieNames.add(cookieNameTmp);
cookieValue.add(cookieContetTmp);
}
}
} catch (Exception e) {
Log.d("updateCookie: ", e.toString());
}
}
In my current spring-boot project, I add this class with the goal to allow me store and retrieve cookies:
public class CookieAcessor {
public static List<HttpCookie> getCookies() {
try {
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
URL url = new URL("http://localhost:8080");
List <HttpCookie> cookies = cookieJar.get(url.toURI());
return cookies;
} catch(Exception e) {
return new ArrayList<HttpCookie>();
}
}
public static String getCookie(String key) {
List<HttpCookie> cookies = getCookies();
for(HttpCookie cookie : cookies) {
if(cookie.getName().equals(key))
return cookie.getValue();
}
return null;
}
public static void setCookie(String key, String value) {
try {
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
HttpCookie cookie = new HttpCookie(key, value);
URL url = new URL("http://localhost:8080");
cookieJar.add(url.toURI(), cookie);
} catch(Exception e) {
System.out.println("Erro ao armazenar o cookie!");
}
}
}
but when I try execute any methods from this class (for read or save a cookie), nothing is done. Anyone can see what's wrong with this code? It was based on this article from official documentation: http://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html.
UPDATE
this class is used in a method from controller like this:
#RequestMapping(value = "/")
public String index() {
CookieAcessor.setCookie("teste", "...");
System.out.println("cookie[teste] = "+CookieAcessor.getCookie("teste"));
return "public/index";
}
Hi I want to know how I can use Optional in java SE 8 in the function below.
public URL getAuthenticatedURL() throws MalformedURLException {
if (log != null){
log.writeINFOToLog("Fetching authentication URL...");
}
else{
Log.initLog();
log.writeINFOToLog("Fetching authentication URL...");
}
try{
String url = String.format("%s://%s%s?username=%s&password=%s",getProtocol(), getHost(), getPath(), getUsername(), getPassword());
URL returnURL = new URL(url);
return returnURL;
}
catch (MalformedURLException ex){
log.writeExceptionToLog(ex);
return null;
}
}
I want to be able to handle the scenario where values involved in constructing the URL is null or empty.
After some research, I think its best that I avoid nulls, since it does not make much sense to have a null.
Here is my code snippet of the same function once I have used Optional<URL>
public Optional<URL> getAuthenticatedURL() throws MalformedURLException {
if (log != null){
log.writeINFOToLog("Fetching authentication URL...");
}
else{
Log.initLog();
log.writeINFOToLog("Fetching authentication URL...");
}
String url = String.format("%s://%s%s?username=%s&password=%s",getProtocol(), getHost(), getPath(), getUsername(), getPassword());
return Optional.ofNullable(new URL(url));
}
So when I call the function the code will be something like this.
if(getAuthenticatedURL.isPresent()){
URL val = getAuthenticatedURL.get();
}
I think it is more reasonable to use Supplier than Optional, because getAuthenticatedURL() has no argument and generates an Object(URL).
It looks like:
Supplier<URL> supplier = () -> {
...
try {
return new URL(...);
} catch (MalformedURLException e) {
return null;
}
};
URL url = supplier.get();