Jasper Report : "Document has no pages" - javascript

I have a problem when I run this code. I get always this message : "Document has no pages" with a blank page in the pdf file .
Note: I'm using NetBeans IDE 7.2 Beta.
Jar files imported are:
com.lowagie.text-2.1.7.jar
commons-beanutils-1.5.jar
commons-collections-2.1.jar
commons-digester-2.1.jar
commons-javaflow.jar
commons-logging-1.3.jar
jasperreports-5.5.1.jar
javax.servlet.jar
I need your help,please.
this is my code :
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Currency;
import java.util.HashMap;
import javax.swing.JFrame;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.swing.JRViewer;
public class Report extends JFrame{
public Report(String month,int year){
try{
//load the driver
Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://localhost:3306/motor";
String user="root";
String pass="";
Connection cn=DriverManager.getConnection(url,user,pass);
System.out.println("connected in report");
PreparedStatement ps = cn.prepareStatement("select number,title,name,ikar,echtirak,price,tarakom from users order by number asc");
ResultSet rs;
rs=ps.executeQuery();
JasperPrint jasperPrint=null;
HashMap<String, Object> mapParameters = new HashMap <String, Object>();
// jrxml compiling process
JasperReport jasperReport = JasperCompileManager.compileReport("C:/Users/user/Documents/NetBeansProjects/MotorApp/MyReports/motorReport.jrxml");
int i=1;
while(rs.next()){
mapParameters.put("Name", rs.getString("title")+" "+rs.getString("name"));
mapParameters.put("Number",rs.getString("number"));
mapParameters.put("Ikar",rs.getString("ikar"));
mapParameters.put("Amperage",rs.getString("echtirak")+" A");
mapParameters.put("tarakom",rs.getString("tarakom")+" $");
mapParameters.put("monthPrice",rs.getString("price")+" $");
Integer total=Integer.parseInt(rs.getString("price"))+Integer.parseInt(rs.getString("tarakom"));
mapParameters.put("totalPrice",total+" $");
mapParameters.put("monthYear",year+" "+month);
try{
System.out.println("Filling report...");
jasperPrint = JasperFillManager.fillReport(jasperReport, mapParameters,cn);
JRViewer viewer = new JRViewer(jasperPrint);
System.out.println("Done!");
JasperExportManager.exportReportToPdfFile(jasperPrint,"C:/Users/user/Desktop/"+month+" "+year+".pdf");
}catch(JRException elle){
System.out.println(elle.getMessage());
}
}
}catch(Exception ev){
System.out.println(ev.getMessage());
}
}
}
I truly appreciate your help.

My first thought is on the motorReport.jrxml file. It may have some issues on its content. Try reducing the contents of the report to a point where the code works and the reports can display properly. It may give you a clue to the cause of the problem. Then get back here with more specifics if you still can't solve this problem.

mapParameters in your code is not records of DataSource. It is parameters of report, therefore report haven't records.
One of the possible solutions: convert ResultSet into BeanCollection, make JRBeanCollectionDataSource and pass it into fillReport.
Make bean for saving result of query.
public class UserBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
....
}
For example result is
List myList = new ArrayList<UserBean>();
Convert into collection example here stackoverflow.com/questions/17206523/put-resultset-values-into-collection-object-then-add-to-arraylist
After convert you must call fillReport like this:
jasperPrint = JasperFillManager.fillReport(jasperReport, new HashMap<String,Object>, new JRBeanCollectionDataSource(myList));

Related

How to get same base64 hmac in java as in nodejs code?

I am trying to create a base64 hmac for sha256. I have two codes for the same, one in JS and other in Java,though I am doing it in android and a kotlin one will help me as well. I have mostly used codes from other SO answers only. The one in node js seems to give correct results and matches with the backend but in java is does not. Here are the codes
const crypto = require('crypto')
const base64urlm = require('base64url')
console.log('hello')
var yourMessage = 'Pritish8-s9';
var sharedSecret = 'Nilesh/ev12/';
//generate hmac sha256 hash
var hmacSignature = crypto.createHmac('SHA256', new Buffer(sharedSecret, 'base64')).update(yourMessage).digest('base64');
hmacSignature = base64urlm.fromBase64(hmacSignature)
console.log(hmacSignature)
It gives the output as
_eiq1peyHuPx8yQwzORwoT7wcNdzv2Y0LUp_E70aIvM
The above is the correct value. Now following is the java code.
package com.drivertest.hmactest;
import android.util.Log;
import org.apache.commons.codec.binary.Hex;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class HMAC {
public static String cal() {
try {
String secret = "Nilesh/ev12/";
String message = "Pritish8-s9";
byte[] secretByteArray = new byte[0];
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
secretByteArray = Base64.getEncoder().encode(secret.getBytes());
}
//byte[] secretByteArray = Base64.encodeBase64(secret.getBytes("utf-8"), true);
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(secretByteArray, "HmacSHA256");
sha256_HMAC.init(secret_key);
String hash = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
hash = Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(message.getBytes()));
}
System.out.println("hash "+hash);
Log.d("++++",hash);
return hash;
}
catch (Exception e){
System.out.println("Error");
}
return "";
}
public static String encode(String key, String data) {
try {
String secret = "Nilesh/ev12/";
String message = "Pritish8-s9";
key=secret;
data=message;
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
sha256_HMAC.init(secret_key);
SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
sha256_HMAC.init(secretKey);
String hash = android.util.Base64.encodeToString(sha256_HMAC.doFinal(message.getBytes()), android.util.Base64.DEFAULT);
Log.d("++",hash);
return Hex.encodeHexString(sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
}
It is a class where I have attempted to do it in different ways with other SO answers. Unfortunately I get a value like
8i/ce0u0GZ+JhL3yblsGhaMnFC0UKkUwJSQSXZ3536s=
or
f22fdc7b4bb4199f8984bdf26e5b0685a327142d142a45302524125d9df9dfab
So can anyone help me in writing java/kotlin code for the same and get the same value like the above in nodejs ?
PS : I have verified the java results on random sites and they seem to match, but my api is failing with this value , and will only work if it can match with that os nodejs, so it is incorrect in that sense.
Thank you :)
There are two differences between your nodejs and Java implementations.
First and the most important: in nodejs you decode your secret using base64, while in Java you encode it:
Base64.getEncoder().encode(secret.getBytes())
Replace it with:
Base64.getDecoder().decode(secret.getBytes())
Second, in nodejs you use URL variant of base64 (base64urlm) when encoding the final result. In Java you use a regular base64. Replace it with:
Base64.getUrlEncoder().encodeToString(...)

Empty page using sendIntent.putExtras(bundle), page not filled Android studio

I'm trying to send some stuff via mail or Bluetooth etc but not working very well.
I would like to see a text like this:
" Respiration Rate: 0 2.0 5.0 16.0 "...
To do that I've implemented a button and Resut.java stuff. When I try to click on the button and I choose e-mail, app open a mail and the text is only "Respiration Rate"
here click-button:
SRR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bundle bundle = new Bundle();
bundle.putDoubleArray("TryThis",plot_array);
sendIntent.putExtras(bundle);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " );
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
result.java:
package com.google.android.gms.samples.vision.face.rPPG;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.jjoe64.graphview.series.PointsGraphSeries;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;
public class RespirationResult extends AppCompatActivity {
private String Date;
int RR;
int il_risultato;
double [] plot_array;
int[] intArray;
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
java.util.Date today = Calendar.getInstance().getTime();
private String[] RRtoSent=new String[300];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_respiration_result);
Date = df.format(today);
TextView RRR = (TextView) this.findViewById(R.id.RRR);
ImageButton SRR = (ImageButton)this.findViewById(R.id.SendRR);
//-------------------------------------------------------------------------risutato
Bundle b = getIntent().getExtras();
double result = b.getDouble("key");
plot_array=b.getDoubleArray("array");
il_risultato=(int) Math.round(result);
RRR.setText(String.valueOf(il_risultato)); //prima era RR, da mettere successivamente
RRtoSent = new String[plot_array.length];
for (int i = 0; i < RRtoSent.length; i++) {
RRtoSent[i] = String.valueOf(plot_array[i]);
}
//grafico
GraphView graph;
LineGraphSeries<DataPoint> series; //an Object of the PointsGraphSeries for plotting scatter graphs
graph = (GraphView) findViewById(R.id.graphico);
series= new LineGraphSeries<>(data()); //initializing/defining series to get the data from the method 'data()'
graph.addSeries(series); //adding the series to the GraphView
//series.setShape(PointsGraphSeries.Shape.POINT);
// activate horizontal and vertical zooming and scrolling
graph.getViewport().setScalableY(true);
graph.getGridLabelRenderer().setGridColor(Color.DKGRAY);
graph.getGridLabelRenderer().setHorizontalLabelsColor(Color.DKGRAY);
graph.getGridLabelRenderer().setVerticalLabelsColor(Color.DKGRAY);
// graph.setTitle("Respiration Rate/min");
graph.getGridLabelRenderer().setHorizontalAxisTitle("time(sec)");
graph.getGridLabelRenderer().setVerticalAxisTitle("RR");
// set manual X bounds
graph.getViewport().setXAxisBoundsManual(true);
graph.getViewport().setMinX(0.5);
graph.getViewport().setMaxX(100);
SRR.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
Bundle bundle = new Bundle();
bundle.putDoubleArray("TryThis",plot_array);
sendIntent.putExtras(bundle);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " );
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
}
});
}
public DataPoint[] data(){
DataPoint[] values = new DataPoint[plot_array.length]; //creating an object of type DataPoint[] of size 'n'
for(int i=0;i<plot_array.length;i++){
DataPoint v = new DataPoint(i,plot_array[i]);
values[i] = v;
}
return values;
}
#Override
public void onBackPressed() {
Intent i = new Intent(RespirationResult.this, SplashScreen.class);
startActivity(i);
finish();
super.onBackPressed();
}
}
Does anyone have an idea about it?
what's wrong or missing?
Thanks in advance
From Android official site:
public static final String EXTRA_TEXT
A constant CharSequence that is associated with the Intent, used with
ACTION_SEND to supply the literal data to be sent. Note that this may
be a styled CharSequence, so you must use Bundle.getCharSequence() to
retrieve it.
So you should convert your double array to String first before calling email app.
Step 1: Write a method which convert a double array to a string.
private String convertDoubleArrayToString(double[] array) {
StringBuilder sb = new StringBuilder();
for (double number: array) {
sb.append(number).append(" ");
}
return sb.toString();
}
Step 2: Change your code to
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Respiration Rate: " + convertDoubleArrayToString(plot_array));
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.send_to)));
That's because all you want to show must be part of the EXTRA_TEXT:
sendIntent.putExtra(Intent.EXTRA_TEXT, "EVERYTHING YOU WANT TO PRINT HERE" );
So you have to build a string with your data, then you create the extra with the complete string.

Can we give bulk url's in this code?

URL url = new URI("http://tamilblog.ishafoundation.org/").toURL();
I want to give 100 url in this connector?
I have the code to run single home page to extract its data
I need to get more contents From several links !
Is it any way possible ?
Here is my code
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class NewClass {
public static void main(String[] args) throws IOException {
Document doc = Jsoup.connect("http://tamilblog.ishafoundation.org").get();
Elements section = doc.select("section#content");
Elements article = section.select("article");
for (Element a : article) {
System.out.println("Title : \n" + a.select("a").text());
System.out.println("Article summary: \n" + a.select("div.entry-summary").text());
}
}
}
I got output from this single page Now i need to get it from several pages (100+links) at once.
And to save it in a document.

Programming string to array/list [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
So I received a text file to create an API, and in this text file I have an example similar to this:
id,first_name,last_name
1,John,Smith
2,Charlie,Sheen
The list goes on with about 100+ rows.
Is there a way to organize this programmatically?
I don't want to manually write this into json format.
I'll take java, C#, Javascript, or php methods.
public String[] returnArray(String line){
return line.split(",");}
This organizes the new array into the elements between each comma. In this example the first element would equal id.
There are lots of open source CSV readers out there for Java and other languages and I highly recommend using one of them. However, if you want a quickly working solution with no additional libraries you can use the following code. Make sure to edit the file name to point to wherever your text file is. Or you can edit the code to allow someone to pass the file name in. When you run this it will echo out the contents of the file.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile
{
private static class Record
{
public String id;
public String firstName;
public String lastName;
#Override
public String toString()
{
return id + "," + firstName + "," + lastName;
}
}
public static void main(String[] args) throws IOException
{
List<Record> records = getRecordsFromFile("C:/Myfile.txt");
for(Record record : records)
{
System.out.println(record);
}
}
private static List<Record> getRecordsFromFile(String fileName) throws IOException
{
List<Record> records = new ArrayList<>();
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(new File(fileName)));
String line = null;
while((line = reader.readLine()) != null)
{
records.add(makeRecordFromLine(line));
}
return records;
}
finally
{
if(reader != null)
{
reader.close();
}
}
}
private static Record makeRecordFromLine(String line)
{
String[] lineArray = line.split(",");
Record record = new Record();
record.id = lineArray[0];
record.firstName = lineArray[1];
record.lastName = lineArray[2];
return record;
}
}
you can use past special techniques to read all the json please have a look into this link:
How to show the "paste Json class" in visual studio 2012 when clicking on Paste Special?

How to pass a camera image to mail as an attachment. (Android, iOS, Windows Phone, Phonegap)

I am developing an app for my work (social housing) and I want it to be able to allow the user to take a photo and attach it to an email so they can send it to us (pictures of repairs etc)
I'm using Phonegap and Eclipse as I want the app to be cross platform but am testing in Android primarily at the moment. Is there a way to do this? I am currently using the code below with no avail.
<script typr="text/javascript" charset="utf-8">
function camera()
{
navigator.camera.getPicture(onSuccess, onFail, { quality: 20,
destinationType: Camera.DestinationType.DATA_URL
});
function onSuccess(imageData) {
var image = document.getElementById('image');
var data = "data:image/jpeg;base64," + imageData;
var link = "mailto:johnsmith#gmail.com?body="+data+"&subject=john smith";
window.location.href = link;
}
function onFail(message) {
alert('Failed because: ' + message);
}
}
</script>
So far I've tried passing the data through to the mail app using the mailto: &attachment method but that never attaches an image (most mail apps treat this as a security hole). Then I tried to embed the base64 code of the image in the body of the email (as shown above). Unfortunately the base64 just displays as plain text and makes mail unresponsive. I've also tried using the image URI instead of the Base64 method in Phonegap but that throws an 'image.URI is not defined' error in my logcat.
Is this possible? I know I can use intents for just android as detailed in another question here but this won't work on iOS etc.
Any help would be greatly appreciated.
EDIT 02/12/2012
What I'm trying to achieve here is the same functionality you get in the native Android gallery/camera app. After you take a picture you have share options, one of which is mail. If you chose to share via mail the image is passed to the mail app as an attachment. Is there any way I can implement this same functionality in my app?
So it looks like there is no 'one size fits all' solution for this problem.
The mailto: method just doesn't pass attachments in most modern mail apps as it's seen as a security risk. So regardless of whether its an imageURI or a base64 encoded image, mailto: just won't work. The passing of 'subject' and 'body' works well though for anyone that wants to use the above code for pre-filling in an email with no attachments.
After posing this question elsewhere it looks like I'll need to use a phonegap plugin (emailComposer for iOS and WebIntent for Android) in order to pass an image sucessfully to a mail app from my phonegap app.
Thanks.
use this JAVA code to send Email with photo and text.
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Security;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class GMailSender extends javax.mail.Authenticator {
private String mailhost = "smtp.gmail.com";
private String user;
private String password;
private Session session;
static {
Security.addProvider(new JSSEProvider());
}
public GMailSender(String user, String password) {
this.user = user;
this.password = password;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");
session = Session.getDefaultInstance(props, this);
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
public synchronized void sendMail(String subject, String body, String sender, String recipients) throws Exception {
try {
MimeMessage message = new MimeMessage(session);
DataHandler handler = new DataHandler(new ByteArrayDataSource(body.getBytes(), "text/plain"));
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setDataHandler(handler);
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
Transport.send(message);
} catch (Exception e) {
}
}
public synchronized void sendMail(String subject, String body, String senderEmail, String recipients, String filePath,String logFilePath) throws Exception {
boolean fileExists = new File(filePath).exists();
if (fileExists) {
String from = senderEmail;
String to = recipients;
String fileAttachment = filePath;
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
// create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// fill message
messageBodyPart.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(fileAttachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("screenShoot.jpg");
multipart.addBodyPart(messageBodyPart);
//part three for logs
messageBodyPart = new MimeBodyPart();
DataSource sourceb = new FileDataSource(logFilePath);
messageBodyPart.setDataHandler(new DataHandler(sourceb));
messageBodyPart.setFileName("logs.txt");
multipart.addBodyPart(messageBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
}else{
sendMail( subject, body, senderEmail, recipients);
}
}
public class ByteArrayDataSource implements DataSource {
private byte[] data;
private String type;
public ByteArrayDataSource(byte[] data, String type) {
super();
this.data = data;
this.type = type;
}
public ByteArrayDataSource(byte[] data) {
super();
this.data = data;
}
public void setType(String type) {
this.type = type;
}
public String getContentType() {
if (type == null)
return "application/octet-stream";
else
return type;
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(data);
}
public String getName() {
return "ByteArrayDataSource";
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("Not Supported");
}
}
}

Categories

Resources