I use the same bindings configuration for unmarshalling once using the Unmarshaler and once using a Binder. The first approach works fine, the second throws an Exception. What's the reason?
Input:
<?xml version="1.0" encoding="UTF-8"?>
<foo:root xmlns:foo="http://www.domain.org/foo">test</foo:root>
Bindings:
<?xml version="1.0"?>
<xml-bindings
xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm"
package-name="test">
<xml-schema element-form-default="QUALIFIED" namespace="http://www.domain.org/foo">
<xml-ns prefix="foo" namespace-uri="http://www.domain.org/foo" />
</xml-schema>
<java-types>
<java-type name="Root">
<xml-root-element name="root"/>
<java-attributes>
<xml-value java-attribute="text"/>
</java-attributes>
</java-type>
</java-types>
</xml-bindings>
Classes:
package test;
public class Root {
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
Demo:
Map<String, Object> jaxbContextProperties = new HashMap<String, Object>(1);
jaxbContextProperties.put(JAXBContextProperties.OXM_METADATA_SOURCE, "bindings.xml");
JAXBContext jaxbContext = JAXBContextFactory.createContext(new Class[] { Root.class}, jaxbContextProperties);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Root root = (Root)unmarshaller.unmarshal(new File("input.xml"));
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = documentBuilder.parse(new File("input.xml"));
Binder<Node> binder = jaxbContext.createBinder();
root = (Root) binder.unmarshal(document);
Output:
Exception in thread "main" javax.xml.bind.UnmarshalException - with linked exception:
[Exception [EclipseLink-25008] (Eclipse Persistence Services - 2.5.0.v20130507- 3faac2b): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor with default root element foo:root was not found in the project]
There is no problem with EclipseLink JAXB (MOXy) you just need to make sure your DocumentBuilderFactory is namespace aware by changing your code to look like the following:
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new File("input.xml"));
Related
I used a library itextsharp .
I used the following code to create PDF File and print it , but the next error occurs, what code is missing ?.
Severity Code Description Project File Line Suppression State Suppression State Error Can not resolve reference: System.Drawing, referenced by itextsharp. Please add a NuGet package or assembly reference for System.Drawing, or remove the reference to itextsharp. print_pdf
full code
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Runtime;
using Android.Widget;
using System.IO;
using Android.Content;
using iTextSharp.text;
using iTextSharp.text.pdf;
namespace print_pdf
{
[Activity(Label = "#string/app_name", Theme = "#style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
var directory = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory, "pdf").ToString();
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
var path = Path.Combine(directory, "myTestFile.pdf");
if (File.Exists(path))
{
File.Delete(path);
}
var fs = new FileStream(path, FileMode.Create);
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
document.Add(new Paragraph("Hello World"));
document.Close();
writer.Close();
fs.Close();
Java.IO.File file = new Java.IO.File(path);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(Android.Net.Uri.FromFile(file), "application/pdf");
StartActivity(intent);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
Try to add the add System.Drawing.dll as references
Right click on References --> Add Referencesc --> Assembly --> Browse... --> C:\Windows\Microsoft.NET\Framework\v4.0.30319 --> select System.Drawing.dll.
I am trying to convert existing stored proc outbound gateway xml into dsl.
<int-jdbc:stored-proc-outbound-gateway id="my-proc"
request-channel="myChannel"
data-source="datasource"
stored-procedure-name="SAMPLE_SP"
expect-single-result="false"
ignore-column-meta-data="true">
<!-- Parameter Definitions -->
<int-jdbc:sql-parameter-definition name="V_TEST_ID" direction="IN"/>
<int-jdbc:sql-parameter-definition name="O_MSG" direction="OUT"/>
<!-- Parameter Mappings Before Passing & Receiving -->
<int-jdbc:parameter name="V_TEST_ID" expression="payload.testId"/>
</int-jdbc:stored-proc-outbound-gateway>
can you please throw some light how to pass input parameters to dsl?
#Bean
public StoredProcOutboundGateway spGateway(){
StoredProcOutboundGateway storedProcOutboundGateway = new StoredProcOutboundGateway(storedProcExecutor());
storedProcOutboundGateway.setExpectSingleResult(true);
storedProcOutboundGateway.setRequiresReply(true);
return storedProcOutboundGateway;
}
#Bean
public StoredProcExecutor storedProcExecutor() {
StoredProcExecutor storedProcExecutor = new StoredProcExecutor(this.datasource);
storedProcExecutor.setStoredProcedureName("SAMPLE_SP2");
storedProcExecutor.setIsFunction(false);
storedProcExecutor.setReturningResultSetRowMappers(..);
return storedProcExecutor;
}
You need to create the procedure parameters, and the sql parameters...
#Bean
public StoredProcExecutor storedProcExecutor() {
StoredProcExecutor storedProcExecutor = new StoredProcExecutor(this.datasource);
storedProcExecutor.setStoredProcedureName("SAMPLE_SP2");
storedProcExecutor.setIsFunction(false);
storedProcExecutor.setReturningResultSetRowMappers(..);
List<ProcedureParameter> procedureParameters = new ArrayList<>();
procedureParameters.add(new ProcedureParameter("cdc_group_name", groupName, null));
// TODO set output_limit from property file
procedureParameters.add(new ProcedureParameter("output_limit", 500, null));
storedProcExecutor.setProcedureParameters(procedureParameters);
List<SqlParameter> sqlParameters = new ArrayList<>();
sqlParameters.add(new SqlParameter("cdc_group_name", Types.CHAR));
sqlParameters.add(new SqlParameter("output_limit", Types.BIGINT));
storedProcExecutor.setSqlParameters(sqlParameters);
return storedProcExecutor;
}
What I'm trying to achieve is UTF-8 encoded JSF validation and converter messages (message-bundle). Also, I would like custom resource bundle for labels, etc (resource-bundle).
I managed to create and use custom resource bundle successfully, but I have problem with defining message-bundle.
I have the following structure under src/ directory:
- com.example.i18n.resources
- FacesMsgs.properties
- FacesMsgs_de.properties
- UTF8FacesMsgs.java
- Msgs.properties
- Msgs_de.properties
- UTF8Msgs.java
Faces-config.xml snippet:
<application>
<message-bundle>com.example.i18n.resources.UTF8FacesMsgs</message-bundle>
<resource-bundle>
<base-name>com.example.i18n.resources.UTF8Msgs</base-name>
<var>msg</var>
</resource-bundle>
<locale-config>
<default-locale>de</default-locale>
</locale-config>
</application>
In my implementation I have followed the instructions given here:
Internationalization in JSF with UTF-8 encoded properties files
These are resulting classes:
public class ResourceBundleWrapper extends ResourceBundle {
public ResourceBundleWrapper(ResourceBundle parent) {
setParent(parent);
}
#Override
protected Object handleGetObject(String key) {
return parent.getObject(key);
}
#Override
public Enumeration<String> getKeys() {
return parent.getKeys();
}
}
EncodingControl.java
public class EncodingControl extends Control {
private String encoding;
private String extension;
public EncodingControl(String encoding, String extension) {
this.encoding = encoding;
this.extension = extension;
}
#Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, extension);
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
URL url = loader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
bundle = new PropertyResourceBundle(new InputStreamReader(stream, encoding));
} finally {
stream.close();
}
}
return bundle;
}
}
UTF8FacesMsgs.java
public class UTF8FacesMsgs extends ResourceBundleWrapper {
public UTF8FacesMsgs() {
super(ResourceBundle.getBundle("com.example.i18n.resources.FacesMsgs",
FacesContext.getCurrentInstance().getViewRoot().getLocale(),
new EncodingControl("UTF-8", "properties"));
}
}
UTF8Msgs.java
public class UTF8Msgs extends ResourceBundleWrapper {
public UTF8Msgs() {
super(ResourceBundle.getBundle("com.example.i18n.resources.Msgs",
FacesContext.getCurrentInstance().getViewRoot().getLocale(),
new EncodingControl("UTF-8", "properties"));
}
}
Resulting behaviour:
resource-bundle configuration seems to be working without issue: default UTF8Msgs.java is used and all labels on the page are rendered successfully.
On the other hand, behaviour with message-bundle is quite different although everything is configured likewise: when validation fails (submiting the button triggers validation) I get MissingResourceException - the default UTF8FacesMsgs.java is not used and UTF8FacesMsgs_de.java is expected.
Behaviour with changes introduced:
When I configure faces-config.xml like this (directly using properties file, not java class):
<application>
<message-bundle>com.example.i18n.resources.FacesMsgs</message-bundle>
<resource-bundle>
<base-name>com.example.i18n.resources.UTF8Msgs</base-name>
<var>msg</var>
</resource-bundle>
<locale-config>
<default-locale>de</default-locale>
</locale-config>
</application>
and delete FacesMsgs_de.properties everything runs without issue. So - default properties file is used and default java file is not.
Does anybody know what is the problem with message-bundle configuration?
When I use Struts 2.1.8, I used freemarker like this :
configure a bean in applicationContext.xml:
<bean id="freemarkerManager"
class="org.apache.struts2.views.freemarker.FreemarkerManager"/>
in the code :
try {
ServletContext servletContext = ServletActionContext.getServletContext();
System.out.println(freemarkerManager.getConfig());
Configuration configuration =
freemarkerManager.getConfiguration(servletContext);
Template template = configuration.getTemplate(templateFilePath);
File htmlFile = new File(servletContext.getRealPath(htmlFilePath));
File htmlDirectory = htmlFile.getParentFile();
if (!htmlDirectory.exists()) {
htmlDirectory.mkdirs();
}
Writer out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(htmlFile), "UTF-8"));
template.process(data, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
It worked well with Struts 2.1.8;
but now that I use Struts 2.3.15, it doesn't work; it could't load freemarker.properties. I read the source code , the problem is the fileManager is null in loadSettings() method :
try {
in = fileManager.loadFile(
ClassLoaderUtil.getResource("freemarker.properties", getClass()));
in Struts 2.1.8 loadSettings() method is like this:
InputStream in = null;
try {
in = FileManager.loadFile("freemarker.properties", FreemarkerManager.class);
It has no problem
could any one tell me how can I use freemarkerManager with Struts 2.3.15?
You must initialize freemarkerManager like this:
FreemarkerManager freemarkerManager = Dispatcher.getInstance().getContainer().getInstance(FreemarkerManager.class);
I'm using Rhino to generate XHTML but my urls are being encoded as in:
-http://www.example.com/test.html?a=b&c=d
becomes
-http://www.example.com/test.html?a=b&c=d
Failing test case as follows:
public class E4XUrlTest extends TestCase {
public void testJavascript() throws Exception {
final Context context = new ContextFactory().enterContext();
context.setLanguageVersion(Context.VERSION_1_7);
try {
final ScriptableObject scope = new Global(context);
final Script compiledScript = context.compileReader(
new StringReader("<html><body><a href={'blah.html?id=2345&name=345'}></a></body></html>"), "test", 1, null);
HashMap<String, Object> variables = new HashMap<String, Object>();
Set<Entry<String, Object>> entrySet = variables.entrySet();
for (Entry<String, Object> entry : entrySet) {
ScriptableObject.putProperty(scope, entry.getKey(), Context.javaToJS(entry.getValue(), scope));
}
Object exec = compiledScript.exec(context, scope);
String html = exec.toString();
System.out.println(html);
assertTrue(html.indexOf("id=2345&name") > 0);
} finally {
Context.exit();
}
}
}
Any ideas?
Actually the encoding "&name" is correct in xHTML since &name; is NOT a valid xHTML entity. ALL browsers understand the URL correctly. So you need to fix your test rather than looking to break your correct xHTML.
:-) stw