I have an error while compiling report the error is:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: javax/servlet/ServletOutputStream
this is the code:
Map parameter = new HashMap();
parameter.put("customerId", notification_table.getValueAt(r, 0).toString());
ReportV sd = new ReportV();
sd.showReport(parameter);
this is the class I used:
import java.sql.*;
import java.util.Map;
import javax.swing.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import net.sf.jasperreports.engine.JasperCompileManager;
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 ReportV {
Connection conn = null;
void showReport(Map parameters) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("jdbc:odbc:pcn");
JasperReport report = JasperCompileManager.compileReport("recipt.jrxml");
JasperPrint print = JasperFillManager.fillReport(report, parameters, conn);
JRViewer viewer = new JRViewer(print);
viewer.setOpaque(true);
viewer.setVisible(true);
//make your JFrame visible
this.add(viewer);
this.setSize(300, 200);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
} catch (Exception ex) {
System.out.println("CAUSE: " + ex.getCause());
System.out.println("MESSAGE" + ex.getMessage());
System.out.println("LOCAL MESSAGE" + ex.getLocalizedMessage());
ex.printStackTrace();
}
}
}
you have not imported the ServletOutputStream class.
import javax.servlet.ServletOutputStream;
I believe that's part of Java EE, so you will need that lib in your classpath in addition to the standard java jdk.
Related
I have the following error: Content not allowed in Prolog** I have two methos, one called from main and another from button event handler. One method read the rdf file and another create individual of Student class based on name entered by users in a text field.
What is the expected error.
My code is:
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntClass;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.util.FileManager;
import javax.swing.*;
import java.awt.*;
import static java.io.FileDescriptor.in;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewJFrame extends javax.swing.JFrame {
OntModel model = ModelFactory.createOntologyModel();
public static void readOntology(String file,OntModel model)
InputStream in = FileManager.get().open(file);
if (in ==null) {
throw new IllegalArgumentException( "File: " + file + " not found");
}
model.read(in,"");
Another method called from Button handler method()
private static void read1(String str,OntModel model)
{
String ns="http://www.semanticweb.org/untitled-ontology-0012/";
OntClass user = model.createClass(ns + "User");
OntClass user1 = model.getOntClass(ns + "User");
Individual janeSmith = user1.createIndividual(ns + str);
JOptionPane.showMessageDialog(null, janeSmith.toString());
try {
String file="F://student.owl";
FileWriter out=new FileWriter(file);
} catch (IOException ex) { Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
OntModel model=ModelFactory.createOntologyModel();
String str=jTextField2.getText();
read1(str, model);
}
And finally main()
public static void main(String args[]) {
OntModel model = ModelFactory.createOntologyModel();
// read camera ontology
String file="F://student.owl";
readOntology(file , model );
I'm stumped. This script works great in Eclipse on my windows machine, if I hard code the file paths. If I try to take in arguments and run it on my edge node (a linux box), it throws no particular errors but it just leaves an empty output file. I must be missing something stupid, but I am not seeing it. Anyone have any idea what's going on?
package com.trv.cbia.de.tika;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class DocParser {
public Map<String, Object> processRecord(String path) {
Map<String, Object> map = new HashMap<String, Object>();
String docPath = path;
try{
BodyContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
InputStream inputstream = new FileInputStream(new File(docPath));
ParseContext pcontext = new ParseContext();
Parser pdfparser = new AutoDetectParser();
pdfparser.parse(inputstream, handler, metadata, pcontext);
map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
map.put("title", metadata.get(TikaCoreProperties.TITLE));
map.put("pageCount", metadata.get("xmpTPg:NPages"));
} catch (IOException ex){
System.out.println("Caught IOException:" + ex.getMessage());
}
catch(TikaException tx) {
System.out.println("Caught TikaException: " + tx.getMessage());
}
catch(SAXException sx){
System.out.println("Caught SAXException: " + sx.getMessage());
}
return map;
}
public static void main(String args[]){
String file = args[0];
String out = args[1];
DocParser textExtract = new DocParser();
Map<String, Object> extractedMap = textExtract.processRecord(file);
try {
PrintWriter writer = new PrintWriter(out,"UTF-8");
writer.println(extractedMap.get("text"));
writer.flush();
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
Ended up being that I needed to add tika-app-1.13.jar to my classpath. It never divulged any classpath errors. I had to dig through a bunch of the apache mailing list to find someone with a similar problem. Posting the solution here in case anyone else runs across it.
I am trying to use the JasperReports library in a plain Java application. It won't compile because it can't find the aegean chart theme. Can someone point me to a simple example of how to get a .jrxml file to compile and pass this theme to the JasperCompileManager?
package com.asset.jasper.mvc.reports;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.PreparedStatement;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
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.chartthemes.simple.AegeanSettingsFactory;
import net.sf.jasperreports.chartthemes.simple.XmlChartTheme;
import net.sf.jasperreports.chartthemes.spring.AegeanChartTheme;
public class AssetReport {
private static final Log log = LogFactory.getLog (AssetReport.class);
public static void main(String[] args) throws JRException, IOException {
AegeanChartTheme aegeanChartTheme = new AegeanChartTheme();
XmlChartTheme.saveSettings(
AegeanSettingsFactory.createChartThemeSettings(),
new File("src/net/sf/jasperreports/chartthemes/simple/aegean.jrctx")
);
JasperReport jasperReport = JasperCompileManager.compileReport(
"/resources/ARKREPORT.jrxml");
Map<String, Object> parameters = new HashMap<String, Object>();
Connection myconnection = getConnection();
String jdbcString = "select * from asset";
PreparedStatement statement = null;
try {
statement = myconnection.prepareStatement(jdbcString.toString());
} catch (SQLException e) {
e.printStackTrace();
}
ResultSet rs = null;
try {
rs = statement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
JRDataSource dataSource = new JRResultSetDataSource(rs);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
File outDir = new File("/Users/denisputnam/tmp");
outDir.mkdirs();
JasperExportManager.exportReportToPdfFile(jasperPrint, "/tmp/StyledTextReport.pdf");
JasperExportManager.exportReportToHtmlFile(jasperPrint, "/tmp/StyledTextReport.html");
}
static public Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/assetcore", "assetcore", "password");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
I have the following code and I am trying to create a connection to a database.
I get an error "Could not find or load main class onjava" when I run the command: java -cp . onjava
I am able to run the javac -classpath "C:\CATALINA_HOME\lib*" onjava.java command
Both of my .class and .java files are in the same directory WEB-INF\classes\com\onjava
onjava.java
package com.onjava;
import java.sql.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.*;
import javax.naming.Context;
public class onjava extends HttpServlet {
private DataSource datasource;
public void init(ServletConfig config) throws ServletException {
try {
// Look up the JNDI data source only once at init time
Context envCtx = (Context) new InitialContext().lookup("java:comp/env");
datasource = (DataSource) ((InitialContext) envCtx).lookup("jdbc/testdb");
}
catch (NamingException e) {
e.printStackTrace();
}
}
private Connection getConnection() throws SQLException {
return datasource.getConnection();
}
public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException {
Connection connection=null;
try {
connection = getConnection();
//..<do JDBC work>..
if (connection != null) {
String message = "You are connected!";
System.out.println(message);
} else {
System.out.println("Failed to make connection!");
}
}
catch (SQLException sqlException) {
sqlException.printStackTrace();
}
finally {
if (connection != null)
try {connection.close();} catch (SQLException e) {}
}
}
}
EDIT:
I changed my code and I added the public class. But I am facing the same error when I run it!
package src;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Wrapper;
import java.util.Hashtable;
import java.util.Properties;
import java.io.*;
import javax.activation.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import oracle.jdbc.pool.OracleDataSource;
public class onjava {
public static void main(String[] argv) throws SQLException, NamingException {
Properties prop = new Properties();
System.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.apache.naming.java.javaURLContextFactory");
Context initialContext = new InitialContext(prop);
if ( initialContext == null){
System.out.print("JNDI problem. Cannot get InitialContext.");
} else {System.out.print("NO JNDI problemb ");}
// Get DataSource
Context envContext = (Context)initialContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/testdb");
System.out.println("\n -------- Oracle JDBC Connection Testing ------");
try {
Connection jdbcConnection = ((Statement) ds).getConnection();
OracleDataSource ods = ((Wrapper) ds).unwrap(OracleDataSource.class);
jdbcConnection.close();
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
String message = "You are connected!";
System.out.println(message);
}
}
When running java like this, you need to explicitly state the main class. Your command should look something more like java -cp . com.onjava.onjava. However, I don't see the main method in this class either. You need to point to the main method (ie, signature public static void main()).
By the way, it is proper convention to give your classes names that start with a capital letter (Onjava).
Ok so from what you told me, you need to have a main class attached to your project. This means going back to your compiler and creating the main method. To add your code, you will need to do something like this in the main class, which I will call onjavaMain:
public class onjavaMain{
//Main method is this
public static void main(String[] args)
{
//create variable of your onjava class
onjava onJavaConnectToDatabase = new onjava();
onJavaConnectToDatabase.doGet(argument1,argument2);
}
}
Now this is not the complete answer, but this will give you an idea of what you need to do in order to run your project in command line.
I tried to create a Dynamic-reports but Error occured.Anybody give some solution for create Dynamic Reports java.
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import net.sf.dynamicreports.report.builder.column.Columns;
import net.sf.dynamicreports.report.builder.component.Components;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.constant.HorizontalAlignment;
import net.sf.dynamicreports.report.exception.DRException;
public class NewClass {
public static void main(String[] args) {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sts","john", "pswrd");
} catch (SQLException e) {
e.printStackTrace();
return;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
JasperReportBuilder report = DynamicReports.report();//a new report
report
.columns(
Columns.column("Customer Id", "customerid", DataTypes.integerType()),
Columns.column("Name", "customername", DataTypes.stringType()),
Columns.column("Address", "address", DataTypes.stringType()),
Columns.column("Date", "dates", DataTypes.dateType()))
.title(//title of the report
Components.text("SimpleReportExample")
.setHorizontalAlignment(HorizontalAlignment.CENTER))
.pageFooter(Components.pageXofY())//show page number on the page footer
.setDataSource("SELECT customerid, customername,address,dates FROM customersdetails",
connection);
try {
//show the report
report.show();
//export the report to a pdf file
report.toPdf(new FileOutputStream("D:/report.pdf"));
} catch (DRException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
I tried to create a dynamic-reports but error occured.
Exception:
Exception in thread "main" java.lang.NoSuchMethodError: net.sf.jasperreports.engine.util.JRLoader.getLocationInputStream(Ljava/lang/String;)Ljava/io/InputStream;
at net.sf.jasperreports.engine.JRPropertiesUtil.loadProperties(JRPropertiesUtil.java:99) at net.sf.jasperreports.engine.JRPropertiesUtil.loadProperties(JRPropertiesUtil.java:99)
at net.sf.jasperreports.engine.DefaultJasperReportsContext.initProperties(DefaultJasperReportsContext.java:94)
at net.sf.jasperreports.engine.DefaultJasperReportsContext.<init>(DefaultJasperReportsContext.java:71)
at net.sf.jasperreports.engine.DefaultJasperReportsContext.<clinit>(DefaultJasperReportsContext.java:59)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFont(StyleResolver.java:95)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFont(StyleResolver.java:71)
at net.sf.dynamicreports.design.transformation.StyleResolver.getFontHeight(StyleResolver.java:52)
at net.sf.dynamicreports.design.transformation.TemplateTransform.getTextFieldHeight(TemplateTransform.java:981)
at net.sf.dynamicreports.design.transformation.ComponentTransform.textField(ComponentTransform.java:334)
at net.sf.dynamicreports.design.transformation.ComponentTransform.component(ComponentTransform.java:154)
at net.sf.dynamicreports.design.transformation.ComponentTransform.list(ComponentTransform.java:287)
at net.sf.dynamicreports.design.transformation.BandTransform.band(BandTransform.java:184)
at net.sf.dynamicreports.design.transformation.BandTransform.transform(BandTransform.java:74)
at net.sf.dynamicreports.design.base.DRDesignReport.transform(DRDesignReport.java:136)
at net.sf.dynamicreports.design.base.DRDesignReport.<init>(DRDesignReport.java:108)
at net.sf.dynamicreports.design.base.DRDesignReport.<init>(DRDesignReport.java:100)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperReportDesign(JasperReportBuilder.java:261)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.getJasperParameters(JasperReportBuilder.java:288)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.toJasperPrint(JasperReportBuilder.java:299)
at net.sf.dynamicreports.jasper.builder.JasperReportBuilder.show(JasperReportBuilder.java:328)
at Robb.NewClass.main(NewClass.java:60)
You need to add jar in your project