ServletRequestListener - Getting the userprincipal returns null - java-ee-6

I'm having a web-application that is secured with HTTP-Basic auth.
I also implemented a filter using the ServletRequestListener interface. Now when the filter calls the requestInitialized method, the getUserPrincipal-Method of the request returns null. But when I check the request headers, the authorization-header is set with the encrypted value. Here's the code:
#Override
public void requestInitialized(ServletRequestEvent e) {
HttpServletRequest request = (HttpServletRequest) e.getServletRequest();
//p is null
Principal p = request.getUserPrincipal();
Enumeration<String> enH = request.getHeaders("Authorization");
while (enH.hasMoreElements()) {
String s = enH.nextElement();
System.out.println(s);
//prints.
//Basic c3RhY2tvdmVyZmxvdzpteXBhc3N3b3Jk
}
}
Why is the userprincipal not initialized?

You are likely not setting up the needed security layers for embedded-jetty.
Here's an example found in the Jetty embedded examples source tree.
package org.eclipse.jetty.embedded;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.security.Constraint;
public class SecuredHelloHandler
{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
Set<String> knownRoles = new HashSet<String>();
knownRoles.add("user");
knownRoles.add("admin");
security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);
// Your Handler (or Servlet) that should be secured
HelloHandler hh = new HelloHandler();
security.setHandler(hh);
server.start();
server.join();
}
}

I solved it by using a Filter instead of a Listener..
#WebFilter(urlPatterns = { "/*" })
public class RequestFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain fChain) throws IOException, ServletException {
HttpServletRequest hReq = (HttpServletRequest) req;
//p is not null anymore
Principal p = hReq.getUserPrincipal();
fChain.doFilter(hReq, res);
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig config) throws ServletException {
}
}

Related

how to verify http connection pool can improve performance

I want to use http connection pool with Spring RestTemplate, but before using it, I need to verify whether it can improve performance.
I do a little programing here:
#Configuration
public class RestTemplateConfig {
#Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
and test code here
#SpringBootTest
class RestnopoolApplicationTests {
String url = "https://www.baidu.com/";
// String url = "http://localhost:8080/actuator/";
#Autowired
RestTemplate restTemplate;
#Test
void contextLoads() {
}
#Test
void verify_health() {
Instant start = Instant.now();
for(int i=0; i < 100; i ++) {
restTemplate.getForObject(url, String.class);
}
Instant end = Instant.now();
Duration d = Duration.between(start,end );
System.out.println("time span " + d.getSeconds());
}
Also, I write http connection pool below
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
/**
* - Supports both HTTP and HTTPS
* - Uses a connection pool to re-use connections and save overhead of creating connections.
* - Has a custom connection keep-alive strategy (to apply a default keep-alive if one isn't specified)
* - Starts an idle connection monitor to continuously clean up stale connections.
*/
#Configuration
#EnableScheduling
public class HttpClientConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientConfig.class);
// Determines the timeout in milliseconds until a connection is established.
private static final int CONNECT_TIMEOUT = 30000;
// The timeout when requesting a connection from the connection manager.
private static final int REQUEST_TIMEOUT = 30000;
// The timeout for waiting for data
private static final int SOCKET_TIMEOUT = 60000;
private static final int MAX_TOTAL_CONNECTIONS = 50;
private static final int DEFAULT_KEEP_ALIVE_TIME_MILLIS = 20 * 1000;
private static final int CLOSE_IDLE_CONNECTION_WAIT_TIME_SECS = 30;
#Bean
public PoolingHttpClientConnectionManager poolingConnectionManager() {
SSLContextBuilder builder = new SSLContextBuilder();
try {
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
} catch (NoSuchAlgorithmException | KeyStoreException e) {
LOGGER.error("Pooling Connection Manager Initialisation failure because of " + e.getMessage(), e);
}
SSLConnectionSocketFactory sslsf = null;
try {
sslsf = new SSLConnectionSocketFactory(builder.build());
} catch (KeyManagementException | NoSuchAlgorithmException e) {
LOGGER.error("Pooling Connection Manager Initialisation failure because of " + e.getMessage(), e);
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory>create().register("https", sslsf)
.register("http", new PlainConnectionSocketFactory())
.build();
PoolingHttpClientConnectionManager poolingConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
poolingConnectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS);
return poolingConnectionManager;
}
#Bean
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
return new ConnectionKeepAliveStrategy() {
#Override
public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
HeaderElementIterator it = new BasicHeaderElementIterator
(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
String param = he.getName();
String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
return Long.parseLong(value) * 1000;
}
}
return DEFAULT_KEEP_ALIVE_TIME_MILLIS;
}
};
}
#Bean
public CloseableHttpClient httpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(REQUEST_TIMEOUT)
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT).build();
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setConnectionManager(poolingConnectionManager())
.setKeepAliveStrategy(connectionKeepAliveStrategy())
.build();
}
#Bean
public Runnable idleConnectionMonitor(final PoolingHttpClientConnectionManager connectionManager) {
return new Runnable() {
#Override
#Scheduled(fixedDelay = 10000)
public void run() {
try {
if (connectionManager != null) {
LOGGER.trace("run IdleConnectionMonitor - Closing expired and idle connections...");
connectionManager.closeExpiredConnections();
connectionManager.closeIdleConnections(CLOSE_IDLE_CONNECTION_WAIT_TIME_SECS, TimeUnit.SECONDS);
} else {
LOGGER.trace("run IdleConnectionMonitor - Http Client Connection manager is not initialised");
}
} catch (Exception e) {
LOGGER.error("run IdleConnectionMonitor - Exception occurred. msg={}, e={}", e.getMessage(), e);
}
}
};
}
}
and RestTemplateConfig below
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.client.RestTemplate;
import org.apache.http.impl.client.CloseableHttpClient;
#Configuration
public class RestTemplateConfig {
#Autowired
CloseableHttpClient httpClient;
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate(clientHttpRequestFactory());
return restTemplate;
}
#Bean
public HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory();
clientHttpRequestFactory.setHttpClient(httpClient);
return clientHttpRequestFactory;
}
#Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setThreadNamePrefix("poolScheduler");
scheduler.setPoolSize(50);
return scheduler;
}
}
The test result cannot prove that connection pool impvoe performance.
You have not used your new implementation. You are still using the default Apache client. Use your method httpClient() to get the ClosableHttpClient.
Please also note that your test is synchronous, no matter how many connections do you have in the pool, you will use it sequential. Use threads to execute the get request.

Apache Storm Problem: "Unable to canonicalize address localhost/<unresolved>:2000 because it's not resolvable"

When I launch a simple Strorm script on IntellijIdea or Eclipse i encounter this problem: "Unable to canonicalize address localhost/:2000 because it's not resolvable".
import org.apache.storm.*;
import org.apache.storm.generated.*;
import org.apache.storm.spout.SpoutOutputCollector;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.topology.base.BaseRichSpout;
import org.apache.storm.tuple.*;
import org.apache.storm.utils.Utils;
import java.util.Map;
import java.util.Random;
public class ExclamationExample {
public static class TestWordSpout extends BaseRichSpout {
private SpoutOutputCollector _collector;
#Override
public void open(Map map, TopologyContext topologyContext, SpoutOutputCollector spoutOutputCollector) {
_collector = spoutOutputCollector;
}
#Override
public void nextTuple() {
Utils.sleep(100);
final String[] words = new String[]{"nathan", "mike", "jackson", "golda", "bertels"};
final Random rand = new Random();
final String word = words[rand.nextInt(words.length)];
_collector.emit(new Values(word));
System.out.printf("Word spout: %s\n", word);
}
#Override
public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
outputFieldsDeclarer.declare(new Fields("word"));
}
}
public static class ExclamationBolt extends BaseRichBolt {
private OutputCollector collector;
#Override
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
#Override
public void execute(Tuple tuple) {
String val = tuple.getString(0) + "!!!";
collector.emit(tuple, new Values(val));
System.out.printf("Exclamation bolt: %s\n", val);
collector.ack(tuple);
}
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
}
//TOPOLOGY
public static void main(String[] args) throws Exception {
Config conf = new Config();
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout("word", new TestWordSpout(), 2);
builder.setBolt("exclaim1", new ExclamationBolt(), 2).shuffleGrouping("word");
builder.setBolt("exclaim2", new ExclamationBolt(), 2).shuffleGrouping("exclaim1");
conf.setDebug(false);
String topologyName = "test";
conf.setNumWorkers(2);
//If there are arguments, we are running on a cluster
if (args != null && args.length > 0) {
conf.setNumWorkers(3);
topologyName = args[0];
StormSubmitter.submitTopology(topologyName, conf, builder.createTopology());
}
try (LocalCluster cluster = new LocalCluster()) {
cluster.submitTopology(topologyName, conf, builder.createTopology());
Utils.sleep(600000); // wait [param] ms
cluster.killTopology(topologyName);
cluster.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}
What is a possible solution?
I resolved my problem. If can help someone i tell the solution. I ran the Java Application using Java SDK 17, this give me problem, then I created new project with JDK 1.8 and everything works!

Vertx JWKS/JWT verification throws a 500 with no errors logged

I have a very basic Vertx demo I'm trying to create that fetches a JWK from an endpoint and creates an RSAPublicKey for verifying a JWT signature:
package example;
import com.auth0.jwk.JwkException;
import com.auth0.jwk.JwkProvider;
import com.auth0.jwt.interfaces.DecodedJWT;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;
import com.auth0.jwk.UrlJwkProvider;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.interfaces.RSAPublicKey;
import com.auth0.jwt.interfaces.RSAKeyProvider;
import java.security.interfaces.RSAPrivateKey;
public class MainVerticle extends AbstractVerticle {
#Override
public void start(Promise<Void> startPromise) throws Exception {
HttpServer server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route().handler(routingContext -> {
String authHeader = routingContext.request().getHeader("Authorization");
// pull token from header
String token = authHeader.split(" ")[1];
URL jwksEndpoint = null;
try {
jwksEndpoint = new URL("http://localhost:1080/jwks");
} catch (MalformedURLException e) {
e.printStackTrace();
}
JwkProvider jwkProvider = new UrlJwkProvider(jwksEndpoint);
RSAKeyProvider keyProvider = new RSAKeyProvider() {
#Override
public RSAPublicKey getPublicKeyById(String kid) {
//Received 'kid' value might be null if it wasn't defined in the Token's header
RSAPublicKey publicKey = null;
try {
publicKey = (RSAPublicKey) jwkProvider.get(kid).getPublicKey();
} catch (JwkException e) {
e.printStackTrace();
}
return publicKey;
}
#Override
public RSAPrivateKey getPrivateKey() {
return null;
}
#Override
public String getPrivateKeyId() {
return null;
}
};
Algorithm algorithm = Algorithm.RSA256(keyProvider);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build();
DecodedJWT jwt = verifier.verify(token);
System.out.println(jwt);
routingContext.next();
});
router.route("/hello").handler(ctx -> {
ctx.response()
.putHeader("content-type", "text/html")
.end("<h1>Hello from non-clustered messenger example!</h1>");
});
server.requestHandler(router).listen(8888, http -> {
if(http.succeeded()) {
startPromise.complete();
System.out.println("HTTP server started on port 8888");
} else {
startPromise.fail(http.cause());
}
});
}
}
The problem is that when I make request to the /hello endpoint, the application immediately returns a 500. But nothing appears in the logs (even at debug level).
I've tried manually specifying the kid property to rule out the jwkProvider not returning properly
I'm at a loss at how to gain any more insight into what is failing.
Turns out to completely be my oversight. Wrapping that verifier.verify() call in a try/catch showed me that I was expecting an issuer. This is the same problem I was having while trying to achieve this in Quarkus! I was able to remove that from the builder and now this works perfectly.

ClassCastException When Trying to Make JAXRS Call in Errai 4

I am using Errai 4.0.0.Beta1, and I am trying to make a simple JAX RS call.
Here is the code I am using:
final RemoteCallback<List<Company>> remoteCallback = new RemoteCallback<List<Company>>() {
#Override
public void callback(List<Company> companies) {
Window.alert("rpcServiceCaller - Callback");
Window.alert("Number of companies returned: " + companies.size());
}
};
final RestErrorCallback errorCallback = new RestErrorCallback() {
#Override
public boolean error(Request message, Throwable throwable) {
Window.alert(throwable.getMessage());
logger.error(throwable.getMessage(), throwable);
return false;
}
};
RestClient.create(ErraiJAXRSService.class,
remoteCallback,
errorCallback,
200).getCompaniesJSON();
I am seeing the following exception in Super Dev Mode:
Error caused by: ClassCastException: undefined
at f9b_g$ [as collect_0_g$] (StackTraceCreator.java:198)
at H8b_g$ (StackTraceCreator.java:343)
at Iz_g$ [as fillInStackTrace_0_g$] (Throwable.java:114)
at Bz_g$ (Throwable.java:53)
at Xz_g$ (Exception.java:25)
at cA_g$ (RuntimeException.java:25)
at Ymb_g$ (ClassCastException.java:23)
at Mzg_g$ (InternalPreconditions.java:45)
at Xzg_g$ (InternalPreconditions.java:33)
at n1d_g$ (Cast.java:75)
at rrh_g$ (RestClient.java:192)
at srh_g$ (RestClient.java:158)
at wrh_g$ (RestClient.java:113)
at ynf_g$ [as erraiJSON_0_g$] (JAXRSPage.java:94)
at gKh_g$ [as onClick_0_g$] (Type_factory__c_i_e_c_j_JAXRSPage__quals__j_e_i_Any_j_e_i_Default.java:76)
at Exd_g$ [as dispatch_4_g$] (ClickEvent.java:56)
at Fxd_g$ [as dispatch_1_g$] (ClickEvent.java:55)
at Awd_g$ [as dispatch_0_g$] (GwtEvent.java:76)
at ZGd_g$ (EventBus.java:40)
at iHd_g$ [as doFire_0_g$] (SimpleEventBus.java:193)
at oHd_g$ [as fireEvent_2_g$] (SimpleEventBus.java:88)
at RGd_g$ [as fireEvent_1_g$] (HandlerManager.java:127)
at Lve_g$ [as fireEvent_1_g$] (Widget.java:129)
at Lwd_g$ (DomEvent.java:125)
at Tve_g$ [as onBrowserEvent_0_g$] (Widget.java:177)
at gne_g$ (DOM.java:1480)
at fne_g$ (DOM.java:1419)
at HTMLButtonElement.xte_g$ (DOMImplStandard.java:317)
at k6b_g$ (Impl.java:233)
at n6b_g$ (Impl.java:285)
at HTMLButtonElement.<anonymous> (Impl.java:71)
The proxy is returned, but any line that attempts to cast it to an AbstractJaxrsProxy fails with the above exception.
The JaxrsProxyLoaderImpl.java has been created, and my JAX RS Service is there:
package org.jboss.errai.enterprise.client.jaxrs;
import com.google.gwt.http.client.RequestBuilder;
import com.insclix.erraiPOC.shared.domain.Company;
import com.insclix.erraiPOC.shared.service.jaxrs.ErraiJAXRSService;
import java.util.List;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jboss.errai.common.client.framework.ProxyProvider;
import org.jboss.errai.common.client.framework.RemoteServiceProxyFactory;
import org.jboss.errai.security.client.local.interceptors.SecurityExceptionMapper;
public class JaxrsProxyLoaderImpl implements JaxrsProxyLoader { public void loadProxies() {
class com_insclix_erraiPOC_shared_service_jaxrs_ErraiJAXRSServiceImpl extends AbstractJaxrsProxy implements ErraiJAXRSService {
private RemoteCallback remoteCallback;
private ErrorCallback errorCallback;
public com_insclix_erraiPOC_shared_service_jaxrs_ErraiJAXRSServiceImpl() {
setExceptionMapper(new SecurityExceptionMapper());
}
public RemoteCallback getRemoteCallback() {
return remoteCallback;
}
public void setRemoteCallback(RemoteCallback callback) {
remoteCallback = callback;
}
public ErrorCallback getErrorCallback() {
return errorCallback;
}
public void setErrorCallback(ErrorCallback callback) {
errorCallback = callback;
}
public List getCompaniesJSON() {
StringBuilder url = new StringBuilder(getBaseUrl());
url.append("company/jaxrs");
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url.toString());
requestBuilder.setHeader("Accept", "application/json");
sendRequest(requestBuilder, null, new ResponseDemarshallingCallback() {
public Object demarshallResponse(String response) {
return MarshallingWrapper.fromJSON(response, List.class, Company.class);
}
});
return null;
}
public List getCompaniesXML() {
StringBuilder url = new StringBuilder(getBaseUrl());
url.append("company/jaxrs");
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url.toString());
requestBuilder.setHeader("Accept", "application/xml");
sendRequest(requestBuilder, null, new ResponseDemarshallingCallback() {
public Object demarshallResponse(String response) {
return MarshallingWrapper.fromJSON(response, List.class, Company.class);
}
});
return null;
}
public Long createCompanyJSON(final Company a0) {
StringBuilder url = new StringBuilder(getBaseUrl());
url.append("company/jaxrs");
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url.toString());
requestBuilder.setHeader("Content-Type", "application/json");
sendRequest(requestBuilder, MarshallingWrapper.toJSON(a0), new ResponseDemarshallingCallback() {
public Object demarshallResponse(String response) {
return MarshallingWrapper.fromJSON(response, Long.class, null);
}
});
return 0L;
}
public Long createCompanyXML(final Company a0) {
StringBuilder url = new StringBuilder(getBaseUrl());
url.append("company/jaxrs");
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url.toString());
requestBuilder.setHeader("Content-Type", "application/xml");
sendRequest(requestBuilder, MarshallingWrapper.toJSON(a0), new ResponseDemarshallingCallback() {
public Object demarshallResponse(String response) {
return MarshallingWrapper.fromJSON(response, Long.class, null);
}
});
return 0L;
}
}
RemoteServiceProxyFactory.addRemoteProxy(ErraiJAXRSService.class, new ProxyProvider() {
public Object getProxy() {
return new com_insclix_erraiPOC_shared_service_jaxrs_ErraiJAXRSServiceImpl();
}
});
}
}
This turned out to be an issue with the way JAX-RS / Errai class and interface were configured. According to the JAX-RS specification, the #Path annotation needs to be on the implementation, but Errai needs it on the interface.
So, the solution was to have the #Path annotation on BOTH the interface (for Errai), and the class that implements it (for JAX-RS).
Note that if the annotation is on the interface, Wildfly allows for this, Jersey ignores the interface, and Resteasy fails (if running through the ResteasyServletInitializer.

Californium Framework CoAP and PUT request

I am trying to do a request to coap server (er-rest-example) using Californium.
I succesfully do a POST request.
But with PUT I am getting a BAD REQUEST, I try using this URLs in url:
coap://[aaaa::c30c:0000:0000:0002]:5683/actuators/leds
coap://[aaaa::c30c:0000:0000:0002]:5683/actuators/leds?
coap://[aaaa::c30c:0000:0000:0002]:5683/actuators/leds?color=r
But with no one get success.
What I am doing wrong?.
This is my simple script:
package coap_client;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.californium.core.CoapClient;
import org.eclipse.californium.core.CoapResponse;
import org.eclipse.californium.core.coap.MediaTypeRegistry;
public class cliente {
public static void main(String[] args) throws Exception {
Timer timer;
timer = new Timer();
TimerTask task = new TimerTask(){
#Override
public void run(){
String url="coap://[aaaa::c30c:0000:0000:0002]:5683/actuators/leds";
URI uri= null;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
}
CoapClient client = new CoapClient(uri);
CoapResponse response = client.put("color=r",MediaTypeRegistry.TEXT_PLAIN);
System.out.println(response.isSuccess());
if (response!=null) {
byte[] myreponse=response.getPayload();
String respuesta2 = new String(myreponse);
System.out.println(respuesta2);
}
}
};
timer.schedule(task, 10,10*1000);
}
}
In Contiki er-rest-example, see the POST/PUT handler(1) for the LED CoAP resource. It expects a mode param without which you will get a BAD_REQUEST as response. I assume that has to go in the request body.