How can I unlock a file locked by JAXB's unmarhsaller - jaxb

I'm unmarshalling an XML file with JAXB w/Java 1.7.0_03 on Windows 7 x64 using the following code:
try (InputStream xsdStream = ConfigurationService.class.getClassLoader().getResourceAsStream(CONFIG_XSD_FILE_NAME)) {
configFile = new File(configFilePath);
if (configFile.exists()) {
context = JAXBContext.newInstance(Config.class);
Unmarshaller unMarshaller = context.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource xsdStreamSource = new StreamSource(xsdStream);
Schema schema = sf.newSchema(xsdStreamSource);
unMarshaller.setSchema(schema);
Object xmlObject = Config.class.cast(unMarshaller.unmarshal(configFile));
myConfig = (Config) xmlObject;
} else {
log.severe(configFile.getAbsolutePath() + " does not exist, can not parse configuration info from it.");
}
}
Code which calls this method subsequently deletes the XML file.
The XML file will properly delete if unmarhalling is successful. However, if the above code throws and Exception, eg. a SAXException, the XML file remains locked indefinitely and the calling code is not able to delete it with File.delete().
This feels like JAXB is not closing the resource/file in this case. Is it my responsibility to do that somehow or is this a bug?
Reviewing the javadoc for Unmarshaller did not shed any light on this and Googling this issue revealed this old, unanswered question from 2008.

SHORT ANSWER
The behaviour you have described sounds like a bug in the JAXB reference implementation. You can open a ticket using the link below:
http://java.net/jira/browse/JAXB/
Work Around
Instead of unmarshalling from a File you can unmarshal from a FileInputStream and control that it is closed correctly yourself after unmarshalling.
LONG ANSWER
I have not been able to reproduce the issue that you are seeing. I have included what I have tried below. I am using JDK 1.7.0_07 x64 for the Mac.
Configuration Service
Most of the code below is copied from your question. I have added the call to delete the input file and then output if the file still exists.
package forum14765898;
import java.io.*;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
public class ConfigurationService {
private static final String CONFIG_XSD_FILE_NAME = "forum14765898/schema.xsd";
public static void main(String[] args) throws Exception {
File configFile = null;
String configFilePath = "src/forum14765898/input.xml";
JAXBContext context;
Config myConfig;
try (InputStream xsdStream = ConfigurationService.class.getClassLoader().getResourceAsStream(CONFIG_XSD_FILE_NAME)) {
configFile = new File(configFilePath);
if (configFile.exists()) {
context = JAXBContext.newInstance(Config.class);
Unmarshaller unMarshaller = context.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource xsdStreamSource = new StreamSource(xsdStream);
Schema schema = sf.newSchema(xsdStreamSource);
unMarshaller.setSchema(schema);
Object xmlObject = Config.class.cast(unMarshaller.unmarshal(configFile));
myConfig = (Config) xmlObject;
} else {
//log.severe(configFile.getAbsolutePath() + " does not exist, can not parse configuration info from it.");
}
} catch(Exception e) {
e.printStackTrace(System.out);
}
configFile.delete();
System.out.println(configFile.exists());
}
}
schema.xsd
Below is the simple XML schema that I am using.
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<element name="config">
<complexType>
<sequence>
<element name="bar" type="int"/>
</sequence>
</complexType>
</element>
</schema>
input.xml
Below is the XML input. The bar element is not valid according to the XML schema. When a Schema is set on the Unmarshaller this document will be enough to cause an Exception to be thrown while performing an unmarshal operation.
<?xml version="1.0" encoding="UTF-8"?>
<config>
<bar>INVALID</bar>
</config>
Config
package forum14765898;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Config {
public int bar;
}
Output
Below is output from running the demo code. It shows both the validation exception and on the last line we see that the XML file was successfully deleted as it no longer exists.
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; systemId: file:/Users/bdoughan/Scratch/src/forum14765898/input.xml; lineNumber: 3; columnNumber: 23; cvc-datatype-valid.1.2.1: 'INVALID' is not a valid value for 'integer'.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:335)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:512)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:209)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:175)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)
at forum14765898.ConfigurationService.main(ConfigurationService.java:31)
Caused by: org.xml.sax.SAXParseException; systemId: file:/Users/bdoughan/Scratch/src/forum14765898/input.xml; lineNumber: 3; columnNumber: 23; cvc-datatype-valid.1.2.1: 'INVALID' is not a valid value for 'integer'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:453)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3232)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.elementLocallyValidType(XMLSchemaValidator.java:3147)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.processElementContent(XMLSchemaValidator.java:3057)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleEndElement(XMLSchemaValidator.java:2135)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.endElement(XMLSchemaValidator.java:854)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.endElement(ValidatorHandlerImpl.java:579)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.endElement(ValidatingUnmarshaller.java:91)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.endElement(SAXConnector.java:143)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1742)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2900)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:489)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:203)
... 6 more
false

public CashCountCompleted CashDeposit(String path) throws Exception {
// TODO Auto-generated method stub
CashCountCompleted cashCountCompleted = null;
File file = null;
FileInputStream inputStram = null;
try {
file = new File(path);
inputStram = new FileInputStream(file);
JAXBContext jaxbContext = JAXBContext.newInstance(CashCountCompleted.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
cashCountCompleted = (CashCountCompleted) jaxbUnmarshaller.unmarshal(inputStram);
}catch (JAXBException e) {
//throw new...
} catch (FileNotFoundException e) {
//throw new...
}finally{
try{
if(inputStram !=null){
inputStram.close();
}
}catch(Exception exception){
//throw new...
}
}
return cashCountCompleted;
}

Related

MOXy: Efficient deep copy of JAXBElement

docx4j v3.3.0 uses the following code to clone a JAXB object:
public static <T> T deepCopy(T value, JAXBContext jc) {
if (value==null) {
throw new IllegalArgumentException("Can't clone a null argument");
}
try {
#SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) value.getClass();
JAXBElement<T> contentObject = new JAXBElement<T>(new QName(clazz.getSimpleName()), clazz, value);
JAXBSource source = new JAXBSource(jc, contentObject);
JAXBElement<T> elem = jc.createUnmarshaller().unmarshal(source, clazz);
T res;
if (value instanceof JAXBElement<?>) {
#SuppressWarnings("unchecked")
T resT = (T) elem;
res = resT;
} else {
#SuppressWarnings("unchecked")
T resT = (T) elem.getValue();
res = resT;
}
return res;
} catch (JAXBException ex) {
throw new IllegalArgumentException(ex);
}
}
With MOXy v2.5.2 (which we use, since it supports Java 6) and the latest 2.6.3, attempting to clone a JAXBElement, for example:
public void testIssue212() {
CTBookmark bookmark = Context.getWmlObjectFactory().createCTBookmark();
JAXBElement<CTBookmark> el =Context.getWmlObjectFactory().createBodyBookmarkStart(bookmark);
Object o = XmlUtils.deepCopy(el);
}
results in:
[Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class javax.xml.bind.JAXBElement was not found in the project. For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.]
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.handleXMLMarshalException(JAXBUnmarshaller.java:980)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:303)
at org.docx4j.XmlUtils.deepCopy(XmlUtils.java:974)
... 25 more
Caused by: Exception [EclipseLink-25007] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.XMLMarshalException
Exception Description: A descriptor for class javax.xml.bind.JAXBElement was not found in the project. For JAXB, if the JAXBContext was bootstrapped using TypeMappingInfo[] you must call a marshal method that accepts TypeMappingInfo as an input parameter.
at org.eclipse.persistence.exceptions.XMLMarshalException.descriptorNotFoundInProject(XMLMarshalException.java:140)
at org.eclipse.persistence.internal.oxm.Context$ContextState.getSession(Context.java:145)
at org.eclipse.persistence.oxm.XMLContext$XMLContextState.getSession(XMLContext.java:795)
at org.eclipse.persistence.oxm.XMLContext$XMLContextState.getSession(XMLContext.java:1)
at org.eclipse.persistence.internal.oxm.Context.getSession(Context.java:466)
at org.eclipse.persistence.oxm.XMLContext.getSession(XMLContext.java:364)
at org.eclipse.persistence.oxm.XMLContext.getSession(XMLContext.java:1)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:466)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:695)
at org.eclipse.persistence.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:655)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:301)
... 26 more
We can workaround this with something like:
JAXBElement<T> elem;
if (Context.getJaxbImplementation().equals(JAXBImplementation.ECLIPSELINK_MOXy)
&& value instanceof JAXBElement<?>) {
elem = (JAXBElement<T>) value;
Class<?> valueClass = elem.getDeclaredType();
Marshaller mar = jc.createMarshaller();
ByteArrayOutputStream bout = new ByteArrayOutputStream(256);
mar.marshal(elem, bout);
Unmarshaller unmar = jc.createUnmarshaller();
elem = (JAXBElement<T>)unmar.unmarshal(new StreamSource(new ByteArrayInputStream(
bout.toByteArray())), valueClass);
}
but is there a better way?
Disclaimer: I'm the author of JAXB2-Basics that includes the Copyable PluginĀ“ which I think fits the task pretty well.
You may be interested Copyable Plugin, it generates reflection-free strategic copy methods.
Activation in Maven (see also Using JAXB2 Basics Plugins):
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<configuration>
<extension>true</extension>
<args>
<arg>-Xcopyable</arg>
</args>
<plugins>
<plugin>
<groupId>org.jvnet.jaxb2_commons</groupId>
<artifactId>jaxb2-basics</artifactId>
</plugin>
</plugins>
</configuration>
</plugin>
The plugin then generates deep, reflection-free and strategy-based clone and copyTo methods (see below). This gives you very efficient copying. You can also "copy" to an existing instance or customize what and how should be copied by specifying your own strategy. For instance, you may want to avoid copying id fields or something like that. Generated code also knows how to deal with JAXBElement.
This is a kind of code generated:
public Object clone() {
return copyTo(createNewInstance());
}
public Object copyTo(Object target) {
final CopyStrategy2 strategy = JAXBCopyStrategy.INSTANCE;
return copyTo(null, target, strategy);
}
public Object copyTo(ObjectLocator locator, Object target, CopyStrategy2 strategy) {
final Object draftCopy = ((target == null)?createNewInstance():target);
if (draftCopy instanceof IssueJIIB35) {
final IssueJIIB35 copy = ((IssueJIIB35) draftCopy);
{
Boolean nameShouldBeCopiedAndSet = strategy.shouldBeCopiedAndSet(locator, this.isSetName());
if (nameShouldBeCopiedAndSet == Boolean.TRUE) {
String sourceName;
sourceName = this.getName();
String copyName = ((String) strategy.copy(LocatorUtils.property(locator, "name", sourceName), sourceName, this.isSetName()));
copy.setName(copyName);
} else {
if (nameShouldBeCopiedAndSet == Boolean.FALSE) {
copy.name = null;
}
}
}
// ...
}
return draftCopy;
}
public Object createNewInstance() {
return new IssueJIIB35();
}
Might look a bit weird/cumbersome but it takes quite a few JAXB peculiarities into account.
Turns out the docx4j code introduced in https://github.com/plutext/docx4j/pull/163 had issues copying a JAXBElement, whether using MOXy or Sun/Oracle reference implementation.
https://github.com/plutext/docx4j/commit/b5d8b4722e814945e502da9f0516d59c498b64bb fixes it

How do I access the result of FetchXML as XML rather than entities?

In the past my FetchXML was delivering me the result in xml format, but since I change server this function string ret = service.Fetch(fetchXml); no longer works, so I had to resort with another solution, but this one give me more work to build a XML file.
Fetch String example:
string fetchXml = #"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='account'>
<attribute name='name'/>
<attribute name='telephone1'/>
</entity>
</fetch>";
EntityCollection ec = organizationProxy.RetrieveMultiple(new FetchExpression(fetchXml));
XElement rootXml = new XElement("account");
foreach (Entity account in ec.Entities)
{
if (account.Attributes.Contains("name"))
{
rootXml.Add(new XElement("name", account.Attributes.Contains("name") ? account["name"] : ""));
rootXml.Add(new XElement("telephone1", account.Attributes.Contains("telephone1") ? account["telephone1"] : ""));
}
}
res.XmlContent = rootXml.ToString();
So what I'm doing here is build the XML string by hand, and I know that CRM can deliver the result in XML, I have googleit (http://social.msdn.microsoft.com/Forums/en-US/af4f0251-7306-4d76-863d-9508d88c1b68/dynamic-crm-2011-fetchxml-results-into-xmltextreader-to-build-an-xml-output) But this give me more work than my code. Or there is no other solution?
In the past I have used Serialization to convert objects to XML and back again.
To convert to XML
public static string SerializeAnObject(object _object)
{
System.Xml.XmlDocument doc = new XmlDocument();
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(_object.GetType());
System.IO.MemoryStream stream = new System.IO.MemoryStream();
try
{
serializer.Serialize(stream, _object);
stream.Position = 0;
doc.Load(stream);
return doc.InnerXml;
}
catch (Exception ex)
{
throw;
}
finally
{
stream.Close();
stream.Dispose();
}
}
To convert it back into an Entity Collection (or other object)
public static object DeSerializeAnObject(string xmlOfAnObject, Type _objectType)
{
System.IO.StringReader read = new StringReader(xmlOfAnObject);
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(_objectType);
System.Xml.XmlReader reader = new XmlTextReader(read);
try
{
return (object)serializer.Deserialize(reader);
}
catch (Exception ex)
{
throw;
}
finally
{
read.Close();
read.Dispose();
read = null;
}
}

Getting null pointer exception while loading schema

public class TestValidatorSample {
public static void main(String aa[]) throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder parser = dbf.newDocumentBuilder();
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// /test_elements.xsd
Schema schema = factory.newSchema(new StreamSource(TestValidatorSample.class.getResource(
"/xsds/pakagename/test_elements.xsd").toString()));
Validator validator = schema.newValidator();
DOMSource domsrc = new DOMSource(parser.parse(new InputSource("test-example.xml")));
try {
validator.validate(domsrc);
System.out.println("Validation successfull!!!");
// System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println("Validation not successfull!!!");
// System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
}
}
}
Exception in thread "main" java.lang.NullPointerException at line 47.
I am getting a nullpointer(as mentioned above) exception while loading a schema.
In the above code snippet I am trying to load a schema which will be used to validate xmls generated in my application .
Can anybody please help me to find out why I am getting null pointer exception ?

read .properties file in static code of a JSF web application

I would like to get DB connection parameters from a properties file in a static block. The properties file location is WEB-INF/classes/db.properties.
I will prefer to use getResourceAsStream() method. I have tried many ways, but they all returned null.
private static Properties prop = new Properties();
static{
try {
FacesContext facesContext = FacesContext.getCurrentInstance();
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
InputStream inputStream = servletContext.getResourceAsStream("/db.properties");
InputStream is = prop.getClass().getResourceAsStream("/db.properties");
if(inputStream!=null){//it is null
prop.load(inputStream);
}
if(is!=null){//it is null
prop.load(is);
}
} catch (Exception e) {
e.printStackTrace();
}
}
How is this caused and how can I solve it?
As Thufir wrote in a comment, there is a nice tutorial from reading properties from Java code: http://jaitechwriteups.blogspot.ca/2007/01/how-to-read-properties-file-in-web.html
/**
* Some Method
*
* #throws IOException
*
*/
public void doSomeOperation() throws IOException {
// Get the inputStream
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("myApp.properties");
Properties properties = new Properties();
System.out.println("InputStream is: " + inputStream);
// load the inputStream using the Properties
properties.load(inputStream);
// get the value of the property
String propValue = properties.getProperty("abc");
System.out.println("Property value is: " + propValue);
}
InputStream inputStream = servletContext.getResourceAsStream("/db.properties");
This attempt expects the file to be in /WebContent/db.properties.
InputStream is = prop.getClass().getResourceAsStream("/db.properties");
This attempt expects it to be in at least the same archive (JAR) as the java.util.Properties class.
Neither of those attempts reads the file which you've placed in /WEB-INF/classes/db.properties. You can fix this problem in basically 2 ways.
Move it directly in the /WEB-INF folder as /WEB-INF/db.properties and load it as follows:
InputStream input = externalContext.getResourceAsStream("/WEB-INF/db.properties");
(note that you don't need to haul the ServletContext from under the JSF's hoods; there's already a delegate method for that)
Load it relative to the class which is also present in /WEB-INF/classes, e.g. the current managed bean class.
InputStream input = Bean.class.getResourceAsStream("/db.properties");
Or just use the context classloader, it has access to everything.
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
(note the lack of the / prefix)
See also:
Where to place and how to read configuration resource files in servlet based application?

when i am using this code it gives error [duplicate]

This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
when i am using this code it gives error
public class SharedContactServiceImpl extends RemoteServiceServlet implements
SharedContactService {
/**
*
*/
private static final long serialVersionUID = 1L;
public ContactEntry createContact()throws IllegalArgumentException {
// Create the entry to insert
ContactsService myService = new ContactsService("exampleCo-exampleApp-1");
try {
myService.setUserCredentials("abc#in.gappsdemo.in", "xyz#123");
} catch (AuthenticationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String name = "nehaContact";
String notes = "this is some notes from gdata API client";
ContactEntry contact = new ContactEntry();
contact.setTitle(new PlainTextConstruct(name));
contact.setContent(new PlainTextConstruct(notes));
Email primaryMail = new Email();
primaryMail.setAddress("demo#in.gappsdemo.in");
primaryMail.setRel("http://schemas.google.com/g/2005#home");
primaryMail.setPrimary(true);
contact.addEmailAddress(primaryMail);
Email secondaryMail = new Email();
secondaryMail.setAddress("demo#in.gappsdemo.in");
secondaryMail.setRel("http://schemas.google.com/g/2005#work");
secondaryMail.setPrimary(false);
contact.addEmailAddress(secondaryMail);
ExtendedProperty favouriteFlower = new ExtendedProperty();
favouriteFlower.setName("favourite flower");
favouriteFlower.setValue("daisy");
contact.addExtendedProperty(favouriteFlower);
ExtendedProperty sportsProperty = new ExtendedProperty();
sportsProperty.setName("sports");
XmlBlob sportKinds = new XmlBlob();
sportKinds.setBlob(new String("<dance><salsa/><ballroom dancing/><dance/>"));
sportsProperty.setXmlBlob(sportKinds);
contact.addExtendedProperty(sportsProperty);
System.out.println(contact);
// Ask the service to insert the new entry
try{
System.out.println("Inside try Block:");
URL postUrl = new URL("https://www.google.com/m8/feeds/contacts/demo#in.gappsdemo.in/full");
System.out.println("Inside try Block1:");
return myService.insert(postUrl, contact);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return contact;
}
}
I am using this code on server-side it gives error :
[ERROR] [simplerpc] - Line 9: No source code is available for type com.google.gdata.data.contacts.ContactEntry; did you forget to inherit a required module?
That error is occuring because you are using com.google.gdata.data.contacts.ContactEntry in your client side code. (Its being returned to the client code from your service) Client side objects get compiled into Javascript by GWT. To fix it you need to tell GWT where to find all the source for objects that are converted to Javascript (all client side stuff).
To do that you need to add something like <source path='events'/> in "YourProject.gwt.xml". Below is an example: (Using helloMVP)
1. Created new package 'events' in 'com.hellomvp' (com.hellomvp.events)
2. Added <source path='events'/> to "HelloMVP.gwt.xml Now it looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<module rename-to="helloMVP">
<inherits name='com.google.gwt.user.User'/>
<inherits name='com.google.gwt.user.theme.standard.Standard'/>
<inherits name="com.google.gwt.activity.Activity"/>
<inherits name="com.google.gwt.place.Place"/>
<entry-point class='com.hellomvp.client.HelloMVP'/>
<replace-with class="com.hellomvp.client.ClientFactoryImpl">
<when-type-is class="com.hellomvp.client.ClientFactory"/>
</replace-with>
<!-- Specify the paths for translatable code -->
<source path='client'/>
<source path='shared'/>
<source path='events'/>
</module>
Hope this helps.

Resources