Report opens Blank in ADF - jasper-reports

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.

Related

World map not dispalyed in crystal reports

I'm generating a pdf report using crystal report, I would like to use Data Map Tool
In c# code I've a dataset containing geographicals fields and some values to display in the map.
public class CrystalReportViewerPlugIn : ICrystalReportViewer
{
private ReportDocument _reportDocument;
private CrystalReportViewer _crystalReportViewer;
public void Init(string fileName, DataSet dataSet)
{
_reportDocument = new ReportDocument();
_reportDocument.Load(fileName);
_reportDocument.SetDataSource(dataSet);
_crystalReportViewer = new CrystalReportViewer();
_crystalReportViewer.DisplayToolbar = false;
_crystalReportViewer.DisplayGroupTree = false;
_crystalReportViewer.PageToTreeRatio = 4;
_crystalReportViewer.RefreshReport();
_crystalReportViewer.ReportSource = _reportDocument;
}
}
Then I export the result into a strem:
public MemoryStream GetCrystalReportResults(string rptFileName, DataSet ds)
{
var crystalReportViewer = new CrystalReportViewerPlugIn();
crystalReportViewer.PlugIn.Init(rptFileName, ds);
crystalReportViewer.PlugIn.Control.Visible = true;
var oStream = crystalReportViewer.PlugIn.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
var byteArray = new byte[oStream.Length];
oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
return new MemoryStream(byteArray);
}
The stream is exported as pdf:
protected virtual IHttpActionResult FinalizeExport(MemoryStream data, string name)
{
string contentType = "application/octet-stream";
name = name.GetCleanFileName();
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(data);
response.Content.Headers.Remove("content-type");
response.Content.Headers.Add("content-type", contentType);
response.Content.Headers.Remove("x-filename");
response.Content.Headers.Add("x-filename", name);
response.Content.Headers.Add("Content-Disposition", "inline; filename=\"" + name + "\"");
response.Content.Headers.Add("Content-Length", data.Length.ToString());
return ResponseMessage(response);
}
The world map is not displayed, do you have anny idea about this issue ?
Crystal report's map works only in 32 bits environment.

Java - Bing Spatial Data Services : <title>Object moved to....</title>

I'm trying to use Bing Spatial Data Service of Microsoft by using Java from my server. (I used this code : How to send HTTP request in java?) but it doesnt work at all.
What I want to do: get latitude and longitude from a given adress
public static void main(String[] args) throws IOException {
System.out.println(SendRequete());
}
static String SendRequete(){
String bingMapsKey = "zzzzzzzzzz";
String contentType="text/plain";
String targetURL = "http://dev.virtualearth.net/";
String urlParameters="REST/v1/Locations?countryRegion=France&locality=Paris&postalCode=75001&addressLine=rue%20de%20la%20paix&key=" + bingMapsKey;
System.out.println(targetURL+urlParameters);
try{
HttpURLConnection connection = null;
URL url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Content-Length",
Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoOutput(true);
//request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
I keep having the same results:
<html><head><title>Object moved</title></head><body>
<h2>Object moved to here.</h2>
</body></html>
</body></html>ed to here.</h2>
ml><head><title>Object moved</title></head><body>
If I copy and paste on y browser it works fine... Any idea of where the problem is
Looks like you are using the Bing Maps REST services not the Bing Spatial Data Services. The REST services can geocode individual locations on demand, while the Spatial Data Services can geocode up to 200,000 locations in a single request.
Assuming you mean the REST services, yes, the URL you are creating is correct. However you are passing in part of the URL as URL parameters when you shouldn't be. Also, you need to make a GET request, not a POST request. Here is a modified version of your code that should work.
static String SendRequete(){
String bingMapsKey = "zzzzzzzzzz";
String contentType="text/plain";
String targetURL = "http://dev.virtualearth.net/";
String urlParameters="REST/v1/Locations?countryRegion=France&locality=Paris&postalCode=75001&addressLine=rue%20de%20la%20paix&key=" + bingMapsKey;
System.out.println(targetURL+urlParameters);
try{
URL url = new URL(targetURL + urlParameters);
URLConnection connection = url.openConnection();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

SprintBoot returning a PNG from a Controller's RequestMapping

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();
}

Blackberry HttpConnection and query string

I've been having some trouble connecting to a uri when I append a query string... I always get back 400 http code... however when I try the browser, same url, everything goes smooth...
This is what I have:
String query = "q=hello";
byte[] queryBytes = query.getBytes();
Somewhere in my code I open an HttpConnection using the queryBytes like this:
String uri = "https://www.google.co.ve/search" + "?" + new String(queryBytes);
HttpConnection request = (HttpConnection) Connector.open(uri);
request.getResponseCode();
If I don't use bytes for my connection everyting works fine:
String uri = "https://www.google.co.ve/search?q=hello";
Thanks in advance
When i try this, iam getting http code 200.
try {
String httpURL = "https://www.google.co.ve/search?q=hello";
HttpConnection httpConn;
httpConn = (HttpConnection) Connector.open(httpURL);
httpConn.setRequestMethod(HttpConnection.GET);
DataOutputStream _outStream = new DataOutputStream(httpConn.openDataOutputStream());
byte[] request_body = httpURL.getBytes();
for (int i = 0; i < request_body.length; i++) {
_outStream.writeByte(request_body[i]);
}
DataInputStream _inputStream = new DataInputStream(
httpConn.openInputStream());
StringBuffer _responseMessage = new StringBuffer();
int ch;
while ((ch = _inputStream.read()) != -1) {
_responseMessage.append((char) ch);
}
String res = (_responseMessage.toString());
String responce = res.trim();
httpConn.close();
Dialog.alert(responce);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Send a file from server to client in GWT

I am using GWT.
I have to download a file file from server to client.
Document is in the external repository.
Client sends the id of the document through a Servlet.
On server side: Using this ID document is retrieved:
Document document = (Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
ByteArrayInputStream inputStream = (ByteArrayInputStream) contentStream.getStream();
int c;
while ((c = inputStream.read()) != -1) {
System.out.print((char) c);
}
String mime = contentStream.getMimeType();
String name = contentStream.getFileName();
InputStream strm = contentStream.getStream();
Here I can read the document.
I want to send this to the client.
How do I make this a file and send it back to the client?
In Your Servlet:
Document document =(Document)session.getObject(docId);
ContentStream contentStream = document.getContentStream();
String name = contentStream.getFileName();
response.setHeader("Content-Type", "application/octet-stream;");
response.setHeader("Content-Disposition", "attachment;filename=\"" + name + "\"");
OutputStream os = response.getOutputStream();
InputStream is =
(ByteArrayInputStream) contentStream.getStream();
BufferedInputStream buf = new BufferedInputStream(is);
int readBytes=0;
while((readBytes=buf.read())!=-1) {
os.write(readBytes);
}
os.flush();
os.close();// *important*
return;
You can create a standard servlet (which extends HttpServlet and not RemoteServiceServlet) on server side and opportunity to submit the id as servlet parameter on client side.
Now you need after getting request create the excel file and send it to the client. Browser shows automatically popup with download dialog box.
But you should make sure that you set the right content-type response headers. This header will instruct the browser which type of file is it.
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fileId = reguest.getParameter("fileId"); // value of file id from request
File file = CreatorExel.getFile(fileId); // your method to create file from helper class
// setting response headers
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", file.length());
response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\"");
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
InputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream();
input = new BufferedInputStream(fileInput);
output = new BufferedOutputStream(outputStream);
int count;
byte[] buffer = new byte[8192]; // buffer size is 512*16
while ((count = input.read(buffer)) > 0) {
output.write(buffer, 0, count);
}
} finally {
if (output != null) {
try {
output.close();
} catch (IOException ex) {
}
}
if (input != null) {
try {
input.close();
} catch (IOException ex) {
}
}
}