Access denied creating xml file in apache tomcat - ajax

I am creating an Exam Portal, in it there is a JSP calcresult.jsp which calculates the result of exam and shows the result also after that it creates an xml file which stores the result so that examiner can evaluate the result later.
here is the code for xml generation :
<%
DocumentBuilderFactory documentBuilderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder =
documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.newDocument();
Element rootElement = document.createElement("Exam_Report");
document.appendChild(rootElement);
Element em = document.createElement("Name");
em.appendChild(document.createTextNode(session.getAttribute("userid").toString()));
rootElement.appendChild(em);
em = document.createElement("Exam_Id");
em.appendChild(document.createTextNode(session.getAttribute("examid").toString()));
rootElement.appendChild(em);
em = document.createElement("Paper_id");
em.appendChild(document.createTextNode(session.getAttribute("paperid").toString()));
rootElement.appendChild(em);
em = document.createElement("No_Of_Ques");
em.appendChild(document.createTextNode(request.getParameter("qid")));
rootElement.appendChild(em);
em = document.createElement("No_Of_Correct_Ques");
em.appendChild(document.createTextNode(""+right));
rootElement.appendChild(em);
em = document.createElement("Total_Marks");
em.appendChild(document.createTextNode(""+tmarks));
rootElement.appendChild(em);
em = document.createElement("Marks");
em.appendChild(document.createTextNode(""+marks));
rootElement.appendChild(em);
em = document.createElement("Percentage");
em.appendChild(document.createTextNode(""+percentage));
rootElement.appendChild(em);
em = document.createElement("Result");
em.appendChild(document.createTextNode(result));
rootElement.appendChild(em);
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result1 = new StreamResult("CreateXML.xml");
transformer.transform(source, result1);
%>
everything works fine but when i run the page it shows an exception(Access Denied).
Well of course when i have to create a new page or file in server directory then i require administrative authority so what i did was to use absolute path which doesn't have any restriction like C:/xml/CreateXML.xml which really worked but now i am not able to access this xml page through AJAX.
So what is the best way to solve this problem. Any help will be really appreciated.
And well i am using Apache Tomcat as server.

One way would be to write a servlet to return the content of the XML file. Here's an example for a text file. For an xml file you should use "text/xml" as content type.
But a better way imo would be to avoid the creation of a local file and send the XML "on the fly" directly from the servlet. You can find an example here (the post is old but the code is still valid).

Related

Java I/O help. Jar Cannot Open File: URI is Not Hierarchal

I have been searching for 3 days now nonstop looking at every post I can find. My program runs on IntelliJ, but cannot run on an executable. Your help would be appreciated :)
More importantly, where can I find a in depth user-friendly tutorial? Is there a course or book I can pay for? On Udemy, the java classes completely fail to mention I/O such as classpath and URI. TutorialsPoint briefly goes over I/O buts its not indepth. Did I miss something? Is there an easier way to do all this??
Similar posts that have not worked for me:
Java Jar file: use resource errors: URI is not hierarchical
https://stackoverflow.com/a/27149287/155167
I am trying to load an excel file. I am using Maven. Apache POI says it needs a File. So InputStream does not work. http://poi.apache.org/components/spreadsheet/quick-guide.html#FileInputStream
When I java -jar jarFile, it gives me the error:
C:\Users\1010\Documents\Personal\MonsterManager>java -jar monsterManagerVer3.jar
Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical
at java.base/java.io.File.<init>(File.java:421)
at LoadExcel.<init>(LoadExcel.java:62)
at monsterRunner.<init>(monsterRunner.java:13)
at monsterRunner.main(monsterRunner.java:24)
Here is the code
public LoadExcel() throws IOException, URISyntaxException, InvalidFormatException {
mNames = null;
URL ins = this.getClass().getResource("/excel_List.xlsx");
if (ins == null)
throw new FileNotFoundException("The XLSX file didn't exist on the classpath");
ins.toString().replace(" ","%20"); //<-Runs without this part
File file = new File(ins.toURI()); //this is line 62
// File f = new File(getClass().getResource("/MyResource").toExternalForm());
//String path = this.getClass().getClassLoader().getResource("/excel_List.xlsx").toExternalForm();
//File file = new File(path);
OPCPackage pkg = OPCPackage.open(file);
XSSFWorkbook wb = new XSSFWorkbook(pkg);
//FileInputStream fis=new FileInputStream(new File(excelFile));
// XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
loadExcel(sheet);
cacheNames();
// fis.close();
wb.close();
}
If it helps here is the path to the excel file:
src\main\resources\excel_List.xlsx
UPDATE:
so I took the excel file out of the resources folder
\nameOfMyProgram\excel_List.xlsx
and now I get this error.
I tried several versions of using the classLoader, Class and Thread to solve this error from Different ways of loading a file as an InputStream
but I still cannot get it to compile.
Error and my code
If you have to use File object do not put xls-file into resources directory.
Maven puts all files from resources directory into jar.
Java can not create File object based on file in jar-file.
Put your xls-file somewhere in file system and create File object based on its URL.
Since your xls-file is not a resource do not use getResource.
Its URL is its full filename (with path).
This code below works with jar executable
String path = new File("excel_List.xlsx").getAbsoluteFile().toString();
File file = new File(path);
if(!file.exists()){
JOptionPane.showMessageDialog(null,"File not found!");
System.exit(0);
}
OPCPackage pkg = OPCPackage.open(file);
XSSFWorkbook wb = new XSSFWorkbook(pkg);

Can't generate jasper report on spring

I am trying to generate a PDF file using JasperReports, however, regardless of how I try it, it's giving me a NullPointerException.
https://community.jaspersoft.com/questions/520803/getting-null-pointer-exception-fillreport
Tried looking there, and changed the jasper properties file, but it didn't do anything and i'm still getting the same error.
Tried absolute paths, relative paths, getting resource as stream, nothing
This is the code i'm using to generate the report
public String generateInvoiceFor (Reservation reservation) throws JRException {
JasperReport jasperReport = JasperCompileManager.compileReport("I:\\anoranzaHopefullyFinal\\src\\main\\resources\\jasper\\FacturaFinalFinal.jrxml");
List<Reservation> reservations = reservationService.getAll();
JRBeanCollectionDataSource jrBeanCollectionDataSource = new JRBeanCollectionDataSource(reservations);
Map<String,Object> parameters = new HashMap<>();
parameters.put("Idparam", reservation.getId());
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, jrBeanCollectionDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "jasper/jasperOutput/Factura.pdf");
return "Report successfully generated #path= jasper/jasperOutput/";
}
Check your datasource and jasperPrint. If there is no problem try this.
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(
new SimpleOutputStreamExporterOutput("PDF NAME IS HERE.pdf"));
SimplePdfReportConfiguration reportConfig
= new SimplePdfReportConfiguration();
reportConfig.setSizePageToContent(true);
reportConfig.setForceLineBreakPolicy(false);
SimplePdfExporterConfiguration exportConfig
= new SimplePdfExporterConfiguration();
exportConfig.setMetadataAuthor("Auth name is here");
exportConfig.setEncrypted(true);
exportConfig.setAllowedPermissionsHint("PRINTING");
exporter.setConfiguration(reportConfig);
exporter.setConfiguration(exportConfig);
exporter.exportReport();

Conversion exceptions while using docx4j (From Docx to PDF)

I would like to know why this code:
String inputfilepath = "D:\\DFADFADSF";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath + ".docx"));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
wordMLPackage.setFontMapper(new IdentityPlusMapper());
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(wordMLPackage);
String outputfilepath = "D:\\OUT_FontContent.pdf";
OutputStream os = new java.io.FileOutputStream(outputfilepath);
Docx4J.toPDF(wordMLPackage,os);
Throws this exception:
org.docx4j.openpackaging.exceptions.Docx4JException: Exception exporting package
org.docx4j.openpackaging.exceptions.Docx4JException: Exception executing transformer: org.apache.fop.fo.ValidationException: "fo:flow" is missing child elements. Required content model: marker* (%block;)+
Although there are similar posts, I haven't seen one about this exception...
Maybe I should add aditional code to configure the conversion...

Framework for generating BPEL in runtime?

I need to generate BPEL XML code in runtime. The only way I can do it now is to create XML document with "bare hands" using DOM API. But there must be a framework that could ease such work incorporating some kind of object model.
I guess it should look something like this:
BPELProcessFactory.CreateProcess().addSequence
Do you know any?
The Eclipse BPEL designer project provides an EMF model for BPEL 2.0. The generated code can be used to programmatically create BPEL code with a convenient API.
In case anyone stumbles upon this.
Yes this can be done using the BPEL Model.
Here is a sample piece of code which generates a quite trivial BPEL file:
public Process createBPEL()
{
Process process = null;
BPELFactory factory = BPELFactory.eINSTANCE;
try
{
ResourceSet rSet = new ResourceSetImpl();
rSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
.put("bpel", new BPELResourceFactoryImpl());
File file = new File("myfile.bpel");
file.createNewFile();
String filePath = file.getAbsolutePath();
System.out.println(filePath);
AdapterRegistry.INSTANCE.registerAdapterFactory( BPELPackage.eINSTANCE, BasicBPELAdapterFactory.INSTANCE );
Resource resource = rSet.createResource(URI.createFileURI(filePath));
process = factory.createProcess();
process.setName("FirstBPEL");
Sequence seq = factory.createSequence();
seq.setName("MainSequence");
Receive recieve = factory.createReceive();
PortType portType = new PortTypeProxy(URI.createURI("http://baseuri"), new QName("qname"));
Operation operation = new OperationProxy(URI.createURI("http://localhost"), portType , "operation_name");
recieve.setOperation(operation);
Invoke invoke = factory.createInvoke();
invoke.setOperation(operation);
While whiles = factory.createWhile();
If if_st = factory.createIf();
List<Activity> activs = new ArrayList<Activity>();
activs.add(recieve);
activs.add(invoke);
activs.add(if_st);
activs.add(whiles);
seq.getActivities().addAll(activs);
process.setActivity(seq);
resource.getContents().add(process);
Map<String,String> map = new HashMap<String, String>();
map.put("bpel", "http://docs.oasis-open.org/wsbpel/2.0/process/executable");
map.put("xsd", "http://www.w3.org/2001/XMLSchema");
resource.save(map);
}
catch(Exception e)
{
e.printStackTrace();
}
return process;
}
The dependencies require that you add the following jars to the project's build path from the plugins folder in eclipse installation directory:
org.eclipse.bpel.model_*.jar
org.eclipse.wst.wsdl_*.jar
org.eclipse.emf.common_*.jar
org.eclipse.emf.ecore_*.jar
org.eclipse.emf.ecore.xmi_*.jar
javax.wsdl_*.jar
org.apache.xerces_*.jar
org.eclipse.bpel.common.model_*.jar
org.eclipse.xsd_*.jar
org.eclipse.core.resources_*.jar
org.eclipse.osgi_*.jar
org.eclipse.core.runtime_*.jar
org.eclipse.equinox.common_*.jar
org.eclipse.core.jobs_*.jar
org.eclipse.core.runtime.compatibility_*.jar

How to remove whitespace from XElement object created from XElement.ReadFrom(XmlReader)

I am parsing a large xml file. So I am using an XmlReader in combination with XElement instead of XElement.Load().
I have created as XElement object from XmlReader as shown below and here.
static IEnumerable<XElement> StreamRootChildDoc(string uri)
{
using (XmlReader reader = XmlReader.Create(uri, xmlReaderSettings))
{
reader.MoveToContent();
// Parse the file and display each of the nodes.
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
if (reader.Name == "Child")
{
XElement el = XElement.ReadFrom(reader) as XElement;
if (el != null)
yield return el;
}
break;
}
}
}
}
I want to save this XElement object content in the database as string without the whitespace. None of the below 3 ways work. Just a note, if I load the xml in memory using XElement.Load(), the ToString(SaveOptions.DisableFormatting) works.
<root> <child></child> </root> //xml saved in db with whitespace
<root><child></child></root> //want to save as this
XElement.ToString(SaveOptions.DisableFormatting) //
XElement.ToString(SaveOptions.None)
XElement.ToString()
The XmlReaderSettings I am using for the XmlReader object are below. I tried IgnoreWhitespace =true/false with no luck but I cannot set it as true as some elements are skipped (for reason for skipping, see Why does XmlReader skip every other element if there is no whitespace separator?).
XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.ProhibitDtd = false;
//xmlReaderSettings.IgnoreWhitespace = true;//cannot use this setting
It works if I parse the XElement object but that defeats the whole purpose of using XmlReader as XElement.Parse() loads the xml in memory.
XElement el = XElement.ReadFrom(reader) as XElement;
XElement.Parse(el.ToString(), LoadOptions.None)
How can I remove the whitespace?
Edit: This is what I had to do:
The elements skipping is due to two reads reader.Read() and XElement.ReadFrom(reader) in the same iteration thereby skipping every other element. Fixing the loop mentioned in the link above solves that. The issue has nothing to do with XmlReaderSettings.
xelement.ToString(SaveOptions.DisableFormatting) removes the pretty formatting.
Try using this example form the XMLTextReader class. The XMLTextReader has a method "WhitespaceHandling", which you can set to none. It would be helpfull to answer this question, if you could have provided a test XML file, to test is XMLTextReader works.

Resources