Org.eclipse.persistence.exceptions.ConversionException with INTERVALSD

I have this issue with eclipselink 1.2.0.v20091016-r5565 and Oracle 11gR2
column is INTERVAL DAY(5) TO SECOND(1) in database
in EJB has been generated as Integer
any workaround ???
thank u
patrick
[EL Warning]: Exception [EclipseLink-3002] (Eclipse Persistence Services - 1.2.0.v20091016-r5565): org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [0 0:0:2.400000000], of class [class oracle.sql.INTERVALDS], from mapping [org.eclipse.persistence.mappings.DirectToFieldMapping[flushElapsed-->sys.WRM$_SNAPSHOT.FLUSH_ELAPSED]] with descriptor [RelationalDescriptor(org.eclipse.persistence.extension.dynamic.WrmSnapshot --> [DatabaseTable(sys.WRM$_SNAPSHOT)])], could not be converted to [class java.lang.Integer].
Exception in thread "main" Local Exception Stack:
Exception [EclipseLink-3002] (Eclipse Persistence Services - 1.2.0.v20091016-r5565): org.eclipse.persistence.exceptions.ConversionException
Exception Description: The object [0 0:0:2.400000000], of class [class oracle.sql.INTERVALDS], from mapping [org.eclipse.persistence.mappings.DirectToFieldMapping[flushElapsed-->sys.WRM$_SNAPSHOT.FLUSH_ELAPSED]] with descriptor [RelationalDescriptor(org.eclipse.persistence.extension.dynamic.WrmSnapshot --> [DatabaseTable(sys.WRM$_SNAPSHOT)])], could not be converted to [class java.lang.Integer].
at org.eclipse.persistence.exceptions.ConversionException.couldNotBeConverted(ConversionException.java:71)
at org.eclipse.persistence.internal.helper.ConversionManager.convertObjectToInteger(ConversionManager.java:539
package org.eclipse.persistence.extension.dynamic;
import java.io.Serializable;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Entity
@NamedQueries({
@NamedQuery(name = "WrmSnapshot.findAll", query = "select o from WrmSnapshot o")
@Table(name = "WRM$_SNAPSHOT")
@IdClass(WrmSnapshotPK.class)
public class WrmSnapshot implements Serializable {
@Column(name="BEGIN_INTERVAL_TIME", nullable = false)
private Timestamp beginIntervalTime;
@Column(name="BL_MOVED")
private Long blMoved;
@Id
@Column(nullable = false)
private Long dbid;
@Column(name="END_INTERVAL_TIME", nullable = false)
private Timestamp endIntervalTime;
@Column(name="ERROR_COUNT")
private Long errorCount;
@Column(name="FLUSH_ELAPSED")
private Integer flushElapsed;
@Id
@Column(name="INSTANCE_NUMBER", nullable = false)
private Long instanceNumber;
@Column(name="SNAP_FLAG")
private Long snapFlag;
@Id
@Column(name="SNAP_ID", nullable = false)
private Long snapId;
@Column(name="SNAP_LEVEL")

It probably depends on which tool are you using to generate EJB's from tables, but i don't think it's possible to make it use String for INTERVAL fields.
I don't have much experience with working with INTERVAL fields but my guess is that they are converted to Lob's instead of byte array (Lob actually make sense as a representation of byte array). My other guess is that if you choose String for your field then when read from DB it is first converted to Lob then to String, but proper mapping for INTERVAL field is Lob. Number field can be converted to String but its not a "proper" way to handle Number fields.

Similar Messages

  • (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DescriptorException

    We are upgrading various webservices to Weblogic 12c. We are running i a very annoying issue where the webservice can't be deployed on 12c whenever there is an element which is nillable and the type is an Enumartion. For example : <xsd:element name="adresType" type="bg:AdresType" nillable="true" minOccurs="0" /> where AdresType is :
        <xsd:simpleType name="AdresType">
            <xsd:restriction base="xsd:string">
                <xsd:enumeration value="DAILY" />
                <xsd:enumeration value="OFFICIAL" />
                <xsd:enumeration value="CORRESPONDENCE" />
            </xsd:restriction>
        </xsd:simpleType>
    Putting eclipselink 2.5.0 on the class path solves the problem. However, i am using a shared environment and they don't allow me to change the classpath ;-(
    I tried putting 'prefer-application-package', ' prefer-web-inf-classes' etcetera in the weblogic.xml. Doesn't work.
    Can anybody help me out?
    regards
    Johan van Kampen

    I've filed bug 382029 and checked in a fix into trunk (2.5) to fix the error you are getting so that it prints off the pk class causing the exception instead of 202 (which is the error code).
    The reason it seems to work is that the error occurs at the tail end of initializing the descriptor for PlanEffectiveData. When you continue on, it doesn't retry initializing this descriptor and will proceed. What hasn't been initialized are the fetch groups and the primary key class for the PlanEffectiveData; you will likely run into an issue if you attempt to use an em.find on the PlanEffectiveData class.
    I will have to test what the issue is, but I suspect it is a processing problem where the PersistableId IDClass isn't being replaced with the TemporalId class. Can you try removing the IDClass annotations from HistorySlice and seeing if you get this same exception? Presumably you will have to exclude any Entities that directly extend HistorySlice to test that it works correctly.
    Regards,
    Chris

  • Warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.7'

    warning: Supported source version 'RELEASE_6' from annotation processor 'org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor' less than -source '1.7'
    Note: Creating static metadata factory ...
    An annotation processor threw an uncaught exception.
    Consult the following stack trace for details.
    java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/PersistenceException
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
        at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
        at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
        at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
        at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        at java.lang.Class.getDeclaredFields0(Native Method)
        at java.lang.Class.privateGetDeclaredFields(Class.java:2570)
        at java.lang.Class.getDeclaredField(Class.java:2055)
        at org.eclipse.persistence.internal.security.PrivilegedAccessHelper.findDeclaredField(PrivilegedAccessHelper.java:67)
        at org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getField(PrivilegedAccessHelper.java:223)
        at org.eclipse.persistence.internal.helper.Helper.getField(Helper.java:980)
        at org.eclipse.persistence.internal.descriptors.InstanceVariableAttributeAccessor.initializeAttributes(InstanceVariableAttributeAccessor.java:100)
        at org.eclipse.persistence.mappings.DatabaseMapping.preInitialize(DatabaseMapping.java:1455)
        at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.preInitialize(AbstractDirectMapping.java:913)
        at org.eclipse.persistence.oxm.mappings.XMLDirectMapping.preInitialize(XMLDirectMapping.java:439)
        at org.eclipse.persistence.oxm.XMLDescriptor.preInitialize(XMLDescriptor.java:559)
        at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:649)
        at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:632)
        at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:568)
        at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.postConnectDatasource(DatabaseSessionImpl.java:799)
        at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.login(DatabaseSessionImpl.java:756)
        at org.eclipse.persistence.oxm.XMLContext$XMLContextState.setupSession(XMLContext.java:738)
        at org.eclipse.persistence.oxm.XMLContext$XMLContextState.setupSession(XMLContext.java:1)
        at org.eclipse.persistence.internal.oxm.Context$ContextState.<init>(Context.java:86)
        at org.eclipse.persistence.oxm.XMLContext$XMLContextState.<init>(XMLContext.java:702)
        at org.eclipse.persistence.oxm.XMLContext.<init>(XMLContext.java:192)
        at org.eclipse.persistence.oxm.XMLContext.<init>(XMLContext.java:164)
        at org.eclipse.persistence.oxm.XMLContext.<init>(XMLContext.java:154)
        at org.eclipse.persistence.internal.jpa.modelgen.objects.PersistenceXMLMappings.createXMLContext(PersistenceXMLMappings.java:139)
        at org.eclipse.persistence.internal.jpa.modelgen.objects.PersistenceXMLMappings.createXML2_1Context(PersistenceXMLMappings.java:123)
        at org.eclipse.persistence.internal.jpa.modelgen.objects.PersistenceUnitReader.initPersistenceUnits(PersistenceUnitReader.java:178)
        at org.eclipse.persistence.internal.jpa.modelgen.objects.PersistenceUnitReader.<init>(PersistenceUnitReader.java:72)
        at org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor.process(CanonicalModelProcessor.java:376)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:794)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment.discoverAndRunProcs(JavacProcessingEnvironment.java:705)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment.access$1800(JavacProcessingEnvironment.java:91)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment$Round.run(JavacProcessingEnvironment.java:1035)
        at com.sun.tools.javac.processing.JavacProcessingEnvironment.doProcessing(JavacProcessingEnvironment.java:1176)
        at com.sun.tools.javac.main.JavaCompiler.processAnnotations(JavaCompiler.java:1173)
        at com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:859)
        at com.sun.tools.javac.main.Main.compile(Main.java:523)
        at com.sun.tools.javac.main.Main.compile(Main.java:381)..................
    I'm an undergraduate student in software engineering. I worked with EE and tried to built a EJB Application. It worked. But when i connected it to database using persistence it getting error as mentioned.
    When i change my source Binary Format to jdk6 it runs without errors. What can i do for this without downgrading jdk version?

    I resolved my problem. The issue was the version of EclipseLink that I had specified in my pom.xml. Version 2.0.1 has an issue with the meta-model generation and, in fact, I wanted to be using version 2.1.1. Once I changed to 2.1.1 everything compiled correctly.
    Just make certain that you include the correct EclipseLink repository.
    <repository>
    <id>EclipseLink Repo</id>
    <name>EclipseLink Repository for the JPA implementation</name>
    <url>http://www.eclipse.org/downloads/download.php?r=1&amp;nf=1&amp;file=/rt/eclipselink/maven.repo</url>
    </repository>

  • Import org.eclipse.persistence.sessions.Project ?

    Hello,
    I have a legacy mapping file that is a Java file and its class extends org.eclipse.persistence.sessions.Project.
    This file maintains the toplink mapping and is the only toplink configuration of the project. During its inception, the webgain workbench was used to create the file. Later, it was totally hand maintained.
    Now, we would like to bring this to be managed in the JDeveloper Toplink workbench.
    Could you please tell if this is possible.
    Thanks,
    Raj

    Username and password supplied in the persistence.xml file should be for the Database configured user. This user is not an OS user.
    --Gordon                                                                                                                                                                                                                                                                                           

  • Java.io.InvalidClassException: org.eclipse.persistence.internal.helper.DatabaseTable

    Hello im using weblogic 10.3.5 and jpa 2, but i cant make that my project works coz i have this issue....
    56177847, local class serialVersionUID = -8219935847209476671 java.io.InvalidClassException: org.eclipse.persistence.internal.helper.DatabaseTable; local class incompatible: stream classdesc serialVersionUID = 740837816705
    Can somebody help me please?
    Thanks.

    Just a guess because there is so little information given but perhaps you are attempting to deserialize a class that should not have been serialized in the first place.

  • Java.io.InvalidClassException: org.eclipse.persistence.internal.indirection.DatabaseValueHolder; local class incompatible: stream classdesc serialVersionUID = -6893195210780291759, local class serialVersionUID = 1128857921468654749

    Hi,
    I recently create a webservice application.
    It work fine when the server is implemented as java application. But when rewritten as web application( *.war),  the deploiement work on WLS.
    However it throws java.io.InvalidClassException: org.eclipse.persistence.internal.indirection.DatabaseValueHolder; local class incompatible: stream classdesc serialVersionUID = -6893195210780291759, local class serialVersionUID = 1128857921468654749 error when the client start consumming the web service methods.
    I add both eclipselink-javax.persistence-2.0.jar and eclipselink-2.0.2.jar(which are also used in the server side) in $WL_HOME/wlserver_10.3/common/deployable-libraries, that doesn't solve the problem yet.
    Any help will be appreciated, cheers.

    Abenk,
    This looks like a serial version mismatch due to multiple Eclipselink.jar files. Check if you have any under server/internal/ext folder.
    What are you putting in your classpath? Is there a "jrf.jar" and is it getting picked up first? Does this Jrf.jar have an entry of Eclipselink jar?
    Try to check the classpath of the jars used by Weblogic and remove any redundant Eclipselink/Toplink jars.
    What is the complete version of your Weblogic Server ?

  • Could not find plugin org.eclipse.persistence.jpa.equinox.weaving

    one of my rcp project 's product file defined
    <plugin id="org.eclipse.persistence.jpa.equinox.weaving" fragment="true"/>
    it was working for the helio javaee IDE
    I download helio javaee ide again,
    i was supriseingly found out , this plugin does not exist anymore.
    how do I add the plugin
    org.eclipse.persistence.jpa.equinox.weaving
    for helio javaee ?
    Any hints will be more than welcome

    http://www.eclipse.org/equinox/weaving/
    > one of my rcp project 's product file defined
    > <plugin id="org.eclipse.persistence.jpa.equinox.weaving" fragment="true"/>
    > it was working for the helio javaee IDE
    > I download helio javaee ide again,
    > i was supriseingly found out , this plugin does not exist anymore.
    >
    > how do I add the plugin
    > org.eclipse.persistence.jpa.equinox.weaving
    > for helio javaee ?
    >
    > Any hints will be more than welcome

  • JPA Error "No Persistence provider for EntityManager",using org.eclipse.per

    Hello Colleagues,
    I have created JPA project, with out any error have done mapping also. with orm.xml and persistense .xml
    I am getting No Persistence provider for EntityManager error when calling Entity Manager in Entity class
    Error >>> EntityManagerFactory emf = Persistence.createEntityManagerFactory("Personalization_JPA");
    { No Persistence provider for EntityManager named Personalization_JPA }
    Persistence Provider as "org.eclipse.persistence.jpa.PersistenceProvider
    In persistence.xml for my JPA project , I have included following in respective tabs
    1) GENERAL Tab of Persistence.xml
    a) Persistence Provider as "org.eclipse.persistence.jpa.PersistenceProvider"
    b) In Managed classes included my Entity class and test application that calls the entity manager
    c) orm.xml in xml mapping files
    2) Connections Tab of Persistence.xml
    a) Transaction Type as Resource Local, not using any JTA datasourse name in database field
    3) Properties Tab of Persistence.xml
    property name="driver" value="com.sap.dbtech.jdbc.DriverSapDB"
    property name="url" value="jdbc:sapdb://localhost/w15"
    property name="username" value="SAPW15DB"
    property name="password" value="sapsapr3"
    If anything wrong is specified please kindly inform me.

    Hello colleague,
    As per your suggestion I removed Persistence Provider as "org.eclipse.persistence.jpa.PersistenceProvider", made it blank in persistence.xml, but still I get the same error saying No Persistence provider for EntityManager, please have a look at other attributes of persistence.xml
    In persistence.xml for my JPA project , I have included following in respective tabs
    1) GENERAL Tab of Persistence.xml
    a) Persistence Provider as  blank or "org.eclipse.persistence.jpa.PersistenceProvider" makes no difference
    b) In Managed classes included my Entity class and test application that calls the entity manager
    c) orm.xml in xml mapping files
    2) Connections Tab of Persistence.xml
    a) Transaction Type as Resource Local, not using any JTA datasourse name in database field
    3) Properties Tab of Persistence.xml (connecting to maxdb, so is this necessary or not )
    property name="driver" value="com.sap.dbtech.jdbc.DriverSapDB"
    property name="url" value="jdbc:sapdb://localhost/w15"
    property name="username" value="SAPW15DB"
    property name="password" value="sapsapr3"
    If anything wrong is specified please kindly inform me.

  • EclipseLink persistence provider issue with weblogic 10.3

    Hi All,
    I have been trying to deploy and run an EAR in weblogic but when I run the application I get the following warning: WARNING: Found unrecognized persistence provider "org.eclipse.persistence.jpa.PersistenceProvider" in place of OpenJPA provider. This provider's properties will not be used.
    The following is my persistence.xml:
    <persistence 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 persistence_1_0.xsd" version="1.0">
    <persistence-unit name="default" transaction-type="JTA">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <jta-data-source>DataSourceName</jta-data-source>
    <class>oracle.communications.platform.entity.impl.CharacteristicSpecificationDAO</class>
    <properties>
    <property name="eclipselink.logging.level" value="FINEST" />
    <property name="eclipselink.target-database" value="org.eclipse.persistence.platform.database.oracle.OraclePlatform" />
    <property name="eclipselink.target-server" value="WebLogic_10" />
    <property name="eclipselink.session-event-listener" value="oracle.communications.platform.persistence.impl.PomsSessionEventListener" />
    <property name="eclipselink.session.customizer" value="oracle.communications.platform.util.EclipseLinkSessionCustomizer" />
    <property name="poms.cache.coordination.implementation" value="jms" />
    <property name="poms.cache.coordination.ipaddress" value="10.178.139.64" />
    <property name="poms.cache.coordination.port" value="7101" />
    <property name="poms.cache.coordination.multicast.group.address" value="226.10.12.64" />
    <property name="poms.cache.coordination.multicast.port" value="3121" />
    <property name="poms.cache.coordination.topic.connection.factory.name" value="EclipseLinkTopicConnectionFactory" />
    <property name="poms.cache.coordination.topic.name" value="EclipseLinkTopic" />
    <property name="poms.cache.coordination.username" value="weblogic" />
    <property name="poms.cache.coordination.password" value="weblogic" />
    <property name="poms.cache.coordination.password.encrypted" value="false" />
    </properties>
    </persistence-unit>
    </persistence>
    I have written a session customizer that reads properties from the persistence.xml and initializes stuff. But because of the warning i mentioned earlier... I am getting null for all property entries.
    I moved the eclipselink jar entry up ahead of openjpa jar entry in weblogic.server.modules_10.3.1.0.xml and refcount.xml in /modules/features directory. I am still getting the same problem.
    I read in many posts for workarounds for this issue but didnt find anything which worked for me. I would be grateful if someone could provide me a hint as to how to make it work.
    Thanks in advance,
    Prashanth.

    Prashanth,
    Hi, there should be no issue running EclipseLink on WebLogic while you see this warning. If you are getting null properties it may be the result of another issue, could you post specific exceptions and the part of your client code that is having a problem.
    1) The warning below normally appears only when running your persistence unit with an "application managed" JTA datasource as opposed to a "globally defined server scoped datasource". Even then it can be ignored as there are still parts of WebLogic that depend on OpenJPA. Even though the warning states that properties are ignored - they are not and you should see your persistence unit loaded properly.
    I encountered this issue when running an "application managed" JTA - here is an extract of the log showing the warning and the full functioning of the pu later - the persistence unit and example code can be found on the weblogic tutorial examples link below
    "[EL Finer]: 2008.10.29 13:03:55.565--ClientSession(30346337)--Thread(Thread[[ACTIVE] ExecuteThread: '20' for queue: 'weblogic.kernel.Default (self-tuning)',5,Pooled Threads])--client released
    WARNING: Found unrecognized persistence provider "org.eclipse.persistence.jpa.PersistenceProvider" in place of OpenJPA provider. This provider's properties will not be used.
    [EL Info]: 2008.10.29 13:03:56.079--ServerSession(14772987)--EclipseLink, version: Eclipse Persistence Services - 1.1.0 (Build 20081023)
    [EL Info]: 2008.10.29 13:03:56.391--ServerSession(14772987)--file:/C:/view_w34r1a/examples/org.eclipse.persistence.example.jpa.server.weblogic.enterpriseEJB/build/classes/-exampleLocal login successful
    15 Entities in storage: 15
    [EL ExampleLocal EM]: enterprise: Object: [email protected]( id: 6 state: null parent: HashSet@15794734 references: HashSet@15794734)
    [EL ExampleLocal EM]: enterprise: Object: [email protected]( id: 26 state: null parent: HashSet@8800655 references: HashSet@8800655)
    I raised the following minor issue with our WebLogic Server team in Oct for reference - however this warning did not affect proper functioning of EclipseLink JPA.
    https://bug.oraclecorp.com/pls/bug/webbug_edit.edit_info_top?rptno=7520161
    You may reference the following tutorial on running EclipseLink JPA on WebLogic 10.3, it details all the steps necessary to get a JTA container managed persistence unit running via a stateless session bean and a servlet client. It also details and links to application managed datasource configuration details.
    http://wiki.eclipse.org/EclipseLink/Examples/JPA/WebLogic_Web_Tutorial
    2) eclipselink.jar location in WebLogic?
    The eclipselink.jar library should stay in the modules or patch_* directory depending on whether you are running a standalone WebLogic server or as part of a Fusion Middleware JDeveloper environment.
    See the following link that details deployment options for WebLogic and EclipseLink
    http://wiki.eclipse.org/EclipseLink/Examples/JPA/WebLogic_Web_Tutorial#EclipseLink_JAR_location
    Note: I have not modified the load order of EclipseLink, OpenJPA or Kodo, I am running all including this version of OpenJPA in my modules directory. [org.apache.openjpa_1.0.0.0_1-1-1-SNAPSHOT.jar]
    3) I noticed that you are defining the target-database property in your persistence unti but you are running as JTA not RESOURCE_LOCAL. This property can be removed if your JTA datasource is defined as a Transactional server scoped datasource via the WebLogic console.
    thank you
    /michael
    http://www.eclipselink.org

  • Org.eclipselink.persistence.jdbc.... deprecated?

    Hello,
    We use javax.persistence_1.0.0.0_1-0-2.jar and org.eclipse.persistence_1.0.0.0_1-2-0.jar. We have org.eclipselink.persistence.jdbc.user/url/driver/password in persistence.xml with "org.eclipse.persistence.jpa.PersistenceProvider" being the provider. But we started to see WARNING complain about org.eclipselink.persistence.jdbc... being deprecated and suggested using javax.persistence.jdbc...
    Could someone confirm that javax.persistence.jdbc... should replace org.eclipselink.persistence.jdbc... in persistence.xml file? Thanks.

    All parameters needed to make connection are going to be standardized in incoming JPA 2.0.
    If you take a look at chapter "8.2.1.9 properties" of "[Java Persistence 2.0, Proposed Final Draft 2|http://jcp.org/aboutJava/communityprocess/pfd/jsr317/index2.html]" you will find them there. And since EclipseLink is being referential implementation for JPA 2.0 its not surprise that old ones are being deprecated.

  • Search replace Word doc - Getting Erro : org.eclipse.swt.SWTException:

    Hi
    All
    I'm runing this Java class by a jsp to Search and Replace and saveAs a word document, when run the fisrt time it works OK, but if I run again I got this error:
    What is happing there?
    Following the Error and Source Java.
    Thanks
    11:59:49,234 ERROR [[jsp]] Servlet.service() for servlet jsp threw exception
    org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(SWT.java:3563)
    at org.eclipse.swt.SWT.error(SWT.java:3481)
    at org.eclipse.swt.SWT.error(SWT.java:3452)
    at org.eclipse.swt.widgets.Widget.error(Widget.java:432)
    at org.eclipse.swt.widgets.Shell.<init>(Shell.java:274)
    at org.eclipse.swt.widgets.Shell.<init>(Shell.java:265)
    at org.eclipse.swt.widgets.Shell.<init>(Shell.java:218)
    at org.eclipse.swt.widgets.Shell.<init>(Shell.java:156)
    at br.com.tryblob.view.WordSearchReplace.<init>(WordSearchReplace.java:36)
    at org.apache.jsp.replacedoc_jsp._jspService(replacedoc_jsp.java:48)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:175)
    at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:74)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
    at java.lang.Thread.run(Unknown Source)
    12:00:56,843 ERROR [[jsp]] Servlet.service() for servlet jsp threw exception
    org.eclipse.swt.SWTException: Invalid thread access
    at org.eclipse.swt.SWT.error(SWT.java:3563)
    at org.eclipse.swt.SWT.error(SWT.java:3481)
    at org.eclipse.swt.SWT.error(SWT.java:3452)
    at org.eclipse.swt.widgets.Widget.error(Widget.java:432)
    at org.eclipse.swt.widgets.Shell.<init>(Shell.java:274)
    at org.eclipse.swt.widgets.Shell.<init>(Shell.java:265)
    at org.eclipse.swt.widgets.Shell.<init>(Shell.java:218)
    at org.eclipse.swt.widgets.Shell.<init>(Shell.java:156)
    at br.com.tryblob.view.WordSearchReplace.<init>(WordSearchReplace.java:36)
    at org.apache.jsp.replacedoc_jsp._jspService(replacedoc_jsp.java:48)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
    at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:175)
    at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:74)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:869)
    at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:664)
    at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
    at org.apache.tomcat.util.net.MasterSlaveWorkerThread.run(MasterSlaveWorkerThread.java:112)
    at java.lang.Thread.run(Unknown Source)
    ==================JAVA CLASS=====================
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.SWTException;
    import org.eclipse.swt.internal.ole.win32.TYPEATTR;
    import org.eclipse.swt.ole.win32.OLE;
    import org.eclipse.swt.ole.win32.OleAutomation;
    import org.eclipse.swt.ole.win32.OleClientSite;
    import org.eclipse.swt.ole.win32.OleFrame;
    import org.eclipse.swt.ole.win32.OleFunctionDescription;
    import org.eclipse.swt.ole.win32.OlePropertyDescription;
    import org.eclipse.swt.ole.win32.OleParameterDescription;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.ole.win32.Variant;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.BufferedWriter;
    import java.io.IOException;
    public class WordSearchReplace {
         private static final String PROG_ID = "Word.Application";
         private static final int WD_REPLACE_ALL = 2;
         private static final int WD_FIND_CONTINUE = 1;
         private Shell shell = null;
         private OleFrame frame = null;
         private OleClientSite wordSite = null;
         private OleAutomation wordAutomation = null;
         private OleAutomation activeDocumentAutomation = null;
         private boolean cleaned = false;
         * Create a new instance of the WordSearchReplace class.
         public WordSearchReplace() {
              this.shell = new Shell();
              this.frame = new OleFrame(this.shell, SWT.NONE);
              this.wordSite = new OleClientSite(this.frame, SWT.NONE, WordSearchReplace.PROG_ID);
         this.wordAutomation = new OleAutomation(this.wordSite);
         * Open an MS Word file. This is a file whose name ends with the extension
         * .doc or .doc and which conforms to the correct format.
         * Note; if it is possible to open the named file, an attempt is made
         * to cache an OleAutomation object referencing that file which will be
         * referred to in future as the active document. Most other methods
         * need to capture references to further OleAutomation(s) that have the
         * active document as their root.
         * @param fileName An instance of the String class that encapsulates the
         * path to and name of the file that is to be opened.
         * Note; the full path name must be supplied as Word
         * will be opening the file and no assumptions can
         * safely be made concerning the applications 'home'
         * folder.
         * @throws NullPointerException if a null value is passed to the fileName
         * parameter.
         * @throws FileNotFoundException if it is not possible to locate the
         * file.
         * @throws IllegalArgumentException if the name of the file does not end
         * with either the .dot or .doc extensions.
         * @throws SWTException if a problem occurs whilst invoking any of the OLE
         * methods.
         public void openFile(String fileName) throws SWTException,
         NullPointerException,
         FileNotFoundException,
         IllegalArgumentException {
              OleAutomation documentsAutomation = null;
              int[] id = null;
              Variant[] arguments = null;
              Variant invokeResult = null;
              try {
                   // Check the the file name is not null
                   if(fileName == null) {
                        throw new NullPointerException("Null value passed to " +
                             "fileName parameters of the openFile() method.");
                   // Check the the file names ends with '.dot' or '.doc'.
                   // Remember to include templates and docuemnts
                   if(!(fileName.endsWith(".doc")) && !(fileName.endsWith(".dot"))) {
                        throw new IllegalArgumentException(
                             "The filename must end with the extensions \'.doc\' or \'.dot\'");
                   // Check that the file exists
                   File fileToPrint = new File(fileName);
                   if(!(fileToPrint.exists())) {
                        throw new FileNotFoundException("The file " +
                        fileName +
                        "cannot be found.");
                   // From the application, get an automation for the Documents property
                   documentsAutomation = this.getChildAutomation(this.wordAutomation,
                   "Documents");
                   // Get the ID of the Open method
                   id = documentsAutomation.getIDsOfNames(new String[]{"Open"});
                   if(id == null) {
                        throw new SWTException("It was not possible to recover an " +
                        "identifer for the Open method in WordSearchReplace.openFile().");
                   // Build an array of parameters - holds just the file name
                   arguments = new Variant[1];
                   arguments[0] = new Variant(fileName);
                   // Invoke the Open method on the Documents property
                   invokeResult = documentsAutomation.invoke(id[0], arguments);
                   // If the call to invoke the open method failed, throw an SWTException
                   // to terminate processing.
                   if(invokeResult == null) {
                        throw new SWTException("An error occurred whilst invoking the " +
                             "Open method for the following file: " +
                             fileName +
                             " in WordSearchReplace.openFile().");
                   // If it was possible to open the document successfully, grab an
                   // automation object referencing the active document here.               
                   else {
                        this.activeDocumentAutomation = this.getChildAutomation(
                             this.wordAutomation, "ActiveDocument");
              finally {
                   // If the automation was instantiated then dispose of it to
                   // release resources. This OleAutomation was only required
                   // to open the file and can safely be released here.
                   if(documentsAutomation != null) {
                        documentsAutomation.dispose();
         * Save the currently open file - the active document.
         * @throws SWTException if a problem occurs whilst invoking any of the OLE
         * methods.
         public void save() throws SWTException {
              int[] id = null;
              Variant invokeResult = null;
              // From the automation for the ActiveDocument object, get an id for
              // the Save method
              id = this.activeDocumentAutomation.getIDsOfNames(new String[]{"Save"});
              // If it was not possible to recover the id of the Save
              // method, throw an exception to notify the user and terminate
              // processing.
              if(id == null) {
                   throw new SWTException("Unable to obtain an automation for " +
                        "the Save method in WordSearchReplace.save().");
              // Invoke the Save method and catch the value returned
              invokeResult = this.activeDocumentAutomation.invoke(id[0]);
              // If a null value was returned then the invocation of the
              // Save method failed. Throw an exception to notify the
              // user and terminate processing.
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred invoking the " +
                        "Save method in WordSearchReplace.save().");
         * Save the active document using the name provided.
         * @param fileName Am instance of the String class encapsulating the name
         * for the file. Again, the path to and name of the file should
         * be supplied.
         * @throws NullPointerException if a null value is passed to the fileName
         * parameter.
         * @throws IllegalArgumentException if either an empty String is passed
         * to the fileName parameter or if the files name does not end
         * with one of the two permissible extensions - .dot and .doc
         public void saveAs(String fileName) throws SWTException,
         NullPointerException,
         IllegalArgumentException {
              int[] id = null;
              Variant[] arguments = null;
              Variant invokeResult = null;
              // If the fileName parameter is passed a null
              // value, throw an exception.
              if(fileName == null) {
                   throw new NullPointerException("A null value was passed to " +
                        "the fileName parameter of WordSearchReplace.saveAs().");
              // If the fileName parameter has been passed an empty String
              // then again throw an exception.
              if(fileName.length() == 0) {
                   throw new NullPointerException("An empty string was passed " +
                        "to the fileName parameter of WordSearchReplace.saveAs().");
              // Finally, make sure the file name ends in either
              // .doc or .dot.
              if((!fileName.endsWith(".dot")) && (!fileName.endsWith(".doc"))) {
                   throw new IllegalArgumentException("An illegal file name was " +
                        "passed to the fileName parameter of " +
                        "WordSearchReplace.saveAs(). The file name must " +
                        "end in \'.dot\' or \'.doc\'.");
              // From the automation for the ActiveDocument object, get an id for
              // the SaveAs method
              id = this.activeDocumentAutomation.getIDsOfNames(new String[]{"SaveAs"});
              // If it was not possible to recover the id of the SaveAs
              // method, throw an exception to notify the user and terminate
              // processing.
              if(id == null) {
                   throw new SWTException("Unable to obtain an automation for " +
                        "the SaveAs method in WordSearchReplace.saveAs().");
              // Build the array of arguments that will be passed to the invoke
              // method when the SaveAs method is invoked. In this case, this
              // array will contain a single member - a String object encapsulating
              // the path to and name of the output file.
              arguments = new Variant[1];
              arguments[0] = new Variant(fileName);
              // Invoke the SaveAs method and catch the value returned
              invokeResult = this.activeDocumentAutomation.invoke(id[0], arguments);
              // If a null value was returned then the invocation of the
              // PrintOut method failed. Throw an exception to notify the
              // user and terminate processing.
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred invoking the " +
                        "SaveAs method in WordSearchReplace.saveAs().");
         * Mimics Words 'replace' functionality by searching the active
         * document for evey string of characters that matches the value passed to
         * the searchTerm parameter and replacing them with the string of
         * characters passed to the replacementTerm method.
         * It is possible to code a VBA macro within Word that will perfrom a serach
         * and replace. That code would look like the following;
         * <pre>
         *      Selection.Find.ClearFormatting
    *     Selection.Find.Replacement.ClearFormatting
    *     With Selection.Find
    *      .Text = "serach"
    *      .Replacement.Text = "search"
    *      .Forward = True
    *      .Wrap = wdFindContinue
    *      .Format = False
    *      .MatchCase = False
    *      .MatchWholeWord = False
    *      .MatchWildcards = False
    *      .MatchSoundsLike = False
    *      .MatchAllWordForms = False
    *     End With
    *     Selection.Find.Execute Replace:=wdReplaceAll
    * <pre>
    * and this method will 'automate' it.
         * @param searchTerm An instance of the String class that will encapsulate
         * the series of characters that should be replaced.
         * @param replacementTerm An instance of the String class that will
         * encapsulate the series of characters that should replace the
         * searchTerm.
         * @throws NullPointerException if a null value is passed to either the
         * searchTerm or replacementTerm methods.
         * @throws SWTException if a problem occurs when invoking any of the
         * OLE methods.
         public void replace(String searchTerm,
         String replacementTerm) throws SWTException,
         NullPointerException {
              OleAutomation selectionFindAutomation = null;
              OleAutomation childAutomation = null;
              Variant[] arguments = null;
              Variant invokeResult = null;
              int[] id = null;
              int[] namedArguments = null;
              boolean success = true;
              // Validate the searchTerm parameter and throw exception if
              // null value passed.
              if(searchTerm == null) {
                   throw new NullPointerException("Null value passed to " +
                             "searchTerm parameter of the replace() method.");
              // Validate the replacementTerm parameter and throw exception if
              // null value passed.
              if(replacementTerm == null) {
                   throw new NullPointerException("Null value passed to " +
                             "replacementTerm parameter of the replace() method.");
              // Most of the VBA instructions used to perform the search and
              // replace functionality and child automations of Selection.Find,
              // therefore, it is wise to cache that automation first.
              // From the application, get an automation for the Selection property
              childAutomation = this.getChildAutomation(this.wordAutomation,
                   "Selection");
              selectionFindAutomation = this.getChildAutomation(childAutomation,
              "Find");
              // Next, using the cached automation, invoke the 'ClearFormatting'
              // method, validate the returned value and invoke the method.
              // Selection.Find.ClearFormatting
              id = selectionFindAutomation.getIDsOfNames(new String[]{"ClearFormatting"});
              if(id == null) {
                   throw new SWTException("It is not possible to recover an identifier " +
                        "for the ClearFormatting method in WordSearchReplace.replace() " +
                        "when clearing the formatting for the search string.");
              invokeResult = selectionFindAutomation.invoke(id[0]);
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred invoking the " +
                        "ClearFormatting method in WordSearchReplace.repace() " +
                        "when clearing formatting for the search string.");
              // Now, perform the same function but for the replacement string.
              // Selection.Find.Replacement.ClearFormatting
              childAutomation = this.getChildAutomation(selectionFindAutomation,
              "Replacement");
              id = childAutomation.getIDsOfNames(new String[]{"ClearFormatting"});
              if(id == null) {
                   throw new SWTException("It is not possible to recover an identifier " +
                        "for the ClearFormatting method in WordSearchReplace.replace() " +
                        "when clearing the formatting for the replacement string.");
              invokeResult = childAutomation.invoke(id[0]);
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred invoking the " +
                        "ClearFormatting method in WordSearchReplace.repace() " +
                        "when clearing formatting for the replacement string.");
              // Firstly, set the search text.
              // .Text = "search term"
              arguments = new Variant[1];
              arguments[0] = new Variant(searchTerm);
              success = this.setPropertyValue(selectionFindAutomation, "Text", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Text " +
                        "property for the search string in WordSearchReplace.replace().");
              // Next, the replacement text
              // .Replacement.Text = "replacement term"
              childAutomation = this.getChildAutomation(selectionFindAutomation,
              "Replacement");
              arguments[0] = new Variant(replacementTerm);
              success = this.setPropertyValue(childAutomation, "Text", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Text property" +
                        " for the replacement string in WordSearchReplace.replace().");
              // Set the direction of the search - forward in this case.
              // .Forward = True
              arguments[0] = new Variant(true);
              success = this.setPropertyValue(selectionFindAutomation, "Forward", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Forward " +
                        "property in WordSearchReplace.replace().");
              // Tell the search to wrap. Note the literal wdFindContinue relates to
              // a constant that is defined within Word. I have provided a static
              // final to replace it called WD_FIND_CONTINUE
              // .Wrap = wdFindContinue
              arguments[0] = new Variant(WordSearchReplace.WD_FIND_CONTINUE);
              success = this.setPropertyValue(selectionFindAutomation, "Wrap", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Wrap " +
                        "property in WordSearchReplace.replace().");
              // Set the Format property to False.
              // .Format = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "Format", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Format " +
                        "property in WordSearchReplace.replace().");
              // Set the MatchCase property to false.
              // .MatchCase = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchCase", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the MatchCase " +
                        "property in WordSearchReplace.replace().");
              // Set the MatchWholeWord property to false.
              // .MatchWholeWord = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchWholeWord", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the " +
                        "MatchWholeWord property in WordSearchReplace.replace().");
              // Set the MatchWildCards property to false.
              // .MatchWildcards = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchWildCards", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the " +
                        "MatchWildCards property in WordSearchReplace.replace().");
              // Set the MatchSoundsLike property to false.
              // .MatchSoundsLike = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchSoundsLike", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the " +
                        "MatchSoundsLike property in WordSearchReplace.replace().");
              // Set the MatchAllWordForms property to false.
              // .MatchAllWordForms = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchAllWordForms", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the " +
                        "MatchAllWordForms property in WordSearchReplace.replace().");
              // Invoke the Execute command passing the correct value to the Replace
              // parameter. Again, wdReplaceAll is a constant that I have provided
              // a ststic final for called WD_REPLACE_ALL
              // Selection.Find.Execute Replace:=wdReplaceAll
              id = selectionFindAutomation.getIDsOfNames(new String[]{"Execute", "Replace"});
              if(id == null) {
                   throw new SWTException("It was not possible to recover an identifier " +
                        "for the Execute method in WordSearchReplace.replace().");
              arguments = new Variant[1];
              arguments[0] = new Variant(WordSearchReplace.WD_REPLACE_ALL);
              namedArguments = new int[1];
              namedArguments[0] = id[1];
              // There was some indication that the invokeNoReply method should
              // be used when making this call but no, invoke SEEMS to work well
              //selectionFindAutomation.invokeNoReply(id[0], arguments, namedArguments);
              invokeResult = selectionFindAutomation.invoke(id[0], arguments, namedArguments);
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred trying to invoke the " +
                   "Execute method in WordSearchReplace.replace().");
         * Close the active document.
         * @throws SWTException if a problem is encountered invoking any of the
         * OLE methods.
         public void closeFile() throws SWTException {
              int[] id = null;
              Variant[] arguments = null;
              Variant invokeResult = null;
              try {
                   // From the OleAutomation referencing the active document, recover
                   // the id of the Close method.
                   id = this.activeDocumentAutomation.getIDsOfNames(new String[]{"Close"});
                   // If it was not possible to recover the id of the Close
                   // method then throw an exception to notify the user and
                   // terminate processing.
                   if(id == null) {
                        throw new SWTException("It was not possible to recover an " +
                             "identifier for the Close method in " +
                             "WordSearchReplace.closeFile().");
                   // Invoke the Close method on the ActiveDocument automation
                   invokeResult = this.activeDocumentAutomation.invoke(id[0]);
                   // If the invocation of the Close method failed, throw an
                   // exception to notify the user and terminate processing.
                   if(invokeResult == null) {
                        throw new SWTException(
                             "An error occurred invoking the Close method in " +
                             "WordSearchReplace.closeFile().");
              finally {
                   if(this.activeDocumentAutomation != null) {
                        this.activeDocumentAutomation.dispose();
         * Release resources.
         public void dispose() throws SWTException {
              try {
                   // Set the cleaned flag to true. This prevents the method from
                   // running again if it is called from the finalize() method
                   this.cleaned = true;
                   // From the word automation, recover the id of the Quit method
                   int[] id = this.wordAutomation.getIDsOfNames(new String[]{"Quit"});
                   // If the id of the Quit method cannot be recovered
                   // throw an exception - not much good really though.
                   if(id == null) {
                        throw new SWTException("Unable to obtain an id for the Quit " +
                             "property in WordSearchReplace.dispose().");
                   // Invoke Quit
              Variant result = this.wordAutomation.invoke(id[0]);
              // If an error occurs during the invocation, throw an exception.
              // Again though that exception is of limited value.
              if(result == null) {
                   throw new SWTException("A problem occurred trying to invoke the " +
                        "Quit method in WordSearchReplace.dispose().");
         finally {
              // Finally, dispose of the word application automation.
              this.wordAutomation.dispose();
         * The finalize() method has been over-ridden to ensure that resources
         * are correctly released if a WordSearchReplace object is created but
         * not disposed of properly before it becomes eligible for garbage
         * collection. The cleaned flag is used as acheck to ensure that the
         * dispose() method cannot be called more than once.
         public void finalize() throws Throwable {
              if(!this.cleaned) {
                   this.dispose();
         * Creates and returns a 'child' OleAutomation object. The object model
         * employed by Word, Excel and the like, arrange objects, methods and
         * properties hierarchically. To invoke a method, it is often necessary
         * to iterate through this hierarchy from parent to child and this method
         * supports that process.
         * @param automation An OleAutomation object that references the parent
         * automation.
         * @param childName An instance of the String class that encapsulates the
         * name of the child automation.
         * @throws SWTException if a problem is encountered invoking one or
         * other of the OLE methods.
         private OleAutomation getChildAutomation(OleAutomation automation,
         String childName) throws SWTException {
              // Try to recove the unique identifier for the child automation
              int[] id = automation.getIDsOfNames(new String[]{childName});
              // If the identifier cannot be found then throw an exception to
              // terminate processing.           
              if (id == null) {
                   throw new SWTException(
                        "A problem occurred trying to obtain and id for: " +
                   childName +
                   "in the getC

    When you call it the first time, it new Shell() constructs a new Display for you (the default).
    The second time, it gets the default display, but you are in a different Thread now. Since you have to create your widgets in the UI thread, it gives you that error.
    To run code in the UI thread, Display provides two methods:
    display.syncexec(..)and
    display.asyncexec(...)see
    http://help.eclipse.org/help32/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/swt_threading.htm
    for more details.

  • Org.eclipse.swt.SWTException: Invalid thread access - Action struts

    Hi
    I�m runing this WordSearchReplace java class that I got here in this forum, and I�m runing it doing search and replace in Ms word document if I run just one time it works ok, but if I run twice i got that erro, I�m runing that java class in my Action on struts.
    I don�t know what is occur.
    Can you help me?
    Thanks
    Following the example of call, mistakes and java class.
    //======RUNING THE WordSearchReplace JAVA CLASS=========
    WordSearchReplace wordSR = null;
    try {
    String[] v_text = {"#V46#","#V42#"};
    String[] v_replace = {"Texto1","Texto2"};
    wordSR = new WordSearchReplace();
    wordSR.openFile(v_path+v_file_name);
    for ( int i=0; i<v_text.length; i++ )
    wordSR.replace( v_text, v_replace[i] );
    wordSR.save();
    wordSR.closeFile();
    catch(Exception e) {
    System.out.println("Caught: ERRO ao Executar WordSearchReplace " + e.getClass().getName());
    System.out.println(e.getMessage());
    e.printStackTrace(System.out);
    finally {
    if(wordSR != null) {
    try {
    wordSR.dispose();
    catch(Exception innerE) {
    System.out.println("Caught: " + innerE.getClass().getName());
    System.out.println(innerE.getMessage());
    innerE.printStackTrace(System.out);
    //========ERRO ===========================
    17:24:49,093 INFO [STDOUT] Invalid thread access
    17:24:49,093 INFO [STDOUT] org.eclipse.swt.SWTException: Invalid thread access
    17:24:49,093 INFO [STDOUT] at org.eclipse.swt.SWT.error(SWT.java:3563)
    17:24:49,093 INFO [STDOUT] at org.eclipse.swt.SWT.error(SWT.java:3481)
    17:24:49,093 INFO [STDOUT] at org.eclipse.swt.SWT.error(SWT.java:3452)
    17:24:49,093 INFO [STDOUT] at org.eclipse.swt.widgets.Widget.error(Widget.java:432)
    17:24:49,093 INFO [STDOUT] at org.eclipse.swt.widgets.Shell.<init>(Shell.java:274)
    17:24:49,093 INFO [STDOUT] at org.eclipse.swt.widgets.Shell.<init>(Shell.java:265)
    17:24:49,093 INFO [STDOUT] at org.eclipse.swt.widgets.Shell.<init>(Shell.java:218)
    17:24:49,093 INFO [STDOUT] at org.eclipse.swt.widgets.Shell.<init>(Shell.java:156)
    17:24:49,093 INFO [STDOUT] at br.com.tryblob.view.WordSearchReplace.<init>(WordSearchReplace.java:38)
    17:24:49,093 INFO [STDOUT] at br.com.tryblob.view.WordAction.execute(WordAction.java:70)
    17:24:49,093 INFO [STDOUT] at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:484)
    17:24:49,093 INFO [STDOUT] at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:274)
    17:24:49,093 INFO [STDOUT] at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
    17:24:49,093 INFO [STDOUT] at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507)
    17:24:49,093 INFO [STDOUT] at javax.servlet.http.HttpServlet.service(HttpServlet.java:697)
    //====== WordSearchReplace JAVA CLASS=========
    import java.util.ArrayList;
    import java.util.Iterator;
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.SWTException;
    import org.eclipse.swt.internal.ole.win32.TYPEATTR;
    import org.eclipse.swt.ole.win32.OLE;
    import org.eclipse.swt.ole.win32.OleAutomation;
    import org.eclipse.swt.ole.win32.OleClientSite;
    import org.eclipse.swt.ole.win32.OleFrame;
    import org.eclipse.swt.ole.win32.OleFunctionDescription;
    import org.eclipse.swt.ole.win32.OlePropertyDescription;
    import org.eclipse.swt.ole.win32.OleParameterDescription;
    import org.eclipse.swt.widgets.Shell;
    import org.eclipse.swt.ole.win32.Variant;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileWriter;
    import java.io.BufferedWriter;
    import java.io.IOException;
    public class WordSearchReplace {
         private static final String PROG_ID = "Word.Application";
         private static final int WD_REPLACE_ALL = 2;
         private static final int WD_FIND_CONTINUE = 1;
         private Shell shell = null;
         private OleFrame frame = null;
         private OleClientSite wordSite = null;
         private OleAutomation wordAutomation = null;
         private OleAutomation activeDocumentAutomation = null;
         private boolean cleaned = false;
         * Create a new instance of the WordSearchReplace class.
         public WordSearchReplace() {
              this.shell = new Shell();
              this.frame = new OleFrame(this.shell, SWT.NONE);
              this.wordSite = new OleClientSite(this.frame, SWT.NONE, WordSearchReplace.PROG_ID);
         this.wordAutomation = new OleAutomation(this.wordSite);
         * Open an MS Word file. This is a file whose name ends with the extension
         * .doc or .doc and which conforms to the correct format.
         * Note; if it is possible to open the named file, an attempt is made
         * to cache an OleAutomation object referencing that file which will be
         * referred to in future as the active document. Most other methods
         * need to capture references to further OleAutomation(s) that have the
         * active document as their root.
         * @param fileName An instance of the String class that encapsulates the
         * path to and name of the file that is to be opened.
         * Note; the full path name must be supplied as Word
         * will be opening the file and no assumptions can
         * safely be made concerning the applications 'home'
         * folder.
         * @throws NullPointerException if a null value is passed to the fileName
         * parameter.
         * @throws FileNotFoundException if it is not possible to locate the
         * file.
         * @throws IllegalArgumentException if the name of the file does not end
         * with either the .dot or .doc extensions.
         * @throws SWTException if a problem occurs whilst invoking any of the OLE
         * methods.
         public void openFile(String fileName) throws SWTException,
         NullPointerException,
         FileNotFoundException,
         IllegalArgumentException {
              OleAutomation documentsAutomation = null;
              int[] id = null;
              Variant[] arguments = null;
              Variant invokeResult = null;
              try {
                   // Check the the file name is not null
                   if(fileName == null) {
                        throw new NullPointerException("Null value passed to " +
                             "fileName parameters of the openFile() method.");
                   // Check the the file names ends with '.dot' or '.doc'.
                   // Remember to include templates and docuemnts
                   if(!(fileName.endsWith(".doc")) && !(fileName.endsWith(".dot"))) {
                        throw new IllegalArgumentException(
                             "The filename must end with the extensions \'.doc\' or \'.dot\'");
                   // Check that the file exists
                   File fileToPrint = new File(fileName);
                   if(!(fileToPrint.exists())) {
                        throw new FileNotFoundException("The file " +
                        fileName +
                        "cannot be found.");
                   // From the application, get an automation for the Documents property
                   documentsAutomation = this.getChildAutomation(this.wordAutomation,
                   "Documents");
                   // Get the ID of the Open method
                   id = documentsAutomation.getIDsOfNames(new String[]{"Open"});
                   if(id == null) {
                        throw new SWTException("It was not possible to recover an " +
                        "identifer for the Open method in WordSearchReplace.openFile().");
                   // Build an array of parameters - holds just the file name
                   arguments = new Variant[1];
                   arguments[0] = new Variant(fileName);
                   // Invoke the Open method on the Documents property
                   invokeResult = documentsAutomation.invoke(id[0], arguments);
                   // If the call to invoke the open method failed, throw an SWTException
                   // to terminate processing.
                   if(invokeResult == null) {
                        throw new SWTException("An error occurred whilst invoking the " +
                             "Open method for the following file: " +
                             fileName +
                             " in WordSearchReplace.openFile().");
                   // If it was possible to open the document successfully, grab an
                   // automation object referencing the active document here.               
                   else {
                        this.activeDocumentAutomation = this.getChildAutomation(
                             this.wordAutomation, "ActiveDocument");
              finally {
                   // If the automation was instantiated then dispose of it to
                   // release resources. This OleAutomation was only required
                   // to open the file and can safely be released here.
                   if(documentsAutomation != null) {
                        documentsAutomation.dispose();
         * Save the currently open file - the active document.
         * @throws SWTException if a problem occurs whilst invoking any of the OLE
         * methods.
         public void save() throws SWTException {
              int[] id = null;
              Variant invokeResult = null;
              // From the automation for the ActiveDocument object, get an id for
              // the Save method
              id = this.activeDocumentAutomation.getIDsOfNames(new String[]{"Save"});
              // If it was not possible to recover the id of the Save
              // method, throw an exception to notify the user and terminate
              // processing.
              if(id == null) {
                   throw new SWTException("Unable to obtain an automation for " +
                        "the Save method in WordSearchReplace.save().");
              // Invoke the Save method and catch the value returned
              invokeResult = this.activeDocumentAutomation.invoke(id[0]);
              // If a null value was returned then the invocation of the
              // Save method failed. Throw an exception to notify the
              // user and terminate processing.
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred invoking the " +
                        "Save method in WordSearchReplace.save().");
         * Save the active document using the name provided.
         * @param fileName Am instance of the String class encapsulating the name
         * for the file. Again, the path to and name of the file should
         * be supplied.
         * @throws NullPointerException if a null value is passed to the fileName
         * parameter.
         * @throws IllegalArgumentException if either an empty String is passed
         * to the fileName parameter or if the files name does not end
         * with one of the two permissible extensions - .dot and .doc
         public void saveAs(String fileName) throws SWTException,
         NullPointerException,
         IllegalArgumentException {
              int[] id = null;
              Variant[] arguments = null;
              Variant invokeResult = null;
              // If the fileName parameter is passed a null
              // value, throw an exception.
              if(fileName == null) {
                   throw new NullPointerException("A null value was passed to " +
                        "the fileName parameter of WordSearchReplace.saveAs().");
              // If the fileName parameter has been passed an empty String
              // then again throw an exception.
              if(fileName.length() == 0) {
                   throw new NullPointerException("An empty string was passed " +
                        "to the fileName parameter of WordSearchReplace.saveAs().");
              // Finally, make sure the file name ends in either
              // .doc or .dot.
              if((!fileName.endsWith(".dot")) && (!fileName.endsWith(".doc"))) {
                   throw new IllegalArgumentException("An illegal file name was " +
                        "passed to the fileName parameter of " +
                        "WordSearchReplace.saveAs(). The file name must " +
                        "end in \'.dot\' or \'.doc\'.");
              // From the automation for the ActiveDocument object, get an id for
              // the SaveAs method
              id = this.activeDocumentAutomation.getIDsOfNames(new String[]{"SaveAs"});
              // If it was not possible to recover the id of the SaveAs
              // method, throw an exception to notify the user and terminate
              // processing.
              if(id == null) {
                   throw new SWTException("Unable to obtain an automation for " +
                        "the SaveAs method in WordSearchReplace.saveAs().");
              // Build the array of arguments that will be passed to the invoke
              // method when the SaveAs method is invoked. In this case, this
              // array will contain a single member - a String object encapsulating
              // the path to and name of the output file.
              arguments = new Variant[1];
              arguments[0] = new Variant(fileName);
              // Invoke the SaveAs method and catch the value returned
              invokeResult = this.activeDocumentAutomation.invoke(id[0], arguments);
              // If a null value was returned then the invocation of the
              // PrintOut method failed. Throw an exception to notify the
              // user and terminate processing.
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred invoking the " +
                        "SaveAs method in WordSearchReplace.saveAs().");
         * Mimics Words 'replace' functionality by searching the active
         * document for evey string of characters that matches the value passed to
         * the searchTerm parameter and replacing them with the string of
         * characters passed to the replacementTerm method.
         * It is possible to code a VBA macro within Word that will perfrom a serach
         * and replace. That code would look like the following;
         * <pre>
         *      Selection.Find.ClearFormatting
    *     Selection.Find.Replacement.ClearFormatting
    *     With Selection.Find
    *      .Text = "serach"
    *      .Replacement.Text = "search"
    *      .Forward = True
    *      .Wrap = wdFindContinue
    *      .Format = False
    *      .MatchCase = False
    *      .MatchWholeWord = False
    *      .MatchWildcards = False
    *      .MatchSoundsLike = False
    *      .MatchAllWordForms = False
    *     End With
    *     Selection.Find.Execute Replace:=wdReplaceAll
    * <pre>
    * and this method will 'automate' it.
         * @param searchTerm An instance of the String class that will encapsulate
         * the series of characters that should be replaced.
         * @param replacementTerm An instance of the String class that will
         * encapsulate the series of characters that should replace the
         * searchTerm.
         * @throws NullPointerException if a null value is passed to either the
         * searchTerm or replacementTerm methods.
         * @throws SWTException if a problem occurs when invoking any of the
         * OLE methods.
         public void replace(String searchTerm,
         String replacementTerm) throws SWTException,
         NullPointerException {
              OleAutomation selectionFindAutomation = null;
              OleAutomation childAutomation = null;
              Variant[] arguments = null;
              Variant invokeResult = null;
              int[] id = null;
              int[] namedArguments = null;
              boolean success = true;
              // Validate the searchTerm parameter and throw exception if
              // null value passed.
              if(searchTerm == null) {
                   throw new NullPointerException("Null value passed to " +
                             "searchTerm parameter of the replace() method.");
              // Validate the replacementTerm parameter and throw exception if
              // null value passed.
              if(replacementTerm == null) {
                   throw new NullPointerException("Null value passed to " +
                             "replacementTerm parameter of the replace() method.");
              // Most of the VBA instructions used to perform the search and
              // replace functionality and child automations of Selection.Find,
              // therefore, it is wise to cache that automation first.
              // From the application, get an automation for the Selection property
              childAutomation = this.getChildAutomation(this.wordAutomation,
                   "Selection");
              selectionFindAutomation = this.getChildAutomation(childAutomation,
              "Find");
              // Next, using the cached automation, invoke the 'ClearFormatting'
              // method, validate the returned value and invoke the method.
              // Selection.Find.ClearFormatting
              id = selectionFindAutomation.getIDsOfNames(new String[]{"ClearFormatting"});
              if(id == null) {
                   throw new SWTException("It is not possible to recover an identifier " +
                        "for the ClearFormatting method in WordSearchReplace.replace() " +
                        "when clearing the formatting for the search string.");
              invokeResult = selectionFindAutomation.invoke(id[0]);
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred invoking the " +
                        "ClearFormatting method in WordSearchReplace.repace() " +
                        "when clearing formatting for the search string.");
              // Now, perform the same function but for the replacement string.
              // Selection.Find.Replacement.ClearFormatting
              childAutomation = this.getChildAutomation(selectionFindAutomation,
              "Replacement");
              id = childAutomation.getIDsOfNames(new String[]{"ClearFormatting"});
              if(id == null) {
                   throw new SWTException("It is not possible to recover an identifier " +
                        "for the ClearFormatting method in WordSearchReplace.replace() " +
                        "when clearing the formatting for the replacement string.");
              invokeResult = childAutomation.invoke(id[0]);
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred invoking the " +
                        "ClearFormatting method in WordSearchReplace.repace() " +
                        "when clearing formatting for the replacement string.");
              // Firstly, set the search text.
              // .Text = "search term"
              arguments = new Variant[1];
              arguments[0] = new Variant(searchTerm);
              success = this.setPropertyValue(selectionFindAutomation, "Text", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Text " +
                        "property for the search string in WordSearchReplace.replace().");
              // Next, the replacement text
              // .Replacement.Text = "replacement term"
              childAutomation = this.getChildAutomation(selectionFindAutomation,
              "Replacement");
              arguments[0] = new Variant(replacementTerm);
              success = this.setPropertyValue(childAutomation, "Text", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Text property" +
                        " for the replacement string in WordSearchReplace.replace().");
              // Set the direction of the search - forward in this case.
              // .Forward = True
              arguments[0] = new Variant(true);
              success = this.setPropertyValue(selectionFindAutomation, "Forward", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Forward " +
                        "property in WordSearchReplace.replace().");
              // Tell the search to wrap. Note the literal wdFindContinue relates to
              // a constant that is defined within Word. I have provided a static
              // final to replace it called WD_FIND_CONTINUE
              // .Wrap = wdFindContinue
              arguments[0] = new Variant(WordSearchReplace.WD_FIND_CONTINUE);
    // System.out.println("jose vieira WD_FIND_CONTINUE:" + arguments[0]);
              success = this.setPropertyValue(selectionFindAutomation, "Wrap", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Wrap " +
                        "property in WordSearchReplace.replace().");
              // Set the Format property to False.
              // .Format = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "Format", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the Format " +
                        "property in WordSearchReplace.replace().");
              // Set the MatchCase property to false.
              // .MatchCase = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchCase", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the MatchCase " +
                        "property in WordSearchReplace.replace().");
              // Set the MatchWholeWord property to false.
              // .MatchWholeWord = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchWholeWord", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the " +
                        "MatchWholeWord property in WordSearchReplace.replace().");
              // Set the MatchWildCards property to false.
              // .MatchWildcards = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchWildCards", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the " +
                        "MatchWildCards property in WordSearchReplace.replace().");
              // Set the MatchSoundsLike property to false.
              // .MatchSoundsLike = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchSoundsLike", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the " +
                        "MatchSoundsLike property in WordSearchReplace.replace().");
              // Set the MatchAllWordForms property to false.
              // .MatchAllWordForms = False
              arguments[0] = new Variant(false);
              success = this.setPropertyValue(selectionFindAutomation, "MatchAllWordForms", arguments);
              if(!success) {
                   throw new SWTException("A problem occurred setting the " +
                        "MatchAllWordForms property in WordSearchReplace.replace().");
              // Invoke the Execute command passing the correct value to the Replace
              // parameter. Again, wdReplaceAll is a constant that I have provided
              // a ststic final for called WD_REPLACE_ALL
              // Selection.Find.Execute Replace:=wdReplaceAll
              id = selectionFindAutomation.getIDsOfNames(new String[]{"Execute", "Replace"});
              if(id == null) {
                   throw new SWTException("It was not possible to recover an identifier " +
                        "for the Execute method in WordSearchReplace.replace().");
              arguments = new Variant[1];
              arguments[0] = new Variant(WordSearchReplace.WD_REPLACE_ALL);
              namedArguments = new int[1];
              namedArguments[0] = id[1];
              // There was some indication that the invokeNoReply method should
              // be used when making this call but no, invoke SEEMS to work well
              //selectionFindAutomation.invokeNoReply(id[0], arguments, namedArguments);
              invokeResult = selectionFindAutomation.invoke(id[0], arguments, namedArguments);
              if(invokeResult == null) {
                   throw new SWTException("A problem occurred trying to invoke the " +
                   "Execute method in WordSearchReplace.replace().");
         * Close the active document.
         * @throws SWTException if a problem is encountered invoking any of the
         * OLE methods.
         public void closeFile() throws SWTException {
              int[] id = null;
              Variant[] arguments = null;
              Variant invokeResult = null;
              try {
                   // From the OleAutomation referencing the active document, recover
                   // the id of the Close method.
                   id = this.activeDocumentAutomation.getIDsOfNames(new String[]{"Close"});
                   // If it was not possible to recover the id of the Close
                   // method then throw an exception to notify the user and
                   // terminate processing.
                   if(id == null) {
                        throw new SWTException("It was not possible to recover an " +
                             "identifier for the Close method in " +
                             "WordSearchReplace.closeFile().");
                   // Invoke the Close method on the ActiveDocument automation
                   invokeResult = this.activeDocumentAutomation.invoke(id[0]);
                   // If the invocation of the Close method failed, throw an
                   // exception to notify the user and terminate processing.
                   if(invokeResult == null) {
                        throw new SWTException(
                             "An error occurred invoking the Close method in " +
                             "WordSearchReplace.closeFile().");
              finally {
                   if(this.activeDocumentAutomation != null) {
                        this.activeDocumentAutomation.dispose();
         * Release resources.
         public void dispose() throws SWTException {
              try {
                   // Set the cleaned flag to true. This prevents the method from
                   // running again if it is called from the finalize() method
                   this.cleaned = true;
                   // From the word automation, recover the id of the Quit method
                   int[] id = this.wordAutomation.getIDsOfNames(new String[]{"Quit"});
                   // If the id of the Quit method cannot be recovered
                   // throw an exception - not much good really though.
                   if(id == null) {
                        throw new SWTException("Unable to obtain an id for the Quit " +
                             "property in WordSearchReplace.dispose().");
                   // Invoke Quit
              Variant result = this.wordAutomation.invoke(id[0]);
              // If an error occurs during the invocation, throw an exception.
              // Again though that exception is of limited value.
              if(result == null) {
                   throw new SWTException("A problem occurred trying to invoke the " +
                        "Quit method in WordSearchReplace.dispose().");
         finally {
              // Finally, dispose of the word application automation.
              this.wordAutomation.dispose();
         * The finalize() method has been over-ridden to ensure that resources
         * are correctly released if a WordSearchReplace object is created but
         * not disposed of properly before it becomes eligible for garbage
         * collection. The cleaned flag is used as acheck to ensure that the
         * dispose() method cannot be called more than once.
         public void finalize() throws Throwable {
              if(!this.cleaned) {
                   this.dispose();
         * Creates and returns a 'child' OleAutomation object. The object model
         * employed by Word, Excel and the like, arrange objects, methods and
         * properties hierarchically. To invoke a method, it is often necessary
         * to iterate through this hierarchy from parent to child and this method
         * supports that process.
         * @param automation An OleAutomation object that references the parent
         * automation.
         * @param childName An instance of the String class that encapsulates the
         * name of the child automation.
         * @throws SWTException if a problem is encountered invoking one or
         * other of the OLE methods.
         private OleAutomation getChildAutomation(OleAutomation automation,
         String childName) throws SWTException {
              // Try to recove the unique identifier for the child automation
              int[] id = automation.getIDsOfNames(new String[]{childName});
              // If the identifier cannot be found then throw an exception to
              // terminate processing.           
              if (id == null) {
                   throw new SWTException(
                        "A problem occurred trying to obtain and id for: " +
                   childName +
                   "in the getChildAutomation() method.");
              // SWT's implementation of OLE referes to all of Words objects, methods
              // and properties using the single term 'property'. The next stage
              // therefore is to recover a refence to the 'property' that relates
              // to the child automation.
              Variant pVarResult = automation.getProperty(id[0]);
              // If it is not possible to recover a 'property' for the child
              // automation, then throw an SWTException.
              if (pVarResult == null) {
                   throw new SWTException(
                        "A problem occurred trying to obtain an automation for property: " +
                   id[0] +
                   " in the getChildAutomation() method.");
              // As we are after a child automation in this instance, call the
              // getAutomation() method on the 'property'.
              return(pVarResult.getAutomation());
         * Sets the value of a property.
         * @param automation An instance of the OleAutomation class that will
         * hold a reference to the properties parent automation object
         * @param propertyName An instance of the String class that encapsulates the
         * name of the property whose value is to be set.
         * @param arguments An array of type Variant whose elements contain the
         * values that will be set for the named property.
         * @return A primitive boolean value that indicates whether or not the
         * properties value was successfully set.
         * @throws NullPointerException will be thrown if a null value is passed to
         * any of the methods three arguments.
         * @throws IllegalArgumentException will be thrown if an empty String
         * is passed to the propertyName parameter or if an empty array
         * is passed to the arguments parameter. Note, no check is made
         * on the vallues of the elements in the arguments array.
         * @throws SWTException will be thrown if a problem is encountered
         * imvoking any of the OLE methods.
         private boolean setPropertyValue(OleAutomation automation,
         String propertyName,
         Variant[] arguments) throws SWTException,
         NullPointerException,
         IllegalArgumentException {
              // Validate the various parameters
              if(automation == null) {
                   throw new NullPointerException(
                        "A null value was pas

    Alright, I'll try to keep it as simple as possible. If that's not going to work out, we can always complicate it later :)
    I suppose you had a look at the link and I assume you know about threads.
    We can easily fix this issue if you are instantiating, calling and disposing the object within one thread, e.g. you use it only in one method like
    public mySwtExecutionMethod(String fileName){
      WordSearchReplace replace = new WordSearchReplace();
      // do your replacing here
      replace.dispose();
      // no reference to replace is left so it won't escape this thread
    }Now the fix for your class becomes simple. As you remember from the link, you have to call all methods from within the UI thread. We will now create a Display every time upon instantiation of WordSearchReplace, so the current thread becomes the UI thread.
    I had a look at the constructor, and the overhead doesn't seem that bad, provided this is not a dedicated search&replace server.
    private final Display display;
    public WordSearchReplace()
         display = new Display(); // create display
         this.shell = new Shell(display);   // initialize shell with new display so this thread becomes the UI thread
         this.frame = new OleFrame(this.shell, SWT.NONE);
         this.wordSite = new OleClientSite(this.frame, SWT.NONE, WordSearchReplace.PROG_ID);
         this.wordAutomation = new OleAutomation(this.wordSite);
    }Since we always create a new Display, we should also dispose it. There is already a dispose() method, so we just have to add to it
    display.dispose();That's it!
    If you hold on longer to your reference and this isn't working for you, you'd have to do a lot more synchronizing and that the UI thread still exist as long as the reference.
    Wish you good luck

  • Error : An error occurred while automatically activating bundle org.eclipse

    Hi,
    OpenScript closed with unsaved changes and now I cannot get it to open again. I checked out the logs it was giving the below error.
    !ENTRY org.eclipse.core.resources 2 10035 2013-03-28 10:05:18.046
    !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.
    !ENTRY org.eclipse.osgi 4 0 2013-03-28 10:05:18.062
    !MESSAGE An error occurred while automatically activating bundle org.eclipse.core.resources (326).
    !STACK 0
    org.osgi.framework.BundleException: Exception in org.eclipse.core.resources.ResourcesPlugin.start() of bundle org.eclipse.core.resources.
    I do not mind losing the file with the unsaved changes. Please let me know if anyone has faced a similar problem and the solution for the same.
    Thanks!

    Hi,
    OpenScript closed with unsaved changes and now I cannot get it to open again. I checked out the logs it was giving the below error.
    !ENTRY org.eclipse.core.resources 2 10035 2013-03-28 10:05:18.046
    !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.
    !ENTRY org.eclipse.osgi 4 0 2013-03-28 10:05:18.062
    !MESSAGE An error occurred while automatically activating bundle org.eclipse.core.resources (326).
    !STACK 0
    org.osgi.framework.BundleException: Exception in org.eclipse.core.resources.ResourcesPlugin.start() of bundle org.eclipse.core.resources.
    I do not mind losing the file with the unsaved changes. Please let me know if anyone has faced a similar problem and the solution for the same.
    Thanks!

  • Soap to proxy scenario Getting exception caught with cause   error

    Hi Experts,
    MY scenario is soap to proxy i am  getting below exception message in advanced engine configuration in ICO.
    OAP: request message entering the adapter with user J2EE_GUEST
    09/10/2014 11: 06: 03 346 XI Information Packaging (Bulk Mode) is not Enabled, Proceeding to the Normal Processing.
    09/10/2014 11: 06: 03 346 XISOAP Information: Received an XI message for processing
    09/10/2014 11: 06: 03 598 Error SOAP: response message contains an error XIAdapter / parsing / ADAPTER.SOAP_EXCEPTION - soap fault: Error in processing the Web Service; Other details in the error log of the Web Service from the provider side (Registration UTC 20,140,910,110,603; 6EDA38E4CE67F1B3B939005056882C3A transaction ID)
    09/10/2014 11: 06: 03 598 Information SOAP: completed the processing
    OAP: response message contains an error XIAdapter / parsing / ADAPTER.SOAP_EXCEPTION - soap fault: Error in processing the Web Service; Other details in the error log of the Web Service from the provider side (Registration UTC 20,140,910,110,603; 6EDA38E4CE67F1B3B939005056882C3A transaction ID)
    09/10/2014 11: 06: 03 598 Information SOAP: completed the processing
    09/10/2014 11: 06: 03 598 Information SOAP: response message to continuing 7477aafa-38da-11e4-beed-00000028af0a
    09/10/2014 11: 06: 03 599 Error MP: exception caught with cause com.sap.engine.interfaces.messaging.api.exception.MessagingException: SOAP: response message contains an error XIAdapter / parsing / ADAPTER.SOAP_EXCEPTION - soap fault: Error in processing the Web Service; Other details in the error log of the Web Service from the provider side (Registration UTC 20,140,910,110,603; 6EDA38E4CE67F1B3B939005056882C3A transaction ID)
    09/10/2014 11: 06: 03 599 Error SOAP: error occured: com.sap.engine.interfaces.messaging.api.exception.MessagingException: SOAP: response message contains an error XIAdapter / parsing / ADAPTER.SOAP_EXCEPTION - soap fault: Error in processing the Web Service; Other details in the error log of the Web Service from the provider side (Registration UTC 20,140,910,110,603; 6EDA38E4CE67F1B3B939005056882C3A transaction ID)
    payload is contains some  special charters in  which is in protiguse language
    example.
    • AWPJ SERV DE TERCERIZ and
    dot is the special char
    same payload while testing using sproxy tcode dot "•" is converting in " # "symbol and with out error its successfully updating the database in ECC.
    while testing using the same payload using soap ui removing the dot symbol from the field its successfully processing  and updating the database.
    is this interface is failing in PI level ? or ECC i am not getting dump in ecc.
    is there any special character conversation in sap pi level.
    where this message exactly failing is in PI level or in ECC level?
    Help us find the solution.

    Hi Ravinder,
    When you mark the option Do not use SOAP envelope the adapter will not generate the SOAP envelope therefore you need to set an extra mapping in the Request to wrap the SOAP envelope. For example with XSL:
    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml"/>
        <xsl:template match="/">
            <SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
                <SOAP:Header/>
                <SOAP:Body>
                    <xsl:copy-of select="/"/>
                </SOAP:Body>
            </SOAP:Envelope>
        </xsl:template>
    </xsl:stylesheet>
    Later in the response you will have the SOAP envelope tags. (You can do a first try without java mapping only to see in the monitoring the response with the junk character).
    When you determine the junk character you can try to use and to modify the next java mapping SAP PI - Deciphering apostrophes in XML - Process Integration - SCN Wiki to deal with your problem.
    Hope this helps.
    Regards.

  • ClassCastException at org.eclipse.xtext.builder.clustering.ClusteringBuilderState.doUpdate(Clusterin

    Hi,
    After upgrading xtext to 2.7.3 i get this exception in some cases
    java.lang.ClassCastException: null
    2015-07-02 13:44:19,842 ERROR o.e.x.b.c.ClusteringBuilderState: Error resolving cross references on resource 'platform:/resource/models/Demo/examples/comp.start'
    java.lang.ClassCastException: null
    2015-07-02 13:44:19,842 ERROR org.apache.log4j: org.eclipse.xtext.builder.clustering.ClusteringBuilderState - Error loading resource from: platform:/resource/models/Demo/examples/comp.start
    org.eclipse.xtext.builder.resourceloader.IResourceLoader$LoadOperationException: java.lang.ClassCastException
    at org.eclipse.xtext.builder.clustering.ClusteringBuilderState.doUpdate(ClusteringBuilderState.java:230)
    at org.eclipse.xtext.builder.builderState.AbstractBuilderState.update(AbstractBuilderState.java:112)
    at org.eclipse.xtext.builder.impl.XtextBuilder.doBuild(XtextBuilder.java:187)
    at org.eclipse.xtext.builder.impl.XtextBuilder.incrementalBuild(XtextBuilder.java:167)
    at org.eclipse.xtext.builder.impl.XtextBuilder.build(XtextBuilder.java:95)
    at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:728)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:199)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:239)
    at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:292)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:295)
    at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:351)
    at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:374)
    at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
    at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
    Any idea on how to get rid of this ??

    This class will be called while starting the tool
    public class dslXtextUtilities {
    @Inject
    Injector injector;
    public org.eclipse.emf.ecore.resource.Resource parseString(String str){
    org.eclipse.emf.ecore.resource.Resource xtextResource = null;
    try {
    URI uri = URI.createURI("stdt.dsl", true);
    VhdlParser parser = injector.getInstance(VhdlParser.class);
    XtextResourceSet xtextResourceSet = injector.getInstance(XtextResourceSet.class);
    xtextResource = xtextResourceSet.createResource(uri);
    xtextResourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
    InputStream inputStream = new LazyStringInputStream(str);
    ((XtextResource) xtextResource).setParser(parser);
    ((XtextResource) xtextResource).load(inputStream, xtextResourceSet.getLoadOptions());
    } catch (Exception e) {
    return xtextResource;
    return xtextResource;
    ==============================================
    Here is the call
    public class MApp implements IApplication {
    public Object start(IApplicationContext context) throws Exception {
    // unnecessaryExceptions
    try {
    dslXtextUtilities.parseString("int x = 0;");

Maybe you are looking for

  • One apple id two different users

    I was the "original" purchaser and user of iTunes music.  Had music on my desktop (then laptop) and iPhone and Nano and iPad Mini, etc.  Many years ago I also got my husband an iPod.  We just used my Apple ID and manually added music to his iPod sinc

  • Reg: Adding spaces between texts in ALV list header

    Hi All, I was implementing a client requirement for ALV. The list header should contain something of this format. Pgm Id:               ZZZ01 After this list header it is ALV display. I did this using the concatenate statement. ex: Concatenate 'PgmID

  • How to place a TextAreaControl in a grid cell

    I am trying to replace a cell in the GridControl with a TextAreaControl, so the cell can hold multi-line text, can anybody tell me how to do that? TIA Shaomei null

  • Need some help trying to repair network connection.

    Let me start this off by letting you folks know that I am in no way well-versed with any type of Networking or anything of the sort. A friend of mine set up my personal wireless network at my house. Ok, I'll try to keep this concise. I read through t

  • Trouble changing my profile picture for my nokia a...

    How do I change my profile picture on twitter for my nokia asha 303? The option is not availible.