unable to run test using mockmvc - mockmvc

I am trying to write unit test using mockmvc for my API, I was able to test it through postman but in the ide it is failing. I tried passing exact same headers and body but it says 401 unauthorized. Basically it is asking me to provide correct x-Auth token.
#Test
public void testMethod() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post(api/v1/test/user) .header("X-Auth-Token","actual_token").contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content("{\n" + ""key1": "value1",\n" + ""key2": "value2",\n" + ""key3": {\n" + ""key3.1":"value3.1",\n" + ""key3.2":"value3.2",\n" + ""key3.3":"value3.3",\n" + ""key3.4":"value3.4",\n" + ""key3.5":"value3.5"\n" + "}\n" + "}")) .andExpect(status().is(200));
}
public ObjectTest testMethod( #RequestBody ObjectTest objecttest, #RequestHeader(name = "X-Auth-Token") String xAuthToken ){ //my logic
}

Related

How to display error message in multi file uploading with Rest webservices

Hi am in way of uploading multiple files into aws bucket using spring mvc and rest web services.
The positive scenario is working like if I select more one file its saved in aws bucket and am getting 200 here
String json1 = handler.handleResponse(response1);
System.out.println(json1);
My question is I have selected three files called x ,y and z as usual way the first file gets saved into bucket due to some issue y and z files failed to save how to inform the user that y and z are not saved into bucket
#PostMapping("/upload")
public String handleFileUpload(#RequestParam("specifications") MultipartFile[] specifications,
HttpServletRequest request,HttpSession session,final RedirectAttributes redirectAttributes) throws Exception {
for (int i = 0; i < specifications.length; i++) {
MultipartFile file = specifications[i];
String path = "Specification/";
String bucketName="BUcket/";
String inJson = "{\"filename\":\"" + file.getOriginalFilename() + "\",\"bucketname\":\""+ bucketName + "\",\"path\":\""+ path + "\"}";
addLogo(file, inJson);
}
code upload file
public void addLogo(MultipartFile file ,String inJson) throws IOException
{
String message="";
byte[] bytes = file.getBytes();
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(fileUploadURL);
HttpEntity entity = MultipartEntityBuilder.create().addTextBody("json", inJson).addBinaryBody("file", bytes).build();
httppost.setEntity(entity);
HttpResponse response1 = httpclient.execute(httppost);
System.out.print(response1.getStatusLine());
ResponseHandler<String> handler = new BasicResponseHandler();
String json1 = handler.handleResponse(response1);
System.out.println(json1);
message = message + "You successfully uploaded " + file.getOriginalFilename() + "\n";
System.out.println(message);
}
by using ResponseEntity spring object, you can customize your returns based upload results. you catch IOEXception and create a specific return String,
I modified your method to be like this :
#PostMapping("/upload")
public ResponseEntity<?> handleFileUpload(#RequestParam("specifications")
MultipartFile[] specifications,
HttpServletRequest request,HttpSession session,final RedirectAttributes
redirectAttributes) throws Exception {
String failed_upload="";
for (int i = 0; i < specifications.length; i++) {
try{
MultipartFile file = specifications[i];
String path = "Specification/";
String bucketName="BUcket/";
String inJson = "{\"filename\":\"" + file.getOriginalFilename()
+ "\",\"bucketname\":\""+ bucketName + "\",\"path\":\""+ path + "\"}";
addLogo(file, inJson);
}catch(IOException){
failed_upload=failed_upload+specifications[i]+" ,";
}
} if(!failed_upload.equals("")){
return new ResponseEntity<>("Files"+failed_upload+" not uploaded",
HttpStatus.INTERNAL_SERVER_ERROR);
}else{
return new ResponseEntity<>("Everything is ok", HttpStatus.OK);
}

How to print some logs "before" a spring-data repository method, without custom repo

I have a Spring data repository.
When http://localhost:8080/persons webservice is called, I want to log something. I DO NOT want to make MyCustomRepository<>. Cleaner options?
Repo class:
#RepositoryRestResource(collectionResourceRel = "persons", path = "persons")
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {
List<Person> findByLastName(#Param("name") String name);
Sample log:
log.error("AccessToken: " + securityContext.getTokenString());
log.error("User: {} / {}", accessToken.getPreferredUsername(), accessToken.getName());
log.error("Principal: {}", principal.getName());
You can create an aspect to intercept calls to your PersonRepository. From there you can access OAuth2 access token and the security context to retrieve the principal. Here is an example,
#Component
#Aspect
#Log
public class SecurityAspect {
#Autowired
private OAuth2ClientContext oauth2ClientContext;
#Pointcut("execution(public * my.example.repository.PersonRepository.*(..))")
public void pointcut() {
}
#Around("pointcut()")
public Object advice(ProceedingJoinPoint pjp) throws Throwable {
log.info(
"Entering SecurityAspect.advice() in class "
+ pjp.getSignature().getDeclaringTypeName()
+ " - method: " + pjp.getSignature().getName());
OAuth2AccessToken accessToken = oauth2ClientContext.getAccessToken();
log.info("AccessToken: " + accessToken);
if (SecurityContextHolder.getContext().getAuthentication()
instanceof OAuth2Authentication) {
OAuth2Authentication authentication =
(OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
if (authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken userToken =
(UsernamePasswordAuthenticationToken) authentication.getUserAuthentication();
log.info("Principal id: " + userToken.getPrincipal());
if (userToken.getDetails() instanceof Map) {
Map details = (Map) userToken.getDetails();
log.info("Principal Name: " + details.get("name"));
}
}
}
return pjp.proceed();
}
}

How to restrict to a list of query params for a REST api

I want to restrict to a set of query params for rest Method.
#Path("/users")
public class UserService {
#GET
#Path("/query")
public Response getUsers(
#QueryParam("from") int from,
#QueryParam("to") int to,
#QueryParam("orderBy") List<String> orderBy) {
return Response
.status(200)
.entity("getUsers is called, from : " + from + ", to : " + to
+ ", orderBy" + orderBy.toString()).build();
}
}
“users/query?from=100&to=200&orderBy=age&orderBy=name” [WORKS]
“users/query?x=y” [also works and when my query params are set with default values]
i want throw some exceptions based on that.

Use Google volley api to send HTTP POST request of RDF data

So, I have recently integrated the Volley API in my app in order to provide a Cloud storage solution (REST). Since, i have never used the API before i have some trouble trying to send RDF (text/turtle) data via HTTP POST. The REST server is working perfectly since I send GET and POST requests (via the Postman Chrome app) and every time i receive 200 and 201 responses. Although i managed to send a simple GET request via the API, i get a 400 error when i send an HTTP POST.
The code is the following:
//the RDF turtle payload to send over HTTP POST
final String bodyPost = "#prefix : <http://xxx.xxx.xxx.gr/xxx/schema/xxx#> ." + "\n" +
"#prefix xsd: <http://www.w3.org/2001/XMLSchema#> ." + "\n" +
"[a :Patient ;" + "\n" +
":lastName "+'"'+"Aylakiotis"+'"'+"^^xsd:string ; " + "\n" +
":firstName "+'"'+"Yiannis"+'"'+"^^xsd:string ;" + "\n" +
":dateOfBirth "+'"'+"1970-04-14"+'"'+"^^xsd:date ;" + "\n" +
":amka "+'"'+"12345678903"+'"'+"^^xsd:string ;" + "\n" +
":gender :Male ;" + "\n" +
"] .";
RequestQueue queue = Volley.newRequestQueue(this);
final String URL ="http://xxx.xxx.xxx:8080/xxx/";
EditText folderTitle = (EditText) findViewById(R.id.folderTitle);
StringRequest strReq = new StringRequest(Request.Method.POST, URL,
new Response.Listener() {
#Override
public void onResponse(Object response) {
folderTitle.setText("Response is: " + response.toString().substring(0,500));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
folderTitle.setText("Error: " + error.getMessage());
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
System.out.println("string post data: " + bodyPost);
if (params != null && params.size() > 0) {
System.out.println("string post data: " + bodyPost);
return encodeParameters(params, getParamsEncoding());
}
return bodyPost.getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
String creds = String.format("%s:%s", "xxx", "xxx");
String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT);
headers.put("Authorization", auth);
headers.put("Content-Type", "text/turtle");
return headers;
}
};
// Add the request to the RequestQueue.
queue.add(strReq);
String bodyPost is the data payload i want to send in a turtle RDF format. I am putting this in my getBody() method, however i still get a 400 bad request. I have already sent this String via POST http through the Postman Chrome app and it works (201 Created). I saw that most implementations had getParams() but this requires key/value pairs whereas i am using triples that i want to send as a whole string of raw data
Set your Content-type to text/turtle. Override your request header like this:
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
final HashMap<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "text/turtle");
return params;
}

Display List of 15 Facebook Friends with Name and Profile Picture in JSP

Got a tiny JSP problem. Am new to the whole bit, so please be lenient with me :)
I intend to draw a table with 2 columns: One for facebook friends profiles pictures and the other for facebook friends names.
I've checked a few references on this forum, but they didn't seem to work out.
Here goes the basic code structure:
/*
* #(#)Friends.java 1.0
*
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.Parameter;
import com.restfb.exception.FacebookException;
/**
* Facebook Application Friends Servlet
*
* #version 3.0
*/
public class Friends extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final int MAX_FRIENDS = 15;
#Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
// set MIME type and encoding
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
// get writer for output
final PrintWriter p = response.getWriter();
// make sure that we have obtained an access token, otherwise redirect
// to login
final String accessToken = request.getParameter("access_token");
if (accessToken == null) {
response.sendRedirect(Config.getValue("LOGIN_URL"));
return;
}
// get client
final DefaultFacebookClient client = new DefaultFacebookClient(accessToken);
// retrieve the document with all friend user ids
try {
final Connection<UserWithPicture> friends = client.fetchConnection("me/friends",
UserWithPicture.class, Parameter.with("fields", "name, picture"),
Parameter.with("limit", Friends.MAX_FRIENDS));
p.println( /** Here goes the code for table display **/);
} catch (final FacebookException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
p.flush();
p.close();
}
#Override
public void doPost(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
Now, I've written the following code and it's not working for whatever freaky reason there might be. Here it goes:
p.println("<table>" +
"<c:forEach>" +
"<tr>" +
"<td>" + friends.getPicture()
"</td>" +
"<td>" + friends.name
"</td>" +
"</tr>" +
"</c:forEach>" +
"</table>");
Where the getPicture() method is implemented in the UserWithPicture.java Class:
import com.restfb.Facebook;
import com.restfb.types.User;
/**
* Model class for a User with picture
* #version 1.0
*/
public class UserWithPicture extends User {
#Facebook
private String picture;
public String getPicture() {
return this.picture;
}
}
Does anyone see the problem with this code?
Here,
p.println("<table>" +
"<c:forEach>" +
"<tr>" +
"<td>" + friends.getPicture()
"</td>" +
"<td>" + friends.name
"</td>" +
"</tr>" +
"</c:forEach>" +
"</table>");
you're making a conceptual mistake. You're sending <c:forEach> tag plain to the browser. The browser only understands HTML. The browser doesn't understand Java/JSP/JSTL/whatever-server-side tags. When doing this inside a servlet (not recommended), then you need to fix it as follows:
p.println("<table>");
for (Friend friend : friends) {
p.println("<tr><td>" + friend.getPicture() + "</td><td>" + friend.getName() + "</td></tr>");
}
p.println("</table>");
Or when doing this inside a JSP, then just write down those tags plain instead of fiddling with scriptlets.
<table>
<c:forEach items="${friends}" var="friend">
<tr><td>${friend.picture}</td><td>${friend.name}</td></tr>
</c:forEach>
</table>
Here is axactly what you are looking for.
http://www.bitspedia.com/2012/01/how-to-get-facebook-friends-list-in.html
The article explains how you can fetch Facebook Friends using java API (RestFB). A sample project is also attached which demonstrate it.