SprintBoot returning a PNG from a Controller's RequestMapping - rest

I've been scouring the internet for resources and I feel like I almost have the answer, but I can't quite seem to get a BufferedImage to be returned to a browser window.
The project generates a maze which can then create a BufferedImage.
Here is the code from my Controller.
#RequestMapping(method = RequestMethod.GET, path = "/image", params = {"rows", "columns"})
public ResponseEntity<byte[]> image(#RequestParam(name = "rows") int rows, #RequestParam(name = "columns") int columns) throws IOException, InterruptedException {
try {
BasicCartesianGrid requestedMaze = new BasicCartesianGrid(rows, columns);
requestedMaze.forEach(CellAlgorithms.BINARY_TREE);
BufferedImage bufferedImage = requestedMaze.toDisplayImage();
{ // Dumping to file for debugging <- this works as expected
File outputFile = new File("save.png");
ImageIO.write(bufferedImage, "png", outputFile);
}
ByteArrayOutputStream pngByteStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", pngByteStream);
byte[] pngBytes = pngByteStream.toByteArray();
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_PNG);
headers.setContentLength(pngBytes.length);
headers.setCacheControl(CacheControl.noCache().getHeaderValue());
return new ResponseEntity<>(pngBytes, headers, HttpStatus.OK);
} catch (Exception e) {
// This hasn't occurred yet, but is for just in case
Thread.sleep(1000);
System.err.println(e.getLocalizedMessage());
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<>(e.getLocalizedMessage().getBytes("ASCII"), headers, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
I have ascertained that the PNG is being generated correctly, as the file exists and is viewable on my hard-drive. My browser gets a broken image returned back. From my terminal, I can get some more information.
curl "http://localhost:8080/maze/image?rows=10&columns=10"
Dumps out the following (the quotation marks are part of the response, while the data represented by the ellipsis changes from request to request, due to the fact each maze is randomly generated and unique):
"iVBORw0KGgoAAAANSUhEUgAAA......"
I googled this string prefix, and found this page. Which shows that this string should be used as a data-uri, like so:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA…" >
I'm not sure where to go from here. It seems like my image is being generated correctly, but I must be missing a header in my response to tell the browser/spring that these bytes should be interpreted as an image and not as just a string.
UPDATE:
Based on the dialog between myself and Shawn Clark from the answer section, here is what I have presently.
#SpringBootApplication
#Log4j
public class SpringMazesApplication {
#Bean
public HttpMessageConverter<BufferedImage> bufferedImageHttpMessageConverter() {
log.debug("Registering BufferedImage converter");
return new BufferedImageHttpMessageConverter();
}
public static void main(String[] args) throws IOException {
SpringApplication.run(SpringMazesApplication.class, args);
}
}
And the actual controller:
#Controller
#RequestMapping(path = "/maze/basic", method = RequestMethod.GET)
#Log4j
public class BasicMazeController {
#RequestMapping(params = {"format", "format=text"}, produces = MediaType.TEXT_PLAIN_VALUE)
#ResponseBody
public String simpleMazeText(#RequestParam(name = "rows", defaultValue = "10", required = false) int rows,
#RequestParam(name = "columns", defaultValue = "10", required = false) int columns) throws IOException {
BasicCartesianGrid requestedMaze = new BasicCartesianGrid(rows, columns);
requestedMaze.forEach(CellAlgorithms.BINARY_TREE);
return requestedMaze.toDisplayString();
}
#RequestMapping(params = {"format=image"}, produces = MediaType.IMAGE_PNG_VALUE)
#ResponseBody
public BufferedImage simpleMazeImage(#RequestParam(name = "rows", defaultValue = "10", required = false) int rows,
#RequestParam(name = "columns", defaultValue = "10", required = false) int columns) throws IOException {
log.debug("Starting image generation");
BasicCartesianGrid requestedMaze = new BasicCartesianGrid(rows, columns);
requestedMaze.forEach(CellAlgorithms.BINARY_TREE);
BufferedImage bufferedImage = requestedMaze.toDisplayImage();
{ // Dumping to file for debugging <- this works as expected
log.debug("Dumping image to hd");
File outputFile = new File("save.png");
ImageIO.write(bufferedImage, "png", outputFile);
}
log.debug("Returning from image generation");
return bufferedImage;
}
#RequestMapping
#ResponseBody
public ResponseEntity<String> simpleMazeInvalid(#RequestParam(name = "rows", defaultValue = "10", required = false) int rows,
#RequestParam(name = "columns", defaultValue = "10", required = false) int columns,
#RequestParam(name = "format") String format) throws IOException {
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);
return new ResponseEntity<>("Invalid format: " + format, headers, HttpStatus.BAD_REQUEST);
}
}
From my terminal I can curl -D - "url" and I can see with both logging/debugging and the output from my terminal, that the converter is properly registered at the begging of the application and that I'm getting responses as you would expect from all but the actual image uri which returns a 406 Not Acceptable. If I remove the #ResponseBody from the image method, it just returns a 500. I can verify that the image is properly generated as it is being written to disk as I expect it should.

Check out the produces attribute on the #RequestMapping. You would want to set it to image/png.
Here is a complete example:
#RestController
public class ProduceImage {
#GetMapping(path = "/image", produces = "image/png")
public BufferedImage image() throws Exception {
BufferedImage bufferedImage = ImageIO.read(new File("E:\\Downloads\\skin_201305121633211421.png"));
return bufferedImage;
}
}
My BufferedImage is something from my computer but it can be just as easily the BufferedImage that you have from the requestedMaze.toDisplayImage() without having to do all that other work. To make this work you want to include the BufferedImageHttpMessageConverter in your context.
#Bean
public HttpMessageConverter<BufferedImage> bufferedImageHttpMessageConverter() {
return new BufferedImageHttpMessageConverter();
}

Related

Get Exception in thread "main" org.zaproxy.clientapi.core.ClientApiException: Does Not Exist on running form ans script authentication using zap api

public class FormAuth {
private static final String ZAP_ADDRESS = "localhost";
private static final int ZAP_PORT = 8080;
private static final String ZAP_API_KEY = null;
private static final String contextId = "1";
private static final String contextName = "Default Context";
private static final String target = "http://localhost:8090/bodgeit";
private static void setIncludeAndExcludeInContext(ClientApi clientApi) throws UnsupportedEncodingException, ClientApiException {
String includeInContext = "http://localhost:8090/bodgeit.*";
String excludeInContext = "http://localhost:8090/bodgeit/logout.jsp";
clientApi.context.includeInContext(contextName, includeInContext);
clientApi.context.excludeFromContext(contextName, excludeInContext);
}
private static void setLoggedInIndicator(ClientApi clientApi) throws UnsupportedEncodingException, ClientApiException {
// Prepare values to set, with the logged in indicator as a regex matching the logout link
String loggedInIndicator = "Logout";
// Actually set the logged in indicator
clientApi.authentication.setLoggedInIndicator(contextId, java.util.regex.Pattern.quote(loggedInIndicator));
// Check out the logged in indicator that is set
System.out.println("Configured logged in indicator regex: "
+ ((ApiResponseElement) clientApi.authentication.getLoggedInIndicator(contextId)).getValue());
}
private static void setFormBasedAuthenticationForBodgeit(ClientApi clientApi) throws ClientApiException,
UnsupportedEncodingException {
// Setup the authentication method
String loginUrl = "http://localhost:8090/bodgeit/login.jsp";
String loginRequestData = "username={%username%}&password={%password%}";
// Prepare the configuration in a format similar to how URL parameters are formed. This
// means that any value we add for the configuration values has to be URL encoded.
StringBuilder formBasedConfig = new StringBuilder();
formBasedConfig.append("loginUrl=").append(URLEncoder.encode(loginUrl, "UTF-8"));
formBasedConfig.append("&loginRequestData=").append(URLEncoder.encode(loginRequestData, "UTF-8"));
System.out.println("Setting form based authentication configuration as: "
+ formBasedConfig.toString());
clientApi.authentication.setAuthenticationMethod(contextId, "formBasedAuthentication",
formBasedConfig.toString());
// Check if everything is set up ok
System.out
.println("Authentication config: " + clientApi.authentication.getAuthenticationMethod(contextId).toString(0));
}
private static String setUserAuthConfigForBodgeit(ClientApi clientApi) throws ClientApiException, UnsupportedEncodingException {
// Prepare info
String user = "Test User";
String username = "test#example.com";
String password = "weakPassword";
// Make sure we have at least one user
String userId = extractUserId(clientApi.users.newUser(contextId, user));
// Prepare the configuration in a format similar to how URL parameters are formed. This
// means that any value we add for the configuration values has to be URL encoded.
StringBuilder userAuthConfig = new StringBuilder();
userAuthConfig.append("username=").append(URLEncoder.encode(username, "UTF-8"));
userAuthConfig.append("&password=").append(URLEncoder.encode(password, "UTF-8"));
System.out.println("Setting user authentication configuration as: " + userAuthConfig.toString());
clientApi.users.setAuthenticationCredentials(contextId, userId, userAuthConfig.toString());
clientApi.users.setUserEnabled(contextId, userId, "true");
clientApi.forcedUser.setForcedUser(contextId, userId);
clientApi.forcedUser.setForcedUserModeEnabled(true);
// Check if everything is set up ok
System.out.println("Authentication config: " + clientApi.users.getUserById(contextId, userId).toString(0));
return userId;
}
private static String extractUserId(ApiResponse response) {
return ((ApiResponseElement) response).getValue();
}
private static void scanAsUser(ClientApi clientApi, String userId) throws ClientApiException {
clientApi.spider.scanAsUser(contextId, userId, target, null, "true", null);
}
/**
* The main method.
*
* #param args the arguments
* #throws ClientApiException
* #throws UnsupportedEncodingException
*/
public static void main(String[] args) throws ClientApiException, UnsupportedEncodingException {
ClientApi clientApi = new ClientApi(ZAP_ADDRESS, ZAP_PORT, ZAP_API_KEY);
setIncludeAndExcludeInContext(clientApi);
setFormBasedAuthenticationForBodgeit(clientApi);
setLoggedInIndicator(clientApi);
String userId = setUserAuthConfigForBodgeit(clientApi);
scanAsUser(clientApi, userId);
}
}
=========================================================================================
/usr/lib/jvm/java-1.11.0-openjdk-amd64/bin/java -javaagent:/snap/intellij-idea-ultimate/319/lib/idea_rt.jar=43425:/snap/intellij-idea-ultimate/319/bin -Dfile.encoding=UTF-8 -classpath /home/arpit/IdeaProjects/maven-zap-demo/target/classes:/home/arpit/Downloads/zap-clientapi-1.9.0.jar ScriptAuth
Exception in thread "main" org.zaproxy.clientapi.core.ClientApiException: Does Not Exist
at org.zaproxy.clientapi.core.ApiResponseFactory.getResponse(ApiResponseFactory.java:50)
at org.zaproxy.clientapi.core.ClientApi.callApi(ClientApi.java:351)
at org.zaproxy.clientapi.gen.deprecated.ScriptDeprecated.load(ScriptDeprecated.java:146)
at ScriptAuth.uploadScript(ScriptAuth.java:76)
at ScriptAuth.main(ScriptAuth.java:93)
The recommended way to automate authentiation in ZAP is to configure and test it in the desktop, then export the context and import that via the API. If the authentication uses scripts then these will need to be registered with ZAP first.

Apache HttpClient - REST API: Issue in converting response to customized object which is put as SerializableEntity

I am using Apache HttpClient to put/get customized object using REST APIs. Below is the sample code. My putObject() method works fine and I could serialize Person object and put properly. However, while getting the object, I got below error:
Exception in thread "main" java.lang.ClassCastException: [B cannot be cast to Person at MyTest.demoGetRESTAPI(MyTest.java:88) at MyTest.main(MyTest.java:21)
Seems the code to build Person object out of response entity is not correct
HttpEntity httpEntity = response.getEntity();
byte[] resultByteArray = EntityUtils.toByteArray(httpEntity);
Person person = (Person)SerializationUtils.deserialize(resultByteArray);
Am I doing somthing wrong while getting byte[] array and converting to Person object. Please help me out to solve this issue.
Complete Example Program:
import java.io.Serializable;
import org.apache.commons.lang.SerializationUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.SerializableEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
public class MyTest {
public static void main(String[] args) throws Exception {
putObject();
getObject();
}
public static void putObject() throws Exception
{
HttpClient httpClient = new DefaultHttpClient();
Person person = new Person();
person.setName("Narendra");
person.setId("1");
try
{
//Define a postRequest request
HttpPut putRequest = new HttpPut("http://localhost:9084/ehcache-server/rest/screeningInstance/2221");
//Set the API media type in http content-type header
putRequest.addHeader("content-type", "application/x-java-serialized-object");
//Set the request put body
SerializableEntity personSEntity = new SerializableEntity(SerializationUtils.serialize(person));
putRequest.setEntity(personSEntity);
//Send the request; It will immediately return the response in HttpResponse object if any
HttpResponse response = httpClient.execute(putRequest);
//verify the valid error code first
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 201)
{
throw new RuntimeException("Failed with HTTP error code : " + statusCode);
}
}
finally
{
//Important: Close the connect
httpClient.getConnectionManager().shutdown();
}
}
public static void getObject() throws Exception
{
DefaultHttpClient httpClient = new DefaultHttpClient();
try
{
//Define a HttpGet request; You can choose between HttpPost, HttpDelete or HttpPut also.
//Choice depends on type of method you will be invoking.
HttpGet getRequest = new HttpGet("http://localhost:9084/ehcache-server/rest/screeningInstance/2221");
//Set the API media type in http accept header
getRequest.addHeader("accept", "application/x-java-serialized-object");
//Send the request; It will immediately return the response in HttpResponse object
HttpResponse response = httpClient.execute(getRequest);
//verify the valid error code first
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200)
{
throw new RuntimeException("Failed with HTTP error code : " + statusCode);
}
//Now pull back the response object
HttpEntity httpEntity = response.getEntity();
byte[] resultByteArray = EntityUtils.toByteArray(httpEntity);
Person person = (Person)SerializationUtils.deserialize(resultByteArray);
}
finally
{
//Important: Close the connect
httpClient.getConnectionManager().shutdown();
}
}
}
class Person implements Serializable{
String name;
String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return "Person [name=" + name + ", id=" + id + "]";
}
}
I got the solution. It was mistake in my code:
While putting object, I have written below code. That was doing two time serialization. First from Person object to byte[] and second from byte[] to byte[].
SerializableEntity personSEntity = new SerializableEntity(SerializationUtils.serialize(person));
putRequest.setEntity(personSEntity);
This is the right approach:
SerializableEntity personSEntity = new SerializableEntity(person);
putRequest.setEntity(personSEntity);
After getting binary from REST, code should be like below to get Object:
HttpEntity httpEntity = response.getEntity();
InputStream inputStream = null;
try {
inputStream = httpEntity.getContent();
Person p = (Person) SerializationUtils.deserialize(inputStream);
System.out.println("Person:" + p.getName());
}
finally {
inputStream.close();
}
This worked like CHARM !!

Sling Forward with SyntheticResource

I'm trying to build a Sling servlet that returns a modified value of a resource from the JCR. I dont want to change the original resource, so I create a SyntheticResource and make my manipulations. I then return it back using the RequestDispatcher.
The following code doesn't return the Modified content as expected and I don't see any errors in the log either. Can you tell me what I'm doing wrong here
#SlingServlet(methods = "GET", resourceTypes = "sling/components/test", selectors = "test")
public class TestServlet extends SlingSafeMethodsServlet {
/**
*
*/
private static final long serialVersionUID = 4078524820231933974L;
private final Logger log = LoggerFactory.getLogger(getClass());
#Reference
ResourceResolverFactory resolverFactory;
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
Map<String, Object> param = new HashMap<String, Object>();
ResourceResolver resolver = null;
response.setContentType("text/html");
StringWriterResponse writerResponse = new StringWriterResponse(response);
PrintWriter writer = response.getWriter();
try {
param.put(ResourceResolverFactory.SUBSERVICE, "testService");
final String path = request.getRequestPathInfo().getResourcePath();
resolver = resolverFactory.getServiceResourceResolver(param);
final Resource resource = resolver.getResource(path);
String resourceType = resource.getResourceType();
Resource testResource = new SyntheticResource(resolver,
path, resourceType) {
public <T> T adaptTo(Class<T> type) {
if (type == ValueMap.class) {
ModifiableValueMap map = resource
.adaptTo(ModifiableValueMap.class);
map.put("jcr:title", "Modified Title");
return (T)map;
}
return super.adaptTo(type);
}
};
RequestDispatcherOptions requestDispatcherOptions = new RequestDispatcherOptions();
requestDispatcherOptions.setReplaceSelectors("");
final RequestDispatcher requestDispatcher = request.getRequestDispatcher(testResource, requestDispatcherOptions);
requestDispatcher.forward(request, writerResponse);
// log.debug( writerResponse.getString() );
writer.println(writerResponse.getString());
response.setStatus(HttpServletResponse.SC_OK );
} catch (Exception e) {
log.error("Exception: ", e);
} finally {
if( resolver != null) {
resolver.close();
}
if( writer != null ){
writer.close();
}
if (writerResponse != null) {
writerResponse.clearWriter();
}
}
}
}
Using a ResourceDecorator would be simpler, it can return a ResourceWrapper that implements the required changes. Just be careful to keep the decorator's decorate method efficient when it's called for a Resource that it doesn't want to decorate, as it will be called for all Resources.

Game port to unity: Web posting

I am porting a game from Java Native to Unity. While the game is working correctly, I am having trouble posting the score using the same web services.
Java Code:
public static String gameConfigURL = "http://192.168.0.140/services/scoreupload.svc/json/GetGameConfigurationLite";
public static String scoreUploadURL = "http://192.168.0.140/services/scoreupload.svc/json/Upload";
public static final String MagicKey = "0GmWDa6j";
private static int timeoutConnection = 60000;
public static enum RequestSource
{
Unknown,
System,
Person;
}
public static Response sendRequestForResult(Request request, String Url,
Activity activity, Response response) throws JSONException,
ClientProtocolException, IOException,ConnectTimeoutException {
/** Code to create a JSON request from requestObject **/
JSONObject object = request.getJSON();
JSONObject requestObject = new JSONObject();
requestObject.put("request", object);
Log.v("","REQUEST:"+requestObject.toString());
/** Add code to create a HttpPostRequest **/
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(Url);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpResponse httpResponse = null;
String jsonValueString = null;
StringEntity se = null;
try {
se = new StringEntity(requestObject.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "text/json");
/**
* add code to attach the JSON object received from request to the
* HttpPostRequest Add Code to execute HttpRequest
**/
httpResponse = client.execute(httpPost);
/** Get string from the HttpRespnse **/
jsonValueString = EntityUtils.toString(httpResponse.getEntity());
Log.v("","RESPONSE:"+jsonValueString);
/** Create JSON object from incoming String **/
JSONObject repliedObject = new JSONObject(jsonValueString);
response.fromJSON(repliedObject);
return response;
How Do I convert this to unity C#.
So far I have this:
JSONObject j = new JSONObject ();
j.AddField ("Id", "1234567890");
j.AddField ("MagicKey", ApplicationServices.magicKey);
j.AddField ("RequestedBy", "09996f84-1a06-e211-a518-001aa020d699");
j.AddField ("Timestamp", "/Date(1547535370953)/");
j.AddField ("RequestSource", "Person");
j.AddField ("RequestedGameId", "375b43c0-91be-e011-a505-001aa020d699");
j.AddField ("RequestedPersonId", "09996f84-1a06-e211-a518-001aa020d699");
string json = j.ToString ();
Dictionary<string, string> header = new Dictionary<string, string>();
header.Add ("Accept", "application/json");
header.Add ("Content-Type", "text/json");
byte[] encode = Encoding.ASCII.GetBytes (json.ToCharArray ());
WWW getConfig = new WWW (ApplicationServices.gameConfigURL, encode, header);
yield return getConfig;
if (getConfig.error != null) {
Debug.Log (getConfig.error);
} else {
Debug.Log (getConfig.text);
}
This does not seem to work.
For "POST" you should use WWWForm instead of WWW.
Take a look here

Report opens Blank in ADF

I have report1.jrxml which have simple SQL query with no parameters and runs fine in iReport. I want to open this report through ADF.
my reportAction method is as follows:
public void reportAction(FacesContext ctx,OutputStream output) throws FileNotFoundException,NamingException,
SQLException, IOException, JRException,
ClassNotFoundException,
InstantiationException,
IllegalAccessException {
File input = null;
Connection conn = null;
Map reportParameters = new HashMap();
bindings = this.getBindings();
ctx = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)ctx.getExternalContext().getResponse();
String reportPath = ctx.getExternalContext().getInitParameter("reportpath");
input = new File(reportPath+"report1.jasper");
if(bindings!=null){
OperationBinding ob = bindings.getOperationBinding("getCurrentConnection");
ob.execute();
conn = (Connection)ob.getResult();
if(input.getPath()!=null&&reportParameters!=null&&conn!=null){
JasperPrint print = JasperFillManager.fillReport(input.getPath(),reportParameters,conn);
response.addHeader("Content-disposition", "attachment;filename=report1.pdf");
output = response.getOutputStream();
String userName = "ilpa";
File outPutPDF = new File("D:/jdev libs/reports/report1.pdf");
JasperExportManager.exportReportToPdfStream(print, output);
JasperExportManager.exportReportToPdfFile(print,outPutPDF.getPath());
JasperExportManager.exportReportToPdfStream(print, output);
output.flush();
output.close();
}
}
else{
ctx.addMessage(null,new FacesMessage("No bindings configured for this page"));
}
}
What could be wrong?
I have solved the issue myself.
The root cause was I was giving a wrong path in web.xml.
That is, I had report1.jrxml in two locations. The actual report I was using was in a different location.