Why does MSAL4J call ends with Error 404 ResourceNotFound? - java

I'm using msl4j to interact with microsoft products, e.g. emails, calendars. When I call the user informations (without parameters) this will works fine. But, when I try to read messages from the inbox, the call ended with error 404 ("code":"ResourceNotFound","message":"Resource could not be discovered."). I don't know why. The API Permissions seems correct.
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.DeviceCode;
import com.microsoft.aad.msal4j.DeviceCodeFlowParameters;
import com.microsoft.aad.msal4j.IAccount;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.IClientCredential;
import com.microsoft.aad.msal4j.MsalException;
import com.microsoft.aad.msal4j.OnBehalfOfParameters;
import com.microsoft.aad.msal4j.PublicClientApplication;
import com.microsoft.aad.msal4j.SilentParameters;
import com.microsoft.aad.msal4j.UserAssertion;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class AppMSAL4J {
private static String userId;
private static String authority;
private static String clientId;
private static String clientSecret;
private static String tenantId;
private static Set<String> scopes;
public static void main(String args[]) throws Exception {
setUpSampleData();
try {
IAuthenticationResult result = acquireToken();
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
String bodyString = "";
RequestBody body = RequestBody.create(bodyString, mediaType);
String baseUrl = "https://graph.microsoft.com/v1.0/users/" + userId;
String parameters = "";
// parameters = "/mailfolders('Inbox')/messages";
// parameters = "/messages";
Request request = new Request.Builder()
.url(baseUrl + parameters)
.method("GET", null)
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer " + result.accessToken())
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static IAuthenticationResult acquireToken() throws Exception {
IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
ConfidentialClientApplication cca = ConfidentialClientApplication
.builder(clientId, credential)
.authority(authority)
.build();
ClientCredentialParameters parameters = ClientCredentialParameters
.builder(scopes)
.build();
return cca.acquireToken(parameters).join();
}
private static void setUpSampleData() {
userId = "b0f***";
tenantId = "fc2***";
authority = "https://login.microsoftonline.com/" + tenantId;
clientId = "b1a***";
clientSecret = "KJ***";
scopes = Collections.singleton("https://graph.microsoft.com/.default");
}
}

Related

Push data from Dynamo DB to elasticsearch using java

Hi i have created a handler in java for getting the events from dynamo DB
Here is my code
package com.Lambda.dynamodb;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
public class DDBEventProcessor implements
RequestHandler<DynamodbEvent, String> {
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()){
System.out.println(record.getEventID());
System.out.println(record.getEventName());
System.out.println(record.getDynamodb().toString());
}
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
}
}
Lambda function able to write the events in cloudwatch but the challenge is i have to index all the streamed records to the AWS elasticsearch service endpoint and index it.
while search through blogs i got few code samples in python and node.js but my requirement is i have to build this lambda function in java
Could anyone please suggest how to achieve this in java lambda function?
Hi i have included the code below may helpful to some one. Dynamo DB streams to index the document in elasticsearch both inside AWS and outside AWS
package com.Firstlambda;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.auth.AWS4Signer;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.ItemUtils;
import com.amazonaws.services.dynamodbv2.model.AttributeValue;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent;
import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HelloWorld implements RequestHandler<DynamodbEvent, String> {
private static String serviceName = "es";
private static String region = "us-east-1";
private static String aesEndpoint = ""
private static String index = "";
private static String type = "_doc";
static final AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
public String handleRequest(DynamodbEvent ddbEvent, Context context) {
for (DynamodbStreamRecord record : ddbEvent.getRecords()) {
System.out.println("EventName : " + record.getEventName());
System.out.println("EventName : " + record.getDynamodb());
//AWS outside
RestHighLevelClient esClient = esClient();
//AWS outside
//AWS Inside
//RestHighLevelClient esClient = esClient(serviceName, region);
//AWS Inside
if (record.getEventName().toLowerCase().equals("insert")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
IndexRequest indexRequest = new IndexRequest(index, type, JsonUniqueId);
indexRequest.source(JsonString, XContentType.JSON);
try {
IndexResponse indexResponse = esClient.index(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else if (record.getEventName().toLowerCase().equals("modify")) {
String JsonString = getJsonstring(record.getDynamodb().getNewImage());
String JsonUniqueId = GetIdfromJsonString(JsonString);
UpdateRequest request = new UpdateRequest(index, type, JsonUniqueId);
String jsonString = JsonString;
request.doc(jsonString, XContentType.JSON);
try {
UpdateResponse updateResponse = esClient.update(
request, RequestOptions.DEFAULT);
System.out.println(updateResponse.toString());
return "Successfully processed " + ddbEvent.getRecords().size() + " records.";
} catch (IOException e) {
System.out.println(e.getMessage());
}
} else {
System.out.println("remove");
System.out.println("KEYID : " + record.getDynamodb().getKeys().get("ID").getN());
String deletedId = record.getDynamodb().getKeys().get("ID").getN();
DeleteRequest request = new DeleteRequest(index, type, deletedId);
try {
DeleteResponse deleteResponse = esClient.delete(
request, RequestOptions.DEFAULT);
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
return "Successfullyprocessed";
}
public String getJsonstring(Map<String, AttributeValue> newIma) {
String json = null;
Map<String, AttributeValue> newImage = newIma;
List<Map<String, AttributeValue>> listOfMaps = new ArrayList<Map<String, AttributeValue>>();
listOfMaps.add(newImage);
List<Item> itemList = ItemUtils.toItemList(listOfMaps);
for (Item item : itemList) {
json = item.toJSON();
}
return json;
}
public String GetIdfromJsonString(String Json) {
JSONObject jsonObj = new JSONObject(Json);
return String.valueOf(jsonObj.getInt("ID"));
}
// Adds the interceptor to the ES REST client
// public static RestHighLevelClient esClient(String serviceName, String region) {
// AWS4Signer signer = new AWS4Signer();
// signer.setServiceName(serviceName);
// signer.setRegionName(region);
// HttpRequestInterceptor interceptor = new AWSRequestSigningApacheInterceptor(serviceName, signer, credentialsProvider);
// return new RestHighLevelClient(RestClient.builder(HttpHost.create(aesEndpoint)).setHttpClientConfigCallback(hacb -> hacb.addInterceptorLast(interceptor)));
// }
public static RestHighLevelClient esClient() {
String host = "d9bc7cbca5ec49ea96a6ea683f70caca.eastus2.azure.elastic-cloud.com";
int port = 9200;
String userName = "elastic";
String password = "L4Nfnle3wxLmV95lffwsf$Ub46hp";
String protocol = "https";
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol))
.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
This is just a sample code has to be modified based on our requirements

Java - JWT Token Invalid Signature

I have a problem getting my JWT Token verified, despite it giving me the correct payload.
Excuse me if I'm a little insecure in this part of the code, since this was handed out by our teacher via a template, but we are unable to reach him.
We had to make some changes to the code itself, since it had the username put into the token and we want the email put in.
We are using something called UserPrincipal, what I can understand, its used to determine access rights to a file or object and originally we used roles to determine what users had access to which endpoints. This is not the case in this project, since its a short demo based on other features.
How does our user principal class look like?
package rest;
import entity.User;
import java.security.Principal;
public class UserPrincipal implements Principal {
private String name;
private String email;
public UserPrincipal(User user) {
this.email = user.getEmail();
}
public UserPrincipal(String email) {
super();
this.email = email;
}
#Override
public String getName() {
return email;
}
}
See, here the user principal used to also get a list of roles and instead of a email, it got a username.
Where do we use this user principal? Well, we use it when we generate our token. This is also here we have our endpoint, yes it should be moved to our interface class.
package rest;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import entity.User;
import facade.UserFacade;
import exceptions.AuthenticationException;
import exceptions.GenericExceptionMapper;
import utils.PuSelector;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
#Path("login")
public class LoginEndpoint {
private static final int TOKEN_EXPIRE_TIME = 1000 * 60 * 30; // ms * sec * min = 30 min
private static final UserFacade USER_FACADE = UserFacade.getInstance(PuSelector.getEntityManagerFactory("pu"));
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response login(String jsonString) throws AuthenticationException {
JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
String email = json.get("email").getAsString();
String password = json.get("password").getAsString();
String ip = json.get("ip").getAsString();
try {
User user = USER_FACADE.getVeryfiedUser(email, password, ip);
String code = USER_FACADE.sendCode(email);
String token = createToken(email);
JsonObject responseJson = new JsonObject();
responseJson.addProperty("code", code);
responseJson.addProperty("email", email);
responseJson.addProperty("token", token);
return Response.ok(new Gson().toJson(responseJson)).build();
} catch (JOSEException | AuthenticationException ex) {
if (ex instanceof AuthenticationException) {
throw (AuthenticationException) ex;
}
Logger.getLogger(GenericExceptionMapper.class.getName()).log(Level.SEVERE, null, ex);
}
throw new AuthenticationException("Somthing went wrong! Please try again");
}
private String createToken(String email) throws JOSEException {
//String firstNameLetter = user.getFirstName().substring(0, 1);
//String lastNameLetter = user.getLastName().substring(0, 1);
//int ageTimesID = user.getAge() * user.getId();
//String name = firstNameLetter + lastNameLetter + ageTimesID;
String issuer = "the_turtle_troopers";
JWSSigner signer = new MACSigner(SharedSecret.getSharedKey());
Date date = new Date();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject(email)
.claim("email", email)
.claim("allowed", true)
.claim("issuer", issuer)
.issueTime(date)
.expirationTime(new Date(date.getTime() + TOKEN_EXPIRE_TIME))
.build();
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
signedJWT.sign(signer);
return signedJWT.serialize();
}
}
We have a security context class.. Not quite sure if this has any impact on my problem, but regardless:
package rest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.SecurityContext;
import java.security.Principal;
public class JWTSecurityContext implements SecurityContext {
UserPrincipal user;
ContainerRequestContext request;
public JWTSecurityContext(UserPrincipal user, ContainerRequestContext request) {
this.user = user;
this.request = request;
}
#Override
public boolean isUserInRole(String role) {
return true;
}
#Override
public boolean isSecure() {
return request.getUriInfo().getBaseUri().getScheme().equals("https");
}
#Override
public Principal getUserPrincipal() {
return user;
}
#Override
public String getAuthenticationScheme() {
return "JWT"; //Only for INFO
}
}
And finally we have our JWTAuthenticationFilter:
package rest;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
import exceptions.AuthenticationException;
import javax.annotation.Priority;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
#Provider
#Priority(Priorities.AUTHENTICATION)
public class JWTAuthenticationFilter implements ContainerRequestFilter {
private static final List<Class<? extends Annotation>> securityAnnotations
= Arrays.asList(DenyAll.class, PermitAll.class, RolesAllowed.class);
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext request) throws IOException {
if (isSecuredResource()) {
String token = request.getHeaderString("x-access-token");//
if (token == null) {
request.abortWith(exceptions.GenericExceptionMapper.makeErrRes(token, 403));
return;
}
try {
UserPrincipal user = getUserPrincipalFromTokenIfValid(token);
//What if the client had logged out????
request.setSecurityContext(new JWTSecurityContext(user, request));
} catch (AuthenticationException | ParseException | JOSEException ex) {
Logger.getLogger(JWTAuthenticationFilter.class.getName()).log(Level.SEVERE, null, ex);
request.abortWith(exceptions.GenericExceptionMapper.makeErrRes("Token not valid (timed out?)", 403));
}
}
}
private boolean isSecuredResource() {
for (Class<? extends Annotation> securityClass : securityAnnotations) {
if (resourceInfo.getResourceMethod().isAnnotationPresent(securityClass)) {
return true;
}
}
for (Class<? extends Annotation> securityClass : securityAnnotations) {
if (resourceInfo.getResourceClass().isAnnotationPresent(securityClass)) {
return true;
}
}
return false;
}
private UserPrincipal getUserPrincipalFromTokenIfValid(String token) throws ParseException, JOSEException, AuthenticationException {
SignedJWT signedJWT = SignedJWT.parse(token);
//Is it a valid token (generated with our shared key)
JWSVerifier verifier = new MACVerifier(SharedSecret.getSharedKey());
if (signedJWT.verify(verifier)) {
if (new Date().getTime() > signedJWT.getJWTClaimsSet().getExpirationTime().getTime()) {
throw new AuthenticationException("Your Token is no longer valid");
}
String email = signedJWT.getJWTClaimsSet().getClaim("email").toString();
return new UserPrincipal(email);
} else {
throw new JOSEException("User could not be extracted from token");
}
}
}
Hope someone will be able to tell me why it is my token isn't getting validated on jwt.io

Scheduled task through annotations in servlet is not working

I have a server that handles requests, and with regular intervals (every 1-2 minutes) needs to call another server and update a list of objects that is used to create the response to the request. Inspired by for example the accepted answer for this question, I tried to use the Schedule annotation, but can't get it to work.
How to run a background task in a servlet based web application?
A simplified view of the server is:
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "MyServer", urlPatterns = {"/data/*", "/scheduled/*"}, loadOnStartup = 1)
public class MyServlet extends HttpServlet {
private static final String UTF_8 = "UTF-8";
private static final String APPLICATION_JSON = "application/json";
private static final long serialVersionUID = 1L;
private static connector connector;
public MyServlet() {
super();
}
public void destroy() {}
#Override
public void init() throws ServletException {
connector = new connector();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path = request.getServletPath();
String pathInfo = request.getPathInfo().substring(1);
response.setContentType(APPLICATION_JSON);
response.setCharacterEncoding(UTF_8);
if (path.endsWith("/data")) {
List<DataItem> dataItems = connector.currentData;
response.getWriter().write(JsonUtility.convertToJsonString(dataItems));
} else if (path.endsWith("/scheduled")) {
connector.fetchData();
response.getWriter().write("Done");
} else {
response.getWriter()
.write(pathInfo + " Is not Found but not returning 404");
return;
}
}
}
The connector class that is supposed to update the stored data from the other server at regular intervals is:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Schedule;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
#Startup
#Singleton
public class Connector {
public List<DataItem> currentData = new LinkedList<>();
#Lock(LockType.READ)
#Schedule(second = "*", minute = "*/2", hour = "*", persistent = false)
public void fetchNews() {
logger.debug("Fetching data");
String response = sendGet(url, bearerToken);
JsonObject json = new Gson().fromJson(response, JsonObject.class);
//Transform the response to a list of DataItems.
List<DataItem> retrievedData = toDataList(json)
System.out.println(retrievedData);
synchronized(currentData) {
currentData = retrievedData;
}
}
private String sendGet(String path, String authorizationProperty) {
URL url;
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization", authorizationProperty);
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
String output;
StringBuffer response = new StringBuffer();
while ((output = in.readLine()) != null) {
response.append(output);
}
in.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
However, the method fetchData is not firing every second minute as I was expecting. I don't know what I am missing. I have played around a bit with adding/removing the #Startup annotation, creating an instance of the class in the init() method on the server, but still have no result.

Error jersey Rest client using sparql queries

I am trying to execute sparql queries from jersey client but the problem that the execution returns 200 status and the result is null.But , when I execute the same query on POSTMAN the status is 200 but the result is not null.
the the code for java client :
package org.jaba.messenger.messenger.client;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;
import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.w3c.dom.Document;
public class restapiClient {
public static void main(String args[])
{
Client client=ClientBuilder.newClient();
//sb simple query
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("admin", "123123");
client.register(feature);
String query=new String("SELECT * WHERE { ?a ?b ?c }") ;
URLCodec uc = new URLCodec();
String sparqlQueryUri = null;
try
{
sparqlQueryUri=uc.encode(query);
System.out.println("SimpleJerseyClient(): uri = " + sparqlQueryUri);
}catch (EncoderException e)
{
System.err.println(e.toString());
e.printStackTrace();
}
WebTarget target=client.target("http://localhost:8080/qodisco/api/sync-search")
.queryParam("query",sparqlQueryUri);
Invocation.Builder invocationBuilder =target.request();
Response response = invocationBuilder.get();
;
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
}
}
that is the code of the API that I am connecting to it:
package br.ufrn.dimap.consiste.qodisco.api;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import br.ufrn.dimap.consiste.qodisco.model.entities.Domain;
import br.ufrn.dimap.consiste.qodisco.model.entities.User;
import br.ufrn.dimap.consiste.qodisco.model.enums.TopicType;
import br.ufrn.dimap.consiste.qodisco.services.APIService;
import br.ufrn.dimap.consiste.qodisco.services.FusekiService;
#RestController
#RequestMapping("/api")
public class QoDiscoAPI {
#Autowired
private APIService apiService;
#Autowired
private FusekiService fusekiService;
#RequestMapping(value="/user", method=RequestMethod.POST)
public ResponseEntity<String> addUser(#RequestBody User user){
if(!apiService.addUser(user)){
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
return new ResponseEntity<String>(HttpStatus.CREATED);
}
#RequestMapping(value="/sync-search", method=RequestMethod.GET, produces="text/json")
//#RequestParam("domain") String domain,
public String syncSearch( #RequestParam("query") String query){
return apiService.searchByQuery("Pollution", query);
}
#RequestMapping(value="/async-search", method=RequestMethod.GET, produces="text/json")
public #ResponseBody String asyncSearch(#RequestParam("query") String query, #RequestParam("domain") String domain, #RequestParam("type") int type){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss.SSS");
Date date = new Date();
String topicName = "qodisco"+auth.getName()+dateFormat.format(date);
TopicType topicType;
switch(type){
case 1:
topicType = TopicType.TIPO1;
break;
case 2:
topicType = TopicType.TIPO2;
break;
case 3:
topicType = TopicType.TIPO3;
break;
default:
topicType = null;
break;
}
if(topicType!=null){
fusekiService.asyncSearch(query, topicName, domain, topicType);
return topicName;
} else{
return null;
}
}
#RequestMapping(value="/resource", method=RequestMethod.POST)
public ResponseEntity<String> addResource(#RequestParam("domain") String domain,
#RequestParam("data") String data){
apiService.createOrUpdateResource(domain, data);
return new ResponseEntity<String>(HttpStatus.CREATED);
}
#RequestMapping(value="/resource", method=RequestMethod.PUT)
public ResponseEntity<String> updateResource(#RequestParam("domain") String domain,
#RequestParam("data") String data){
apiService.createOrUpdateResource(domain, data);
return new ResponseEntity<String>(HttpStatus.OK);
}
#RequestMapping(value="/resource", method=RequestMethod.DELETE)
public ResponseEntity<String> removeResource(#RequestParam("domain") String domain,
#RequestParam("data") String data){
apiService.createOrUpdateResource(domain, data);
return new ResponseEntity<String>(HttpStatus.OK);
}
#RequestMapping(value="/repository", method=RequestMethod.POST)
public ResponseEntity<String> addRepository(#RequestParam("domains") List<String> domainNames,
#RequestParam("url") String repositoryUrl, #RequestParam("operations") List<String> operations){
if(apiService.addRepository(domainNames, repositoryUrl, operations)){
return new ResponseEntity<String>(HttpStatus.OK);
} else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
#RequestMapping(value="/repository", method=RequestMethod.DELETE)
public ResponseEntity<String> removeRepository(#RequestParam("url") String url){
if(apiService.removeRepository(url)){
return new ResponseEntity<String>(HttpStatus.OK);
} else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
#RequestMapping(value="/rdo", method=RequestMethod.GET, produces="text/json")
public List<Domain> getRdos(HttpServletResponse response){
return apiService.getDomains();
}
#RequestMapping(value="/rdo", method=RequestMethod.POST)
public ResponseEntity<String> addRdo(#RequestBody Domain domain){
System.out.println(domain);
if(apiService.addRdo(domain)){
return new ResponseEntity<String>(HttpStatus.OK);
}else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
#RequestMapping(value="/rdo", method=RequestMethod.DELETE)
public ResponseEntity<String> removeRdo(#RequestParam("name") String name){
if(apiService.removeDomain(name)){
return new ResponseEntity<String>(HttpStatus.OK);
} else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
#RequestMapping(value="/rdo", method=RequestMethod.PUT)
public ResponseEntity<String> updateRdo(#RequestBody Domain domain){
if(apiService.addRdo(domain)){
return new ResponseEntity<String>(HttpStatus.OK);
}else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
}
that is the result of running the client :
SimpleJerseyClient(): uri = SELECT+*+WHERE+%7B+%3Fa+%3Fb++%7D
200
org.glassfish.jersey.client.internal.HttpUrlConnector$2#cd3fee8
null
Thanks
This could be caused by a parsing error on the side of the endpoint. I've found that Fuseki (is that your underlying triple store?) requires spaces to be encoded as %20 rather than +. However, I managed to run + encoded queries from the browser just fine. Perhaps replacing + with %20 in the encoded query string will resolve the issue. Otherwise, hope someone finds this useful.
sparqlQueryUri = uc.encode(query).replaceAll("\\+", "%20");

How to get HttpOnly cookie using jsoup

package com.company;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.net.*;
import java.util.Map;
public class Parser {
private String viewState;
private String eventValidation;
Map<String, String> cookies;
public void login() throws IOException {
String url = "http://www.aogc2.state.ar.us:8080/DWClient/";
CookieHandler.setDefault(new CookieManager());
Connection connection = Jsoup.connect(url + "Login.aspx");
updateViewState(connection);
try {
Connection.Response res = connection
.data("DWC$DWMessages", "")
.data("__VIEWSTATE", viewState)
.data("__EVENTVALIDATION", eventValidation)
.data("DWC_NotificationToolTip_ClientState", "")
.data("LoginWebPart$LoginTypes", "Guest")
.data("LoginWebPart$TextBoxUserName", "")
.data("LoginWebPart$TextBoxPassword", "")
.data("LoginWebPart$ButtonLogin", "Login")
.data("LoginWebPart_LanguageContextMenu_ClientState","")
.method(Connection.Method.POST)
.execute();
cookies = connection.request().cookies();
System.out.println(cookies);
} catch (IOException ex) {
ex.printStackTrace();
System.exit(1);
}
}
}
This is the printed cookie list
{AspxAutoDetectCookieSupport=1, 11f5b7bb-885f-4c81-808d-7d5ae64248f1=DWSessionLoginID=6251bf1c-010f-4219-9a2f-5846d8f77907}
This is described as an httpOnly cookie. How can I get it?

Categories

Resources