Is there any solution to have something like <cms:include type="OpenCmsString" element="text1" /> ? Because the output from my <cms:include element="text1"> always give me data with <p> tag.
Any kind help is appreciated.
I've once created my own tag for that (StripPTag). You would compile that class and wrap it in a jar file, then deploy that to your opencms webapp lib folder.
package com.opencmsserver.taglib;
import org.opencms.flex.CmsFlexController;
import org.opencms.jsp.Messages;
import org.opencms.main.CmsLog;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.commons.logging.Log;
/**
* Removes the <p> tag from the surrounded content,
* because FCKEditor always add <p> tag to content at
* the beginning and end when using the html editor component
*
* #author Mathias Lin
*
* #version $Revision: 0.1 $
*
* #since 0.4
*/
public class StripPTag extends BodyTagSupport {
/** Serial version UID required for safe serialization. */
private static final long serialVersionUID = -2361021288258405388L;
/** The log object for this class. */
private static final Log LOG = CmsLog.getLog(StripPTag.class);
/**
* #see javax.servlet.jsp.tagext.Tag#doEndTag()
* #return EVAL_PAGE
* #throws JspException in case soemthing goes wrong
*/
public int doEndTag() throws JspException {
ServletRequest req = pageContext.getRequest();
// This will always be true if the page is called through OpenCms
if (CmsFlexController.isCmsRequest(req)) {
try {
// Get link-string from the body and reset body
String content = getBodyContent().getString();
content = content.replaceAll("<p>", "");
content = content.replaceAll("</p>", "");
getBodyContent().clear();
getBodyContent().print(content);
getBodyContent().writeOut(pageContext.getOut());
} catch (Exception ex) {
if (LOG.isErrorEnabled()) {
LOG.error("Failed using StripPTag. ", ex);
}
throw new JspException(ex);
}
}
return EVAL_PAGE;
}
}
and my own opencmsserver.tld:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>0.1</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>opencmsserver</short-name>
<uri>http://www.opencmsserver.com/taglib/cms</uri>
<display-name>OpenCms JSP standard taglib</display-name>
<description>
Additional OpenCms Tags
Developed by SYSVISION Ltd. / Mathias Lin (info#opencmsserver.com)
</description>
<tag>
<name>stripPTag</name>
<tag-class>com.opencmsserver.taglib.StripPTag</tag-class>
<body-content>JSP</body-content>
<description>
This tag stripts the p-tag from the surrounded content.
</description>
</tag>
</taglib>
which I then reference in my web.xml:
<!-- Begin: Custom SYSVISION OpenCmsServer lib -->
<taglib>
<taglib-uri>http://www.opencmsserver.com/taglib/opencmsserver</taglib-uri>
<taglib-location>/WEB-INF/opencmsserver.tld</taglib-location>
</taglib>
In your jsp, you just surround it then with:
<opencmsserver:stripPTag>Some content<p>with a paragraph</opencmsserver:stripPTag>
(and don't forget to reference to this tag lib in the jsp header section).
Related
I'm trying to build a simple Webscript Endpoint in Alfresco that gets a pdf using a Java Webscript controller. We eventually want to expand this endpoint to take multiple pdfs and do some manipulation, but for right now we are just trying to read in and save 1 pdf.
The problem is the resulting InputStream is empty. This is despite it working just fine for xml files.
This is our uploadpdf.get.desc
<webscript>
<shortname>Upload PDFs</shortname>
<description>Upload PDFs</description>
<url>/uploadpdf</url>
<authentication>user</authentication>
<format default="html"></format>
</webscript>
This is our uploadpdf.get.html.ftl
<html>
<body>
<form action="${url.service}" method="post" enctype="multipart/form-data">
PDF1: <input type="file" name="pdf1"><br>
XML1: <input type="file" name="xml1"><br>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
This is our uploadpdf.post.dec
<webscript>
<shortname>Upload PDFs</shortname>
<description>Upload PDFs</description>
<url>/uploadpdf</url>
<authentication>user</authentication>
<format default="json"></format>
</webscript>
This is our uploadpdf.post.json.ftl (currently just returning a test string)
${newFile}
This is our Webscript-context.xml
<?xml version='1.0' encoding='UTF-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="webscript.alfresco.tutorials.helloworld.get"
class="com.test.platformsample.HelloWorldWebScript"
parent="webscript">
</bean>
<bean id="webscript.uploadpdf.get"
class="com.test.UploadPdfWebScript"
parent="webscript">
</bean>
<bean id="webscript.uploadpdf.post"
class="com.test.UploadPdfWebScript"
parent="webscript">
</bean>
</beans>
And this is our UploadPdfWebscript.java (notice for testing purposes we are using org.springframework.extensions.webscripts.servlet.FormData;
This is to easily get the file. The code then saves the file to the local docker container. The problem is that file and by extention the InputStream is empty.
package com.test;
import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.servlet.FormData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;
public class UploadPdfWebScript extends DeclarativeWebScript {
private static Log logger = LogFactory.getLog(UploadPdfWebScript.class);
protected Map<String, Object> executeImpl(
WebScriptRequest req, Status status, Cache cache) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("fromJava", "HelloFromJava");
logger.debug("Your 'UploadPdf' Web Script was called!");
final FormData form = (FormData)req.parseContent();
InputStream file1 = null;
if(form == null || form.getFields() == null) {
return model;
}
for (FormData.FormField field : form.getFields())
{
if (field.getName().equals("pdf1"))
{
file1 = field.getInputStream();
}
}
String result = "this should be overwritten";
try{
result = processFile(file1);
} catch(Exception e) {
logger.error(e.getMessage());
}
if(result == null || result.equals("")) {
result = "No result";
}
model.put("newFile", result);
return model;
}
public String processFile(InputStream file) {
String ret = "{\”Result\": Success}”;
try {
byte[] buffer = new byte[file.available()];
file.read(buffer);
File targetFile = new File("targetFile.pdf");
OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer2);
} catch (Exception e) {
ret = "{\”Result\": Failure}”;
logger.error(e.getMessage(), e);
}
return ret;
}
How can I get a pdf or other arbitrary file type from the InputStream? Again the InputStream that is returned from the form is empty whenever I try to upload a pdf and as a result so is the saved pdf.
Note: If I try to read the pdf from the local file system rather than sending it via a post request, this works fine. The pdf I'm uploading is definitely valid and not empty. I also know the webscript is being properly called as it is posting a log message, returning Success, and creating the targetFile.pdf which is empty.
Change this line:
outStream.write(buffer2);
To:
outStream.write(buffer);
Here's what shows up in the tomcat dir on my Docker container:
-rw-r----- 1 root root 117249 Aug 7 19:28 targetFile.pdf
Looks like it works!
I'm new to JavaEE and currently learning JavaEE7. I have JavaEE7 installed and downloaded NetBeans 8.0.2 so I could follow allow with the Webinar published here:
https://www.youtube.com/watch?v=sCNslREYpD0&spfreload=10
This tutorial in the video uses JavaEE6 rather than JavaEE7.
I made it about 12 minutes into the Webinar before I encountered the java.lang.IllegalStateException mentioned in the title of my post. At 12:18 in the video, the presenter adds a #PersistenceUnit to the code, and then an EntityManagerFactory. Even though I have followed his tutorial very carefully, I'm having issues with persistence and keep getting the following Exception:
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
at com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper.getDelegate(EntityManagerFactoryWrapper.java:103)
at com.sun.enterprise.container.common.impl.EntityManagerFactoryWrapper.createEntityManager(EntityManagerFactoryWrapper.java:114)
at org.glasssfish.samples.TestServlet.processRequest(TestServlet.java:79)
at org.glasssfish.samples.TestServlet.doGet(TestServlet.java:103)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
I have search StackOverflow and Google extensively, and the answer I keep coming across relates to the location of the persistence.xml file. I'm using NetBeans which automatically creates and places the persistence.xml file in a Configuration Files folder.
The project layout in NetBean 8.0.2 looks like the following:
Web Pages
WEB-INF
index.html
Source Packages
org.glassfish.samples
TestServlet.java
org.glassfish.samples.model
Friend.java
Libraries
JDK 1.8 (Default)
GlassFish Server 4.1
Configuration Files
MANIFEST.MF
persistence.xml
Here is Friend.java file that was automatically generated by NetBeans as part of the tutorial:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.glasssfish.samples.model;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author james
*/
#Entity
#Table(name = "FRIEND")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Friend.findAll", query = "SELECT f FROM Friend f"),
#NamedQuery(name = "Friend.findByName", query = "SELECT f FROM Friend f WHERE f.name = :name"),
#NamedQuery(name = "Friend.findByAge", query = "SELECT f FROM Friend f WHERE f.age = :age")})
public class Friend implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 30)
#Column(name = "NAME")
private String name;
#Column(name = "AGE")
private Integer age;
public Friend() {
}
public Friend(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#Override
public int hashCode() {
int hash = 0;
hash += (name != null ? name.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Friend)) {
return false;
}
Friend other = (Friend) object;
if ((this.name == null && other.name != null) || (this.name != null && !this.name.equals(other.name))) {
return false;
}
return true;
}
#Override
public String toString() {
return "org.glasssfish.samples.model.Friend[ name=" + name + " ]";
}
}
Here is the TestServlet.java file:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.glasssfish.samples;
import java.io.IOException;
import java.io.PrintWriter;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.glasssfish.samples.model.Friend;
/**
*
* #author james
*/
#WebServlet(name = "TestServlet", urlPatterns = {"/TestServlet"})
public class TestServlet extends HttpServlet {
#PersistenceUnit
EntityManagerFactory emf;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet TestServlet at " + request.getContextPath() + "</h1>");
//
int count;
if (request.getSession().getAttribute("count") == null) {
count = 0;
} else {
count = (Integer)request.getSession().getAttribute("count");
}
request.getSession().setAttribute("count", ++count);
out.println("Accessed again: " + request.getSession().getAttribute("count"));
Friend f = (Friend)emf.createEntityManager().createNamedQuery("Friend.findAll").getResultList().get(0);
out.println("Friend name: " + f.getName());
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
And, of course, the seemingly infamous persistence.xml file that was automatically generated by NetBean 8.0.2:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JavaEE7WebinarPU" transaction-type="JTA">
<jta-data-source>jdbc/sample</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
I tried a variety of things like:
injecting a PersistenceContext instead of a PersistenceUnit and getting an EntityManager directly from there instead of using an EntityManagerFactor (not sure if I did that correctly).
modifying my #PersistenceUnit to #PersistenceUnit(unitName="JavaEE7WebinarPU"). This didn't help much. It just changed my error from:
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName null
to
java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName JavaEE7WebinarPU
I verified that my GlassFish server does, in fact, have a resource named jdbc/sample which is mapped to a pool named SamplePool. I also verified that my GlassFish server has a Connection pool named SamplePool. It is currently set as a javax.sql.DataSource resource type.
I was hoping someone with some more experience with JavaEE might be able to point out something obvious that I'm missing here. Or maybe something that has changed from JavaEE6 to JavaEE7 which may be the cause of my error.
Any help or suggestions would be greatly appreciated.
/
UPDATE: I just ran a Clean and Build in NetBeans and saw the following warning:
/
warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.8'`
I have JDK 1.8 installed (update 31), NetBeans 8.0.2, and GlassFish 4.1. Is this warning suggesting that eclipseLink won't work with JDK 1.8?
/
UPDATE #2: Ok, well this seems to be a very lame resolution. After trying to fix this for a couple of hours. I shut down my GlassFish server, Disconnected from my database, performed a 'Clean and Build', started everything back up again, and redeployed. Now everything seems to be working as I expect it to. I suppose something got a little wonky somewhere and only a 'clean' was able to resolve the issue. Ugh.
/
Apparently something in my build got a little funky. I shut down all my servers, did a Clean and Build and redeployed. Now, everything seems to be working.
Thanks all for your suggestions.
What I found missing in your persistence.xml is the provider. In your persistence-unit element add the following tag also
<provider> provider_name</provider>
check which provider you are using
You have specified entity manager in your post and you trying to access entity manager both are different please see
You should do like this
#PersistenceContext(name="entiyManager")
EntityManager entitymanager;
Also you need to initialized your entitymanager factory
James, I think it is a simple solution.
change from
#PersistenceUnit
to
#PersistenceUnit(unitName="JavaEE7WebinarPU")
also see https://docs.oracle.com/javaee/6/api/javax/persistence/PersistenceUnit.html
No problem buddy its very easy just add this in persistence.xml file
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JavaEE7WebinarPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/sample</jta-data-source>
<properties>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
You have an option at persistence class generated by netbeans to name your persistence unit. After naming it just do a clean and build and you will get your answer.
Here is a test case using a file from SCORM for imsmanifest,xml. This XML has been in use for about 5 or more years, and being a standard I don't want to change it unless required to get this to work.
You can find the xsd file here
The error occurs between <organizations default="CYBER4.ORG"> and <organization identifier="CYBER4.ORG">
In my project, this is the entry from my pom.xml for my jaxb version
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
to generate the Java code I ran (this is the install of xjc for Ubuntu 14.04)
$ xjc -version
xjc 2.2.4-2
$ xjc -verbose -p org.cyber4.scorm2004.xml.manifest.imscp imscp_v1p2.xsd
The output generates (amongst other things)
public class OrganizationsType {
#XmlAttribute(name = "default")
#XmlIDREF
#XmlSchemaType(name = "IDREF")
protected Object _default;
}
and
public class OrganizationType {
#XmlAttribute(name = "identifier", required = true)
#XmlJavaTypeAdapter(CollapsedStringAdapter.class)
#XmlID
#XmlSchemaType(name = "ID")
protected String identifier;
}
This is the test code
package org.cyber4.scorm2004.build;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import org.cyber4.scorm2004.xml.manifest.imscp.ManifestMetadataType;
import org.cyber4.scorm2004.xml.manifest.imscp.ManifestType;
import org.cyber4.scorm2004.xml.manifest.imscp.ObjectFactory;
import org.cyber4.scorm2004.xml.manifest.imscp.OrganizationType;
import org.cyber4.scorm2004.xml.manifest.imscp.OrganizationsType;
import org.cyber4.scorm2004.xml.manifest.imscp.ResourcesType;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
public class TestSCORMBuilder {
public static void main(String args[]) {
try {
ObjectFactory objectFactory = new ObjectFactory();
/*
* <metadata />
*/
ManifestMetadataType metadataType = objectFactory.createManifestMetadataType();
/*
* <organizations default="CYBER4.ORG">
* <organization identifier="CYBER4.ORG" />
* </organizations>
*/
// https://java.net/jira/browse/JAXB-872
OrganizationsType organizationsType = objectFactory.createOrganizationsType();
organizationsType.setDefault("CYBER4.ORG");
OrganizationType organizationType = objectFactory.createOrganizationType();
organizationType.setIdentifier("CYBER4.ORG");
organizationsType.getOrganization().add(organizationType);
/*
* <resources />
*/
ResourcesType resourcesType = objectFactory.createResourcesType();
/*
* <manifest>
* <metadata/ >
* <organizations default="CYBER4.ORG">
* <organization identifier="CYBER4.ORG" />
* </organizations>
* <resources />
* <manifest>
*/
ManifestType manifestType = objectFactory.createManifestType();
manifestType.setMetadata(metadataType);
manifestType.setOrganizations(organizationsType);
manifestType.setResources(resourcesType);
JAXBContext context = JAXBContext.newInstance("org.cyber4.scorm2004.xml.manifest.imscp");
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
"http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd");
marshaller.marshal(objectFactory.createManifest(manifestType), System.out);
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
When I run the code I get this error
javax.xml.bind.MarshalException
- with linked exception:
[com.sun.istack.internal.SAXException2: Object "CYBER4.ORG" is found in an IDREF property but this object doesnt have an ID.]
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:311)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:236)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:95)
at org.cyber4.scorm2004.build.TestSCORMBuilder.main(TestSCORMBuilder.java:73)
Caused by: com.sun.istack.internal.SAXException2: Object "CYBER4.ORG" is found in an IDREF property but this object doesnt have an ID.
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:237)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.errorMissingId(XMLSerializer.java:1045)
at com.sun.xml.internal.bind.v2.runtime.reflect.TransducedAccessor$IDREFTransducedAccessorImpl.print(TransducedAccessor.java:275)
at com.sun.xml.internal.bind.v2.runtime.reflect.TransducedAccessor$IDREFTransducedAccessorImpl.print(TransducedAccessor.java:254)
at com.sun.xml.internal.bind.v2.runtime.property.AttributeProperty.serializeAttributes(AttributeProperty.java:86)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeAttributes(ClassBeanInfoImpl.java:360)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:678)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:143)
at com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:343)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsXsiType(XMLSerializer.java:685)
at com.sun.xml.internal.bind.v2.runtime.property.SingleElementNodeProperty.serializeBody(SingleElementNodeProperty.java:143)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl$1.serializeBody(ElementBeanInfoImpl.java:145)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl$1.serializeBody(ElementBeanInfoImpl.java:115)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeBody(ElementBeanInfoImpl.java:317)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeRoot(ElementBeanInfoImpl.java:324)
at com.sun.xml.internal.bind.v2.runtime.ElementBeanInfoImpl.serializeRoot(ElementBeanInfoImpl.java:60)
at com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:483)
at com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308)
... 3 more
If I comment out line 37
organizationsType.setDefault("CYBER4.ORG");
it generates this XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<manifest xmlns="http://www.imsglobal.org/xsd/imscp_v1p1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd">
<metadata/>
<organizations>
<organization identifier="CYBER4.ORG"/>
</organizations>
<resources/>
</manifest>
but it's missing the
default="CYBER4.ORG"
in <organizations> which is required for imsmanifest.xml to be valid.
This looks like this bug but I want to be sure I haven't missed anything.
default should not contain the id of the object you want to reference, but an object with the same id than the object you want to reference.
Try to replace :
organizationsType.setDefault("CYBER4.ORG");
with :
OrganizationType o = new OrganizationType()
o.setIdentifier("CYBER4.ORG");
organizationsType.setDefault(o);
If organizationType has already been set you can maybe also try :
organizationsType.setDefault(organizationType);
My custom tag (handler is printSomething.java, which implements Tag) is running, but not producing expected output. I was expecting to see "The tag works!", but only my template text is displaying. Am I misusing the JspWriter? Code and output below.
printSomething.java
package webcert.ch08.x0804;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
public class printSomething implements Tag{
private PageContext pc;
private Tag parent;
public void setPageContext(PageContext pc){
this.pc = pc;
}
public void setParent(Tag parent){
this.parent = parent;
}
public Tag getParent(){
return parent;
}
public int doStartTag(){
try{
printMessage();
}
catch(IOException ioe){}
return Tag.SKIP_BODY;
}
public int doEndTag(){
return Tag.EVAL_PAGE;
}
public void release(){
}
public void printMessage() throws IOException{
JspWriter out = pc.getOut();
out.write("<b>The tag works!</b>");
out.print("<b>The tag works!</b>");
out.flush();
}
}
practice.jspx
<html xmlns:mytags="http://www.ets.com/mytags"
xmlns:jsp="http://java.sun.com/JSP/Page">
<jsp:output omit-xml-declaration="true"/>
<jsp:directive.page contentType="text/html"/>
<head><title>Practice JSPX</title></head>
<body>
BEFORE<br/>
<mytags:printSomething/><br/>
AFTER<br/>
</body>
</html>
web.xml
<web-app>
<jsp-config>
<taglib-uri>http://www.ets.com/mytags</taglib-uri>
<taglib-location>/WEB-INF/tags/mytags.tld</taglib-location>
</jsp-config>
</web-app>
mytags.tld
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-
jsptaglibrary_2_0.xsd"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>some tags</short-name>
<tag>
<name>printSomething</name>
<tag-class>webcert.ch08.x0804.PrintSomething</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
output
BEFORE
AFTER
Your code works for me (JBoss 7.1.1 - essentially a Tomcat for the web part).
A few changes that are important, unless they are typos in your code above:
The tag class name should be PrintSomething (capital 'P'), not printSomething (according to Java naming conventiona, but most importantly according to mytags.tld: <tag-class>webcert.ch08.x0804.PrintSomething</tag-class>)
The <jsp-config> of web.xml is syntactically wrong; should be:
<jsp-config>
<taglib>
<taglib-uri>http://www.ets.com/mytags</taglib-uri>
<taglib-location>/WEB-INF/tags/mytags.tld</taglib-location>
</taglib>
</jsp-config>
In mytags.tld there seems to be a line break between http://java.sun.com/xml/ns/j2ee/web- and jsptaglibrary_2_0.xsd. Make sure there is none in the real file!
So I am trying to work on a sample of creating a Custom tag to display
current date. I did everything stated in the example, but on starting my server its
throwing an error: did not find a Child Translator for "taglib". What needs to be fixed here?
Caused by: org.eclipse.jst.j2ee.commonarchivecore.internal.exception.ArchiveWrappedException
at org.eclipse.jst.j2ee.commonarchivecore.internal.impl.ModuleRefImpl.getDeploymentDescriptor(ModuleRefImpl.java:167)
at com.ibm.ws.runtime.component.DeployedModuleImpl.open(DeployedModuleImpl.java:237)
at com.ibm.ws.runtime.component.DeployedModuleImpl.initialize(DeployedModuleImpl.java:436)
... 53 more
Caused by: org.eclipse.jst.j2ee.commonarchivecore.internal.exception.DeploymentDescriptorLoadException: WEB-INF/web.xml
at org.eclipse.jst.j2ee.commonarchivecore.internal.impl.WARFileImpl.getDeploymentDescriptor(WARFileImpl.java:147)
at org.eclipse.jst.j2ee.commonarchivecore.internal.impl.WARFileImpl.getStandardDeploymentDescriptor(WARFileImpl.java:301)
at org.eclipse.jst.j2ee.commonarchivecore.internal.impl.EARFileImpl.getDeploymentDescriptor(EARFileImpl.java:401)
at org.eclipse.jst.j2ee.commonarchivecore.internal.impl.ModuleRefImpl.getDeploymentDescriptor(ModuleRefImpl.java:165)
... 55 more
Caused by: java.lang.IllegalStateException: Parent Translator (WebAppTranslator(web-app,1971221886)) did not find a Child Translator for "taglib".
web.xml declaration is:
<taglib>
<taglib-uri>myTags</taglib-uri>
<taglib-location>/WEB-INF/lib/DateTagLib.tld</taglib-location>
</taglib>
TLD file:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib>
<tlibversion>1.0</tlibversion>
<info>Custom Date Tag</info>
<tag>
<name>displayDate</name>
<tagclass>com.demo.DateTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Display Date</info>
</tag>
Tag Class:
package com.demo;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.*;
import java.util.*;
public class DateTag extends TagSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
public int doStartTag() throws javax.servlet.jsp.JspException {
HttpServletRequest req;
Locale locale;
HttpJspPage g;
DateFormat df;
String date;
JspWriter out;
req = (HttpServletRequest) pageContext.getRequest();
locale = req.getLocale();
df = SimpleDateFormat.getDateInstance(SimpleDateFormat.FULL, locale);
date = df.format(new java.util.Date());
try {
out = pageContext.getOut();
out.print(date);
} catch(IOException ioe){
throw new JspException("IO Error: " + ioe.getMessage());
} //end try/catch
return Tag.SKIP_BODY;
} //end doStarttag
} //end DateTag
</taglib>
Well I figured it out. Instead of doing a "static reference" to your custom tag in Deployment Descriptor, I tried referencing it dynamically from the JSP page itself and it worked.