Friday, April 8, 2011

have differance two queue

how to update new queue to Queue3

Queue Getupdate(Queue q1,Queue q2) { How... }

From stackoverflow
  • The question is unclear; what is your desired result? The union? The intersection? What? If you want ("differance" [sic] in title) to return those in the original queue but not the second, perhaps (.NET 3.5):

    public static Queue<T> Except<T>(this Queue<T> original, Queue<T> remove)
    {
        return new Queue<T>(Enumerable.Except<T>(original,remove));
    }
    
  • using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace TestQC
    {
        class Program
        {
            static void Main(string[] args)
            {
                Queue q1 = new Queue();
                Queue q2 = new Queue();
                Queue q3 = new Queue();
                q1.Enqueue(1);
                q1.Enqueue(2);
                q1.Enqueue(3);
                q1.Enqueue(4);
                q2.Enqueue(1);
                q2.Enqueue(2);
                q2.Enqueue(3);
                q2.Enqueue(4);
                q2.Enqueue(5);
                q2.Enqueue(6);
                Console.Write("Q1: ");
                foreach (var o in q1)
                {
                    Console.Write(o.ToString()+ " ");
                }
                Console.WriteLine();
                Console.Write("Q2: ");
                foreach (var o in q2)
                {
                    Console.Write(o.ToString() + " ");
                }
                Console.WriteLine();
                q3 = GetQUpdate(q1, q2);
                Console.Write("Q3: ");
                foreach (var o in q3)
                {
                    Console.Write(o.ToString() + " ");
                }
    
                Console.ReadLine();
            }
            static Queue GetQUpdate(Queue q1, Queue q2)
            {
                Queue q3 = new Queue();
    
                return q3;
            }
        }
    }
    

    I am testing Function For Implement

    Marc Gravell : Yes, but what do you want the result to be? 5,6? then just use the code I posted earlier (perhaps swap the order - q3 = q2.Except(q1);)
    Marc Gravell : Note that using queues in this way is unusual; would a list / etc be more appropriate?
    Brian Rasmussen : You should edit your original question instead of posting updates in an answer.

How do you get your Fulltext boolean search to pick up the term C++ ?

So, I need to find out how to do a fulltext boolean search on a MySQL database to return a record containg the term "C++".

I have my SQL search string as:

SELECT * FROM mytable WHERE MATCH (field1, field2, field3) AGAINST ("C++" IN BOOLEAN MODE)

Although all of my fields contain the string C++, it is never returned in the search results.

How can I modify MySQL to accommodate this? Is it possible?

The only solution I have found would be to escape the + character during the process of entering my data as something like "__plus" and then modifying my search to accomodate, but this seems cumbersome and there has to be a better way.

From stackoverflow
  • Usually escaped characters are used in the query not in the database data. Try escaping each "+" in your query.

  • How can I modify MySQL to accommodate this?

    You'll have to change MySQL's idea of what a word is.

    Firstly, the default minimum word length is 4. This means that no search term containing only words of <4 letters will ever match, whether that's ‘C++’ or ‘cpp’. You can configure this using the ft_min_word_len config option, eg. in your my.cfg:

    [mysqld]
    ft_min_word_len=3
    

    (Then stop/start MySQLd and rebuild fulltext indices.)

    Secondly, ‘+’ is not considered a letter by MySQL. You can make it a letter, but then that means you won't be able to search for the word ‘fish’ in the string ‘fish+chips’, so some care is required. And it's not trivial: it requires recompiling MySQL or hacking an existing character set. See the section beginning “If you want to change the set of characters that are considered word characters...” in section 11.8.6 of the doc.

    escape the + character during the process of entering my data as something like "__plus" and then modifying my search to accomodate

    Yes, something like that is a common solution: you can keep your ‘real’ data (without the escaping) in a primary, definitive table — usually using InnoDB for ACID compliance. Then an auxiliary MyISAM table can be added, containing only the mangled words for fulltext search bait. You can also do a limited form of stemming using this approach.

    Another possibility is to detect searches that MySQL can't do, such as those with only short words, or unusual characters, and fall back to a simple-but-slow LIKE or REGEXP search for those searches only. In this case you will probably also want to remove the stoplist by setting ft_stopword_file to an empty string, since it's not practical to pick up everything in that as special too.

    A. Rex : @bobince: (Re the discussion in the comments above, thank you for answering this easily-understandable question in a clear manner.) Out of curiosity, how would you do stemming with this approach? Replace every word in the auxiliary table with its stem?
    bobince : Essentially yes (processing the words in search queries in the same way of course). Typically you'd use an existing suffix-stripping stemmer library for your preferred languages. (For both values of ‘language’; see eg. Porter's algorithm for English in many programming languages.)
  • From http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html:

    "A phrase that is enclosed within double quote (“"”) characters matches only rows that contain the phrase literally, as it was typed."

    This means you can search for 'C++' using this query:

    SELECT * FROM mytable WHERE MATCH (field1, field2, field3) AGAINST ('"C++"' IN BOOLEAN MODE)

Loading dlls from gac is blocking app

The last few months my application grew bigger and bigger. It's runnable as Wpf .EXE and XBAP at the moment, both sharing the same code. At a few points in the application, the application locks. After invertigating I found out that the application is loading dlls from the GAC at these moments.

What happens is that the application starts, this takes a couple of seconds, and the user is presented with a logon screen. At the moment the user click the OK button to logon the application locks, because it has to load all kinds of dlls for the rest of the application. Because they're loaded from the UI thread all animations stop playing, event the mouseover of the OK button doesn't finish.

It started out as seconds, but at the moment at some points you'll have to wait a couple of minutes before the app continues. I think it's unexceptable.

Is there a way to move the loading of dlls from the GAC to another thread? So a "Please wait while application is loaded"-animation can be played? Or, even better, can I move the loading of all dlls needed to the start of the app, so there would be less waiting going on when working.

From stackoverflow
  • Yes (for "seconds" at least; not sure it scales to "minutes") - at the login screen, just spin up a worker thread (perhaps with ThreadPool) that does something that requires those assemblies. This will cause them to load...

    ThreadPool.QueueUserWorkItem(LoadAssemblies);
    ...
    static void LoadAssemblies(object state)
    {
        Widget1 widget = new Widget1(); // but just let it go (perhaps dispose it)
    }
    

    You are now off the UI thread, loading your assemblies while the user types their password.

    Sorskoot : I thought I tried a construction like that already, but this time it worked. Thanks!

static methods make Java a pseudo functional language?

I've been mulling about a post by Misko Hevery that static methods in Java are a death to testability. I don't want to discuss the testability issue but more on the concept of static methods. Why do people hate it so much?

It's true that we don't have closures (but we have a slightly awkward anonymous functions), lambdas & functions as first class objects. In a way, I think static methods can be used to mimic functions as first class objects.

From stackoverflow
  • Static methods make testing hard because they can't be replaced, it's as simple as that.

    How can static methods "mimic" functions as first class objects? Arguably they're worse than anything else on this front. You can "mimic" functions as first class objects by creating single-method interfaces, and indeed Google's Java Collections does exactly this in a number of places (for predicates, projections etc). That can't be done with static methods - there's no way (other than with reflection) to pass the concept of "when you want to apply a function, use this method.

    No, I can't see how static methods help here. They discourage state-changing (as the only state available is the global state and any mutable state passed in via the parameters) but they don't help on the "functions as first class objects" side.

    C# has better support for this (with lambda expressions and delegates) but even that's not as general as it might be. (Compare it with F#, for example.)

    ThomasD : Why would you ever want to replace a method for testing? I want to test the method not the replacement!
    Anton Gogolev : What if the method goes to a webserver on the opposite hemishpere and you don't really want that, since you'd be better off with static mock data.
    Jon Skeet : +1 to Anton's comment. If you can't replace your dependencies, your "unit" tests will be testing those dependencies as well as the method they're really trying to test.
  • My biggest objection against static methods is that they are not polymorphic and that they are not used in an object-oriented way, instead one has to you the class (not an object) to access them.

  • Functional != function, and for the record I will claim that a method != function...

    Java is a statically typed, object oriented language. Java has also maintained a relative purity in that manner but it's no where near a functional language.

    While it's true that you can mimic the behavior of functional programming with imperative programming you're never gonna get that tidy syntax which you'll wanna have for lambda calculus. In a way, if the language doesn't support proper lambda calculus it's not a functional programming language.

    C++ has functions, but C++ also have classes. C++ therefore have two type of functions, member functions and functions. When you say method you mean a member function. Because the method is invoked on an instance of an object. But when you say static method you mean just function (in the C/C++ sense). This is just a vocabulary for referring to elements of your code. And in Java code can not exist outside a class, a method would imply that it belongs to some class i.e. type.

    So far nothing of what I've said relates to functional programming but I think you get the point where you wrong.

    I suggest you look at pure functional programming languages such as Haskell or Erlang. Because functional programming languages generally don't have closers either.

    Your claim that static methods can be used to mimic functions as first class objects sounds really bizarre to me. It sounds more like a dynamic programming language than functional programming.

  • If you only use static methods then you are programming in a procedural, non-object-oriented style.

    However, the only context I can think of where this would be OK is during the first programming lessons before object orientation is introduced.

  • In Java, you can't give a function as an argument to another function.

    In a functional language, if you have a function

    def addOne(i) = i + 1
    

    you can pass that to another function that eg applies it to all elements of a list.

    In Java, with

    public static int addOne(int i) { return i + 1; }
    

    there is no way to do that.

  • One characteristic of functional programming is immutability of data. static does imply that you don't need an object (instance) representing state, so that's not a bad start. You do however have state on the class level, but you can make this final. Since (static) methods aren't first-class functions at all, you will still need ugly constructions like anonymous classes to approach a certain style of functional programming in Java.

    FP is best done in an functional language, since it has the necessary language support for things like higher-order functions, immutability, referential transparency and so on.

    However, this does not mean that you can't program in a functional style in an imperative language like Java. Other examples can be given as well. It's not because you are programming in Java that you are doing OOP. You can program with global data and unstructured control flows (goto) in a structured language as C++. I can do OOP in a functional language like Scheme. Etc.

    Steve McConnell mentions the difference of programming in a language versus programming into a language in Code Complete (also a very popular reference on SO).

    So, in short, if you say that "static methods mimic first-class functions", I do not agree.

    If, however, and I think that this was more the point you were trying to get across, you would say that "static methods can help for programming in a functional style in Java", I agree.

Webservice problem with base64 data when upgrading to JBoss 4.2.3

Hi, This is a long one du to config files... I'm running a upgrade from JBoss 4.0.5 to 4.2.3 The system I work with have a legacy webservice. It is based on J2EE webservices 1.1. It has a SLSB (EJB2) as endpoint. The WSDL file points out a schema (XSD-file) file for the definition of the parameters to the webservice. And there is a mapping file which maps to the schema.

The problem: For starters, the service works in JBoss 4.0.5. In 4.2.3 it works perfectly fine for except for a attachment element, the base64 data doesn't convert properly into a byte array. Changing it to string works fine, so there is no problem with typos, it just won't convert into a byte array. Has anyone had a similar problem when upgrading from 4.0.5 to 4.2.3?

If i remove an attachments from the call, it works fine, but if I have one, if fails with:

    org.jboss.ws.WSException: org.jboss.ws.core.binding.BindingException: org.jboss.ws.core.jaxrpc.binding.jbossxb.UnmarshalException: Failed to
     parse source: Failed to resolve target property type on org.jboss.xb.binding.sunday.unmarshalling.ElementBinding@1f1804d({http://foo/newsws/types}attachment, type={http://foo/newsws/types}AttachmentElementType)
            at org.jboss.ws.core.soap.XMLContent.unmarshallObjectContents(XMLContent.java:250)
            at org.jboss.ws.core.soap.XMLContent.transitionTo(XMLContent.java:97)
            at org.jboss.ws.core.soap.SOAPContentElement.transitionTo(SOAPContentElement.java:141)
            at org.jboss.ws.core.soap.SOAPBodyElementDoc.transitionTo(SOAPBodyElementDoc.java:85)
            at org.jboss.ws.core.soap.SOAPContentElement.getObjectValue(SOAPContentElement.java:173)
            at org.jboss.ws.core.EndpointInvocation.transformPayloadValue(EndpointInvocation.java:263)
            at org.jboss.ws.core.EndpointInvocation.getRequestParamValue(EndpointInvocation.java:115)
            at org.jboss.ws.core.EndpointInvocation.getRequestPayload(EndpointInvocation.java:135)
            at org.jboss.ws.core.server.DelegatingInvocation.getArgs(DelegatingInvocation.java:82)
            at org.jboss.wsf.container.jboss42.InvocationHandlerEJB21.getMBeanInvocation(InvocationHandlerEJB21.java:169)
            at org.jboss.wsf.container.jboss42.InvocationHandlerEJB21.invoke(InvocationHandlerEJB21.java:144)
            at org.jboss.ws.core.server.ServiceEndpointInvoker.invoke(ServiceEndpointInvoker.java:221)
            at org.jboss.wsf.stack.jbws.RequestHandlerImpl.processRequest(RequestHandlerImpl.java:466)
            at org.jboss.wsf.stack.jbws.RequestHandlerImpl.handleRequest(RequestHandlerImpl.java:284)
            at org.jboss.wsf.stack.jbws.RequestHandlerImpl.doPost(RequestHandlerImpl.java:201)
            at org.jboss.wsf.stack.jbws.RequestHandlerImpl.handleHttpRequest(RequestHandlerImpl.java:134)
            at org.jboss.wsf.stack.jbws.EndpointServlet.service(EndpointServlet.java:84)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
            at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:524)
            at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
            at org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java:393)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
            at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
            at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
            at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
            at java.lang.Thread.run(Thread.java:619)
Caused by: org.jboss.ws.core.binding.BindingException: org.jboss.ws.core.jaxrpc.binding.jbossxb.UnmarshalException: Failed to parse source:
Failed to resolve target property type on org.jboss.xb.binding.sunday.unmarshalling.ElementBinding@1369863({http://foo/newsws/t
ypes}attachment, type={http://foo/newsws/types}AttachmentElementType)
        at org.jboss.ws.core.jaxrpc.binding.JBossXBDeserializer.deserialize(JBossXBDeserializer.java:111)
        at org.jboss.ws.core.jaxrpc.binding.JBossXBDeserializer.deserialize(JBossXBDeserializer.java:62)
        at org.jboss.ws.core.binding.DeserializerSupport.deserialize(DeserializerSupport.java:60)
        at org.jboss.ws.core.soap.XMLContent.unmarshallObjectContents(XMLContent.java:180)
        ... 36 more
Caused by: org.jboss.ws.core.jaxrpc.binding.jbossxb.UnmarshalException: Failed to parse source: Failed to resolve target property type on or
g.jboss.xb.binding.sunday.unmarshalling.ElementBinding@1369863({http://foo/newsws/types}attachment, type={http://foo/newsws/types}AttachmentElementType)
        at org.jboss.ws.core.jaxrpc.binding.jbossxb.JBossXBUnmarshallerImpl.unmarshal(JBossXBUnmarshallerImpl.java:65)
        at org.jboss.ws.core.jaxrpc.binding.JBossXBDeserializer.deserialize(JBossXBDeserializer.java:103)
        ... 39 more
Caused by: org.jboss.xb.binding.JBossXBException: Failed to parse source: Failed to resolve target property type on org.jboss.xb.binding.sun
day.unmarshalling.ElementBinding@1369863({http://foo/newsws/types}attachment, type={http://foo/newsws/types}Attach
mentElementType)
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:179)
        at org.jboss.xb.binding.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:126)
        at org.jboss.ws.core.jaxrpc.binding.jbossxb.JBossXBUnmarshallerImpl.unmarshal(JBossXBUnmarshallerImpl.java:61)
        ... 40 more
Caused by: org.jboss.ws.WSException: Failed to resolve target property type on org.jboss.xb.binding.sunday.unmarshalling.ElementBinding@1369
863({http://foo/newsws/types}attachment, type={http://foo/newsws/types}AttachmentElementType)
        at org.jboss.ws.extensions.xop.jaxrpc.JBossXBContentAdapter.beforeSetParent(JBossXBContentAdapter.java:115)
        at org.jboss.xb.binding.sunday.unmarshalling.SundayContentHandler.endElement(SundayContentHandler.java:1005)
        at org.jboss.xb.binding.sunday.unmarshalling.SundayContentHandler.endElement(SundayContentHandler.java:246)
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser$DelegatingContentHandler.endElement(SaxJBossXBParser.java:296)
        at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
        at org.apache.xerces.xinclude.XIncludeHandler.endElement(Unknown Source)
        at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source)
        at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
        at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
        at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:175)
        ... 42 more

this is the webservices.xml

<webservice-description>
    <webservice-description-name>FooService</webservice-description-name>
    <wsdl-file>META-INF/wsdl/FooService.wsdl</wsdl-file>
    <jaxrpc-mapping-file>META-INF/FooService-mapping.xml</jaxrpc-mapping-file>
    <port-component>
        <port-component-name>FooService</port-component-name>
        <wsdl-port>FooServicePort</wsdl-port>
        <service-endpoint-interface>com.foo.FooServiceEndpoint</service-endpoint-interface>
        <service-impl-bean>
                <ejb-link>FooServiceBean</ejb-link>

        </service-impl-bean>
    </port-component>
</webservice-description>

From the foo.xsd

<xs:complexType name="AttachmentElementType">
     <xs:annotation>
      <xs:documentation>Attachment data. When submitting, contains the attachment itself.</xs:documentation>
     </xs:annotation>
     <xs:simpleContent>
      <xs:extension base="xs:base64Binary">
       <xs:attribute name="filename" use="required">
        <xs:annotation>
         <xs:documentation>The filename of the attachment</xs:documentation>
        </xs:annotation>
       </xs:attribute>
       <xs:attribute name="href" type="xs:anyURI" use="optional">
        <xs:annotation>
         <xs:documentation>The URL from which the attachment can be downloaded. Not used when submitting news.</xs:documentation>
        </xs:annotation>
       </xs:attribute>
       <xs:attribute name="mimeType" type="xs:string" use="required">
        <xs:annotation>
         <xs:documentation>The MIME type of the attached file</xs:documentation>
        </xs:annotation>
       </xs:attribute>
      </xs:extension>
     </xs:simpleContent>
    </xs:complexType>

From FooService-mapping.xml

<java-xml-type-mapping>
      <java-type>foo.MessageElementType</java-type>
      <root-type-qname xmlns:typeNS='http://foo/newsws/types'>typeNS:MessageElementType</root-type-qname>
      <qname-scope>complexType</qname-scope>
      <variable-mapping>
       <java-variable-name>category</java-variable-name>
       <xml-element-name>category</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>type</java-variable-name>
       <xml-element-name>type</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>headline</java-variable-name>
       <xml-element-name>headline</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>body</java-variable-name>
       <xml-element-name>body</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>attachment</java-variable-name>
       <xml-element-name>attachment</xml-element-name>
      </variable-mapping>
      <variable-mapping>
       <java-variable-name>field</java-variable-name>
       <xml-element-name>field</xml-element-name>
      </variable-mapping>
     </java-xml-type-mapping>

And Attachment.java looks like this:

public class  AttachmentElementType
{

protected java.lang.String filename;

protected java.net.URI href;

protected java.lang.String mimeType;

protected byte[] _value;
public AttachmentElementType(){}

public AttachmentElementType(java.lang.String filename, java.net.URI href, java.lang.String mimeType, byte[] _value){
this.filename=filename;
this.href=href;
this.mimeType=mimeType;
this._value=_value;
}
public java.lang.String getFilename() { return filename ;}

public void setFilename(java.lang.String filename){ this.filename=filename; }

public java.net.URI getHref() { return href ;}

public void setHref(java.net.URI href){ this.href=href; }

public java.lang.String getMimeType() { return mimeType ;}

public void setMimeType(java.lang.String mimeType){ this.mimeType=mimeType; }

public byte[] get_value() { return _value ;}

public void set_value(byte[] _value){ this._value=_value; }

}
From stackoverflow
  • Soved this by reimplenting the service as a JAX-WS annotated webservice, following the same structure and using the same business logic. Not fun, but it worked.

.NET : How to validate XML file with DTD without DOCTYPE declaration

I have an XML file with no DOCTYPE declaration that I would like to validate with an external DTD upon reading.

Dim x_set As Xml.XmlReaderSettings = New Xml.XmlReaderSettings()
x_set.XmlResolver = Nothing
x_set.CheckCharacters = False
x_set.ProhibitDtd = False
x = XmlTextReader.Create(sChemin, x_set)

How do you set the path for that external DTD? How do you validate?

From stackoverflow
  • Could you create an Xml.XmlDocument with the DTD you want, then append the XML file data to the in-memory Xml.XmlDocument, then validate that?

  • I have used the following function successfully before, which should be easy to adapt. How ever this relies on creating a XmlDocument as magnifico mentioned. This can be achieved by:

    XmlDocument doc = new XmlDocument();
    doc.Load( filename );
    doc.InsertBefore( doc.CreateDocumentType( "doc_type_name", null, DtdFilePath, null ), 
     doc.DocumentElement );
    
    
    /// <summary>
    /// Class to test a document against DTD
    /// </summary>
    /// <param name="doc">XML The document to validate</param>
    private static bool ValidateDoc( XmlDocument doc )
    {
     bool isXmlValid = true;
     StringBuilder xmlValMsg = new StringBuilder();
    
     StringWriter sw = new StringWriter();
     doc.Save( sw );
     doc.Save( TestFilename );
    
     XmlReaderSettings settings = new XmlReaderSettings();
     settings.ProhibitDtd = false;
     settings.ValidationType = ValidationType.DTD;
     settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
     settings.ValidationEventHandler += new ValidationEventHandler( delegate( object sender, ValidationEventArgs args )
     {
      isXmlValid = false;
      xmlValMsg.AppendLine( args.Message );
     } );
    
     XmlReader validator = XmlReader.Create( new StringReader( sw.ToString() ), settings );
    
     while( validator.Read() )
     {
     }
     validator.Close();
    
     string message = xmlValMsg.ToString();
     return isXmlValid;
    }
    

Storing username that last modified database row via EJB3.0 and JPA

I'd like to store username that has last modified table row to as a field in every table.

I have following setup: an user logs in, web layer calls some EJB 3.0 beans. Those EJB beans create and modify some JPA entities. Now, I'd like that username (from weblayer) would be automatically stored to every JPA entity (and database row) that is created or modified during EJB method call.

I have this kind of table, (that is: every table has field modifier):

CREATE TABLE my_table (
  some_data INTEGER,
  modifier VARCHAR(20)
);

By automatically I mean, that I wouldn't need to set manually username to each entity inside EJB methods.

You could achive this by storing username to ThreadLocal variable and fetching username from ThreadLocal in JPA entity's EntityListener. However this works only you are using a local EJB call, it will not work with EJB calls that cross JVM boundaries. I'd like to make this work over remote EJB method calls.

It this possible at all?

I am using Weblogic Server 10.3, EJB3.0 and EclipseLink JPA. I am also interested in hearing if this works with other JPA implementations.

From stackoverflow
  • You can use an EJB interceptor (@Around) on the EJB class to get the current user (using standard EJB api) and storing the name in the threadlocal variable. This would work transparently for remote and local calls.