Xml string in Java - forbidden characters for data?

Hi there,
In my java class I am building a xml string and saving it as a xml file in the hard drive. Later when I open the file in the XML editor it gets errors "forbidden characters". I think the problem is that in the data there can be characters as & or <> and of course that would disturbe the xml structure. Is there any smart method in Java which convert all the forbidden characters for xml data?... many thanks for any hints.

emailkia wrote:
In my java class I am building a xml string and saving it as a xml file in the hard drive. I am guessing that you are building a string into which you are putting what you think is xml.
And it isn't.
So the real solution is to build it correctly in the first place.
Is there any smart method in Java which convert all the forbidden characters for xml data?There are also libraries that will allow you to build xml which handle those sorts of issues for you.

Similar Messages

  • Trying To Insert XML String Greater Than 4000 Characters in PHP Fails

    Dear Sir,
    Subject:-Trying To Insert XML String Greater Than 4000 Characters in PHP Fails ORA-01704.
    In an attempt to design web app in PHP and inserting data into "CLOB" field of "articles" table associated with it, returning ORA-01704: string literal too long error.
    Platform: OEL5
    Database 11g(11.0.7.0)
    php : 5.2
    I refer to oracle document ID: [ID 336888.1] it is asking to contact support.
    Please help us in this regards.
    Many Thanks,
    mkyazdani

    Hi,
    I appreciate you, yes it is similar i have referred that manual and also inform to our php developer about the changes we need to make in our php script.
    Regards,
    mkyazdani

  • XML string from Java

    Hi
    I have requirement in which i have a jsp that i use to get information from users. I need to convert the info to XML data into a String , whihc i later use to pass as messages using AQ.
    I also have to, at a later point retreive the data from the XML String, update some information and recreate the XML string object with the new data.
    I do not want to use the XML SQL Utility as this could provide too costly in terms of database hits .
    Is there some XML Parser methods i can use to do the generation and retrieval of XML data into Strings.
    Thanks
    null

    Sort of hack but the way I did it was
    Convert to String:
    Construct a ByteArrayOutputStream
    print your documenet to this,
    and then call the toString() on the
    ByteArrayOutputStream.
    Convert from String to an XMLDocument:
    Construct a StringReader(String s)
    Construct a DOMParser and parse the
    StringReader.
    Hope this helps.
    null

  • Specify xml string in .java file?

    I have a class A in a .java file where I would like to specify a string which is a xml snippet:
    public class A  {
    public String getXmlString() {
    String myXmlString = "<?xml version="1.0"?>
    <catalog>
       <book id="bk101">
          <author>Gambardella, Matthew</author>
          <title>XML Developer's Guide</title>
          <genre>Computer</genre>
          <price>44.95</price>
          <publish_date>2000-10-01</publish_date>
          <description>An in-depth look at creating applications
          with XML.</description>
       </book>
    </catalog>"
    }But that does not compile. I have tried to use the escape \\ charater for the qoutes and angle brackets but that does not solve the problem. How do I specify a string with xml content in a class?

    georgemc wrote:
    killfinsmiltesn wrote:
    I am new here and read this article and agree with this topic.Thanks to share your thought with us.Sure. I think you're a spamming clown.I agree.
    Spam and spammer blocked (again!)
    db

  • What is the best data type to store XML string

    Hello all,
    If we want to store a XML string in oracle database table for some other program use what is the best data type that we can use in the table to store this XML string..
    Is it VARCHAR? or can we use BLOB type
    Anybody to help please
    Message was edited by:
    user483578

    If your XML data will not be larger than 4000 characters then use VARCHAR2 else CLOB. I don't see a need to use BLOB (unless your XML data contains binary information).

  • Inserting XML String into Table with help of Stored Proc

    I will be getting XML String from JAVA, which I have to insert in Table A, XML String is as follows
    <?xml version = '1.0'?>
    < TableA>
    <mappings Record="3">
    < MESSAGEID >1</ MESSAGEID >
    < MESSAGE >This  is available at your address!</ MESSAGE>
    </mappings>
    <mappings Record="3">
    < MESSAGEID >2</ MESSAGEID>
    < MESSAGE >This isn’t available at your address. </ MESSAGE>
    </mappings>
    </ TableA >
    Table Structure*
    MESSAGEID     VARCHAR2(15 BYTE)
    MESSAGE     VARCHAR2(500 BYTE)
    This is the stored procedure which I have written to insert data into TableA, V_MESSAGE will be input parameter for inserting XML String 
    create or replace procedure   AP_DBI_PS_MESSAGE_INSERT
    V_MESSAGE VARCHAR2(1024)
    AS
    declare
    charString varchar2(80);
    finalStr varchar2(4000) := null;
    rowsp integer;
    V_FILEHANDLE UTL_FILE.FILE_TYPE;
    begin
    -- the name of the table as specified in our DTD
    xmlgen.setRowsetTag('TableA');
    -- the name of the data set as specified in our DTD
    xmlgen.setRowTag('mappings');
    -- for getting the output on the screen
    dbms_output.enable(1000000);
    -- open the XML document in read only mode
    v_FileHandle := utl_file.fopen(V_MESSAGE);
    --v_FileHandle := V_MESSAGE;
    loop
    BEGIN
    utl_file.get_line(v_FileHandle, charString);
    exception
    when no_data_found then
    utl_file.fclose(v_FileHandle);
    exit;
    END;
    dbms_output.put_line(charString);
    if finalStr is not null then
    finalStr := finalStr || charString;
    else
    finalStr := charString;
    end if;
    end loop;
    -- for inserting the XML data into the table
    rowsp := xmlgen.insertXML('ONE.TableA',finalStr);
    dbms_output.put_line('INSERT DONE '||TO_CHAR(rowsp));
    xmlgen.resetOptions;
    end;Please Help
    Edited by: 846857 on Jul 18, 2011 10:55 PM

    with t as (select xmltype('<TableA >
                               <mappings Record="3">
                               <MessageId>1</MessageId>
                               <Message> This bundle is available at your address!</Message>
                               </mappings>
                               <mappings Record="3">
                               <MessageId>2</MessageId>
                               <Message>This isn’t available at your address. </Message>
                               </mappings>
                               </TableA  >') col FROM dual)
      --End Of sample data creation with subquery factoring.
      --You can use the query from here with your table and column name.
    select EXTRACTVALUE(X1.column_value,'/mappings/MessageId') MESSAGEID
          ,EXTRACTVALUE(X1.column_value,'/mappings/Message') MESSAGE
    from t,table(XMLSEQUENCE(extract(t.COL,'/TableA/mappings'))) X1;Above Code works as i get result
    MESSAGEID     MESSAGE
    1             This bundle is available at your address!
    2             This isn’t available at your address.
    _____________________________________________ now I want to insert the result into Table A... How to proceed... Please help
    Edited by: 846857 on Jul 19, 2011 12:15 AM

  • To convert  XML String- ResultSet

    Hi
    I am using Web Services created in EJB and will be accessed from JSP client containing applet-swing based GUI, using n tier architecture so I need to convert the XML String to Java ResultSet. (I am able to convert the ResultSet -> XML string using ResultSetBuilder), So I just want to know how to convet the XML String to Java ResultSet.
    Secondly is there any method to manually add columns to the ResultSet.
    Will anybody tell me of any utility, tools or the methods so that I can accomplish this task.
    Thank in advance
    nitin

    What would be the point of doing this? A ResultSet is basically like a cursor running against a database query. You could create a fake ResultSet and pass it something else but why? Just use a normal data-structure.

  • Is there a way to execute a procedure referenced in an XML string?

    The XML string can contain a stand-alone procedure/function or one within a package. The procedure/functions themselves may contain any number of inputs or outputs for procedures. I'm not sure how the procedure that will process this XML string will "know" the datatypes for the IN/OUT parameters for any given stored program. Does Oracle have any built-in mechanism that will execute stored procs in an XML, or would I have to write something that loops through the XML, extracting the proc names, parameters, and parameter values, then query the data dictionary for what type of OUT parameter data type should be used?
    I am told that SQL*Server is able to execute procs reference in XML, so I'm assuming Oracle must have some sort of API to use as a gateway for executing a procedure.

    Hi ,
    Open your edgeProject/index_edgeActions.js.Replace the following with single line comment. Open in edge animate 2014 and publish again. Published content will work
             /*================================================================================
             change Q number to match breakers || Q should = breakers +1 to account for 0 value if no BK0 exists
                     |    |
                     |    |
                     |    |                   DOUBLE CHECK BECAUSE OF BK0
                     |    |
                     |    |
                     |    |
                   __|    |__
             ================================================================================*/
    Like this.
             //================================================================================
             //change Q number to match breakers || Q should = breakers +1 to account for 0 value if no BK0 exists
             //        |    |
             //        |    |
             //        |    |                   DOUBLE CHECK BECAUSE OF BK0
             //        |    |
             //        |    |
             //        |    |
             //      __|    |__
             //================================================================================

  • I want to transform an object into a XML-String

    Hallo,
    in my BSP I want to transform an object into a xml string to set a server side cookie.
    Therefore my code is:
      DATA:
        lv_xml      TYPE string,
        lv_username TYPE string.
    model    ?= get_model( model_id = 'main' ).
      lv_username = sy-uname.
      Call TRANSFORMATION id SOURCE o = model  RESULT XML lv_xml.
      cl_bsp_server_side_cookie=>set_server_cookie(
            name                  = 'MODEL'
            application_name      = runtime->application_name
            application_namespace = runtime->application_namespace
            username              = lv_username
            session_id            = runtime->session_id
            data_value            = lv_xml
            data_name             = 'MODEL'
            expiry_time_rel       = 3600 ).
    But after the command "Call Transformation" the xml-string doesn't contain all the data of my object, only this:
    <?xml version="1.0" encoding="iso-8859-1"?>#<asx:abap xmlns:asx="http://www.sap.com/abapxml" version="1.0"><asx:values><O href="#o19"/></asx:values><asx:heap xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:abap="http://www.sap.com/abapxml/types/built-in" xmlns:cls="http://www.sap.com/abapxml/classes/global" xmlns:dic="http://www.sap.com/abapxml/types/dictionary"> <cls:ZCL_M_ESS_TRV_OVW id="o19"/
    ></asx:heap></asx:abap>
    What is wrong?
    Regards.
    Martin

    see thread nr.: Re: Call transformation with an object

  • How to Search for a Date in a string having both characters and date

    Hi ,
      I have a requirement to search DATE in the String having Both Characters and DATE . Please kindly let me know as early as possible.
    Regards
    Anil Kumar K

    Try to use SEARCH command with the pattern, making the pattern as fine as it can, like if you have your date in the format 02/23/2007, you can give
    SEARCH STRING FOR ' //'. (assuming the date has at least a single blank before it)
    WRITE:  SY-SUBRC UNDER 'SY-SUBRC',
    SY-FDPOS UNDER 'SY-FDPOS'.
    SY-FDPOS is set to offset of the string from which you can get the date value
    Refer here
    http://help.sap.com/saphelp_47x200/helpdata/en/fc/eb33cc358411d1829f0000e829fbfe/frameset.htm
    It would have been better if there is something like UNIX "regular expression" matching in ABAP

  • HTTP transport error: javax.xml.soap.SOAPException: java.security.PrivilegedActionException: javax.xml.soap.SOAPException: Message send failed: String index out of range: -7

    All -
    I'm new to consuming web services in JDeveloper. I'm using Oracle JDEV 10.1.3.3/OC4J.  I'm using this version since it is compatible with Oracle EBS 12.1.3.  My intent is to pull data from our third party recruitment app (Success Factors) and load that data into Oracle HRIS.  I'm already doing this through a .NET application.  I'm converting it to be a Java Concurrent Program in EBS.  The code listed below is a stub call to verify I'm on the right track. I created a JDeveloper Web Services proxy project.  I'm testing it locally on my windows desktop.  When I'm able to consume the service successfully, then I'll think about moving it to the EBS server.
    I'm getting the following error when I invoke the following service:
    HTTP transport error: javax.xml.soap.SOAPException: java.security.PrivilegedActionException: javax.xml.soap.SOAPException: Message send failed: String index out of range: -7
    End point is: https://api4.successfactors.com/sfapi/v1/soap?wsdl
    Any help/assistance would be much appreciated. 
    Below is my code and output of my test:
    package emsc.oracle.apps.emscper.sfapi.proxy;
    import HTTPClient.HTTPConnection;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.IsValidSession;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.IsValidSessionResponse;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.Login;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.LoginResponse;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.LoginResult;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.Logout;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.LogoutResponse;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.SFCredential;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.SFParameter;
    import emsc.oracle.apps.emscper.sfapi.proxy.types.sfobject_sfapi_successfactors_com.Error;
    import java.io.File;
    import javax.xml.rpc.ServiceFactory;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Date;
    import javax.xml.ws.BindingProvider;
    import javax.xml.soap.SOAPException;
    import java.util.Map;
    import oracle.security.ssl.OracleSSLCredential;
    public class SFAPITest {
        // Declare members:      
        private String companyId;
        private String userName;
        private String password;
        private String developerKey;
        private Date   effDt;
        private String greaterThanEffDt;
        private String lessThanEffDt;
        // Declare constants:      
        final static private String breakLine = "+---------------------------------------------------------------------------+";
        final static private String format    = "yyyy-mm-dd";      
        private enum ReqId {
            PrimaryReq(25),
            PrimaryReqCEO(26),
            EmCarePrimary(27),
            RTI(28),
            EmCareClinical(29);
            private int reqId; 
            private ReqId() {
            private ReqId(int value) {
                reqId = value;
            public int getReqId() {
                return reqId;
        // Getters and Setters:  
        protected String getCompanyId() {
           return this.companyId;
        protected void setCompanyId(String value) {
           this.companyId = value;                 
        protected String getUserName() {
           return this.userName;
        protected void setUserName(String value) {
           this.userName = value;                 
        protected String getPassword() {
           return this.password;
        protected void setPassword(String value) {
           this.password = value;                 
        protected String getDeveloperKey() {
           return this.developerKey;
        protected void setDeveloperKey(String value) {
           this.developerKey = value;                 
        protected Date getEffDt() {
            return this.effDt;
        protected void setEffDt(Date value) {
            this.effDt = value;                 
        protected String getGreaterThanEffDt() {
           return this.greaterThanEffDt;
        protected void setGreaterThanEffDt(String value) {
           this.greaterThanEffDt = value;                 
        protected String getLessThanEffDt() {
           return this.lessThanEffDt;
        protected void setLessThanEffDt(String value) {
           this.lessThanEffDt = value;                 
        public void runProgram()
            SFAPIService mySFAPIService;
            String CompletionText = "";
            String effDtStr2 = null;
        /* Code your program logic here.
        * Use getJDBCConnection method to get the connection object for any
        * JDBC operations.
        * Use CpContext provided commit,rollback methods to commit/rollback
        * data base transactions.
        * Don't forget to release the connection before returning from this
        * method.
        /* Call setCompletion method to set the request completion status and
        * completion text.
        * Status values are ReqCompletion.NORMAL,ReqCompletion.WARNING,
        * ReqCompletion.ERROR.
        * Use Completion text message of length 240 characters. If it is more
        * than 240 then full string will appear in log file and truncated 240
        * characters will be used as request completion text.
        try
            ServiceFactory factory = ServiceFactory.newInstance();
            mySFAPIService = (emsc.oracle.apps.emscper.sfapi.proxy.SFAPIService)factory.loadService(emsc.oracle.apps.emscper.sfapi.proxy.SFAPIService.class);      
            SFAPI api = mySFAPIService.getSFAPI();
           /// SFAPI api = new SFAPI();
            //Map<String, Object> requestContext = ((BindingProvider) api).getRequestContext();
            //requestContext.put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
            System.out.println("ServiceName => " + mySFAPIService.getServiceName().toString());
            System.out.println("End Point   => " + mySFAPIService.getServiceName().toString());
            System.out.println(breakLine);
            // Authentication: Login to SFAPI:
            SFCredential credential = new SFCredential();
            // Fake credentials being passed in for this post:   
            credential.setCompanyId("XXX");
            credential.setUsername("XXX");
            credential.setPassword("XXX");
            credential.setDeveloperKey("XXX");
            HTTPConnection httpsConnection = null;       
            OracleSSLCredential _credential = new OracleSSLCredential();      
            _credential.setWallet("\\\\\\C:\\Program Files\\Java\\jdk1.6.0_33\\jre\\lib\\security", "ParkEstes3");
            /*System.setProperty("javax.net.ssl.trustStore","C:\\\\\OraHome_1\\jdev\\jdevbin\\jdk\\jre\\lib\\security\\keystore");
            System.setProperty("javax.net.ssl.trustStorePassword","changeit");  
            System.out.println(System.getProperty("javax.net.ssl.trustStore"));*/
            // SFParameter: Define a generic SFParameter List.  This is a necessary parameter
            // to invoking calls in SFAPI:      
             /*System.setProperty("javax.net.ssl.keyStore",
             "file:\\\C:\\jdk1.4.1\\jre\\lib\\security\\client.keystore");
             System.setProperty("javax.net.ssl.keyStorePassword","welcome");         */
            /*  System.setProperty("oracle.net.wallet_location",
                          "(SOURCE=(METHOD=file)(METHOD_DATA=(DIRECTORY=\\\C:\Users\dparrish\Oracle\WALLETS)))");  // (2)                     */
            File kstore = new File("C:\\OraHome_1\\jdev\\jdevbin\\jdk\\jre\\lib\\security\\jssecacerts");
            boolean exists = kstore.exists();
            if (!exists) {
                System.out.println("Keystore does not exist");
            else {
                System.out.println("Keystore does exist");
            System.setProperty("javax.net.ssl.trustStore", kstore.getAbsolutePath());
            System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
            //System.setProperty("proxySet", "false");
            //System.setProperty("http.proxyHost", "127.0.0.1");
            //System.setProperty("http.proxyPort", "8080");
            System.out.println(kstore.getAbsolutePath());
            List<SFParameter> lst = new ArrayList<SFParameter>();
            SFParameter param = new SFParameter();
            param.setName("");
            param.setValue("");
            lst.add(param);      
            SFParameter[] sfParam = lst.toArray(new SFParameter[lst.size()]);
            Login login = new Login();
            try {
                login.setCredential(credential);
                System.out.println("1");
                login.setParam(sfParam);
                System.out.println("2");
                LoginResponse loginResponse = new  LoginResponse();
                LoginResult loginResult = new LoginResult();
                try {
                     loginResponse = api.login(login);               
                catch (Exception e ) {
                    System.out.println(e.getMessage());
                System.out.println("3");
                try {               
                     loginResult = loginResponse.getResult();
                catch (Exception e ) {
                    System.out.println(e.getMessage());
                System.out.println("4");
                IsValidSession vs = new IsValidSession();                  
                IsValidSessionResponse isValidSessionResponse = api.isValidSession(vs);
                System.out.println("5");
                if (isValidSessionResponse.isResult()) {
                     System.out.println("Session is valid");
                     System.out.println("Result => " + loginResult.getSessionId());
                     System.out.println(breakLine);              
                    Logout logout = new Logout();
                    LogoutResponse logoutResponse = api.logout(logout);
                    if (logoutResponse.isResult()) {
                         System.out.println("Logout of SFAPI Successful");
                    else {
                        System.out.println("Logout of SFAPI Unsuccessful");
                else {
                     System.out.println("Session is invalid");
                    List<Error> errors = new ArrayList<Error>();
                    for (int i = 0; i < loginResult.getError().length;  i++) {
                        errors.add(loginResult.getError()[i]);
                    for (int i = 0; i < errors.size(); i++) {
                         System.out.println("Error Indice   => " + i);
                         System.out.println("Error Code:    => " + errors.get(i).getErrorCode());
                         System.out.println("Error Message: => " + errors.get(i).getErrorMessage());
                         System.out.println(breakLine);                                                          
                    } // end for loop of SFObject errors
                } // end InvalidSession
            catch (Exception e)
                 System.out.println("Session Credential Exception");
                 System.out.println("Exception => " + e.getMessage());
                 System.out.println(breakLine);                   
        catch (Exception e)
            System.out.println("Parameter List Exception");
            System.out.println("Exception => " + e.getMessage());
            System.out.println(breakLine);
        }   // end runProgram
        // Constructor:
        public SFAPITest()  {
        } // end constructor
        public static void main (String args[]) {
            try
                SFAPITest test = new SFAPITest();        
                test.runProgram();
            catch (Exception e) {
                System.out.println("main exception => " + e.getMessage());
    } // SFAPITest
    Here is the output with trace:
    WARNING: Unable to connect to URL: https://api4.successfactors.com:443/sfapi/v1/soap due to java.security.PrivilegedActionException: javax.xml.soap.SOAPException: Message send failed: String index out of range: -7
    Session Credential Exception
    Exception => ; nested exception is:
        HTTP transport error: javax.xml.soap.SOAPException: java.security.PrivilegedActionException: javax.xml.soap.SOAPException: Message send failed: String index out of range: -7
    +---------------------------------------------------------------------------+
    Process exited with exit code 0.

    The other end is throwing back a programming error.
    That might be because you are sending incorrect data and the other end fails to validate it.
    You might be able to guess based on your C# code.  But, since you are using soap one generic solution is available to you.
    - Get an http proxy interceptor like wireshark.
    - Run it while your C# app runs, collect the http requests from that.
    - Run it while running your java code, collect the http requests from that.
    Compare the two.

  • XML String as input parm for WS?

    Hi All.
    This has probably been asked and answered a few times, but I can't seem to find a exact answer to my scenario:
    I have a java method that accepts a string as a input parm. However, the string will contain a fully formatted XML string eg:
    <?xml version=\"1.0\" standalone=\"yes\"?>
    <CAMPUS_UPD>
    <MSG_SEQ_NO>NATX_00000000000000200609141569398</MSG_SEQ_NO>
    <EVENT_NAME>CAMPUS_UPD.UPD</EVENT_NAME>
    <STATUSCODE>000</STATUSCODE>
    <CAMPUS_KODE>01</CAMPUS_KODE>
    <CAMPUS_NAME>STELLENBOSCH</CAMPUS_NAME>
    </CAMPUS_UPD>
    I'm basically going to put this XML string directly onto a InterConnect AQ Table for consumption by Interconnect.
    Now naturally I get a VERY strange set of errors when I actually try to call the WS with this XML String.
    <HTML><HEAD><TITLE>Web Service</TITLE></HEAD><BODY><H1>Bad Request</H1><PRE>Error parsing envelope: (4, 30) PI with the name 'xml' can occur only in the beginning of the document.</PRE></BODY></HTML>
    If I remove the first line of the XML string, the error message changes to:
    <?xml version="1.0" encoding="UTF-8"?>
    <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns0="http://sun.oic.ws/types/"><env:Body><env:Fault><faultcode>env:Client</faultcode><faultstring>caught exception while handling request: deserialization error: unexpected XML reader state. expected: END but found: START: KAMPUS_UPD</faultstring></env:Fault></env:Body></env:Envelope>
    Any Ideas/suggestions/wild speculations/URL's etc.
    Kind Regards
    Elmar Matthee
    University of Stellenbosch
    South Africa

    Hi Eric/all.
    Just thought I'd give a follow up on my progress.
    Got the web services working and finally able to test via Jdev. Seems the problem was with the proxy server settings of jdeveloper itself. I had localhost specified as an ip NOT to use a proxy server for, but when the test code got generated it used the actual ip of my machine (where the application server is also running) to access the web service, and thats where it got stuck.
    I actually sent along the embedded xml string in a string parameter directly to the the web service, and it worked like a charm (as opposed to testing it via the application server administration web page where I had to translate the < and > characters. So quite chuffed with that.
    Today I'm researching a) What happens when you have a complex data type (i.e. a java class containing 3 fields like username/fullname/age) from a web service. When I test it via the application server web page, I get the actual fields with their names and values in an xml type format back, but when I test it via java, i get a reference to the object. Now I could cast the result back into the class definition that I used when creating the web service, but what if I don't know what that is (i.e. someone else somewhere wrote the WS, and I have no idea about implementation)?
    b) related to a) is how to convert the complex data type return value into an XML string before sending the reply (or maybe even a pure String containing the XML data). I.e. instead of sending a Person class, I send back an XML data type containing the relevant data with tags and all. I'm a bit worried about this, because it looks as if the data is alreaddy actually coming back in an XML format, its just that the java test program doesn't see it that way, and I'm loath add the extra overhead if it isn't needed.
    c) related to both a) and b). How the @$#@ does one actually use/call a web service in a simple .jsp page? Seemingly a simple question, but thus far, the answer eludes me. :)
    Any thoughts/comments/ideas/wild speculations/urls welcome.
    Kind Regards.
    Elmar

  • How to store xml data into file in xml format through java program?

    HI Friends,
    Please let me know
    How to store xml data into file in xml format through java program?
    thanks......
    can discuss further at messenger.....
    Avanish Kumar Singh
    Software Engineer,
    Samsung India Development Center,
    Bangalore--560001.
    [email protected]

    Hi i need to write the data from an XML file to a Microsoft SQL SErver database!
    i got a piece of code from the net which allows me to parse th file:
    import java.io.IOException;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import org.apache.xerces.parsers.SAXParser;
    import java.lang.*;
    public class MySaxParser extends DefaultHandler
    private static int INDENT = 4;
    private static String attList = "";
    public static void main(String[] argv)
    if (argv.length != 1)
    System.out.println("Usage: java MySaxParser [URI]");
    System.exit(0);
    String uri = argv[0];
    try
    XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
    MySaxParser MySaxParserInstance = new MySaxParser();
    parser.setContentHandler(MySaxParserInstance);
    parser.parse(uri);
    catch(IOException ioe)
    ioe.printStackTrace();
    catch(SAXException saxe)
    saxe.printStackTrace();
    private int idx = 0;
    public void characters(char[] ch, int start, int length)
    throws SAXException
    String s = new String(ch, start, length);
    if (ch[0] == '\n')
    return;
    System.out.println(getIndent() + " Value: " + s);
    public void endDocument() throws SAXException
    idx -= INDENT;
    public void endElement(String uri, String localName, String qName) throws SAXException
    if (!attList.equals(""))
    System.out.println(getIndent() + " Attributes: " + attList);
    attList = "";
    System.out.println(getIndent() + "end document");
    idx -= INDENT;
    public void startDocument() throws SAXException
    idx += INDENT;
    public void startElement(String uri,
    String localName,
    String qName,
    Attributes attributes) throws SAXException
    idx += INDENT;
    System.out.println('\n' + getIndent() + "start element: " + localName);
    if (localName.compareTo("Machine") == 0)
    System.out.println("YES");
    if (attributes.getLength() > 0)
    idx += INDENT;
    for (int i = 0; i < attributes.getLength(); i++)
    attList = attList + attributes.getLocalName(i) + " = " + attributes.getValue(i);
    if (i < (attributes.getLength() - 1))
    attList = attList + ", ";
    idx-= INDENT;
    private String getIndent()
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < idx; i++)
    sb.append(" ");
    return sb.toString();
    }// END PRGM
    Now , am not a very good Java DEv. and i need to find a soln. to this prob within 1 week.
    The next step is to write the data to the DB.
    Am sending an example of my file:
    <Start>
    <Machine>
    <Hostname> IPCServer </Hostname>
    <HostID> 80c04499 </HostID>
    <MachineType> sun4u [ID 466748 kern.info] Sun Ultra 5/10 UPA/PCI (UltraSPARC-IIi 360MHz) </MachineType>
    <CPU> UltraSPARC-IIi at 360 MHz </CPU>
    <Memory> RAM : 512 MB </Memory>
    <HostAdapter>
    <HA> kern.info] </HA>
    </HostAdapter>
    <Harddisks>
    <HD>
    <HD1> c0t0d0 ctrl kern.info] target 0 lun 0 </HD1>
    <HD2> ST38420A 8.2 GB </HD2>
    </HD>
    </Harddisks>
    <GraphicCard> m64B : PCI PGX 8-bit +Accel. </GraphicCard>
    <NetworkType> hme0 : Fast-Ethernet </NetworkType>
    <EthernetAddress> 09:00:30:C1:34:90 </EthernetAddress>
    <IPAddress> 149.51.23.140 </IPAddress>
    </Machine>
    </Start>
    Note that i can have more than 1 machines (meaning that i have to loop thru the file to be able to write to the DB)
    Cal u tellme what to do!
    Even better- do u have a piece of code that will help me understand and implement the database writing portion?
    I badly need help here.
    THANX

  • Error in JSF  - java.lang.NumberFormatException: For input string:

    Nice day friends,
    I am sure that this is one stupid question by newbie like me, but I already lost hope since there no many post on this error especially in JSF at Google.
    Here the full error I've got :
    executePhase(RENDER_RESPONSE 6,com.sun.faces.context.FacesContextImpl@12bb287) threw exception
    java.lang.NumberFormatException: For input string: "id"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
    at java.lang.Integer.parseInt(Integer.java:447)
    at java.lang.Integer.parseInt(Integer.java:497)
    at javax.el.ListELResolver.toInteger(ListELResolver.java:373)
    at javax.el.ListELResolver.getValue(ListELResolver.java:167)
    Here my snippet of code :
    NationalityDO.java (managed bean)
    public class NationalityDO implements Serializable {
    @Id
    @Column(name = "ID", nullable = false)
    private String id;
    private List nationalityList;
    public NationalityDO() {
    public NationalityDO(String id) {
    this.id = id;
    public String getId() {
    return this.id;
    public void setId(String id) {
    this.id = id;
    public List getNationalityList(){
    NationalityDA da=new NationalityDA();
    if(nationalityList==null){
    System.out.println("if(nationalityList==null)");
    try {
    nationalityList=da.retrieveNationalityList();
    } catch (Exception ex) {
    ex.printStackTrace();
    return nationalityList;
    public void setNationalityList(){
    this.nationalityList=nationalityList;
    This is my NationalityDA (used to retrieve data)
    public class NationalityDA {
    public NationalityDA() {
    public List retrieveNationalityList() throws Exception{
    ArrayList ls=new ArrayList();
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rsReturn = null;
    try {
    con = DBManager.getDBConnection();
    String sql="select id,descr,setup_date,change_date from nationality order by id asc" ;
    ps = con.prepareStatement(sql);
    rsReturn = ps.executeQuery();
    while(rsReturn.next()){
    List lsNationality =new ArrayList();
    lsNationality.add(rsReturn.getString(1));//id
    lsNationality.add(rsReturn.getString(2));//descr
    ls.add(lsNationality);
    } catch(SQLException sqlex) {
    sqlex.printStackTrace();
    } finally {
    con.close();
    ps.close();
    return ls;
    Here my nationality.jsp
    <h:dataTable value='#{nationality.nationalityList}' var='item' border="1" cellpadding="2" cellspacing="0">
    <h:column>
    <f:facet name="header">
    <h:outputText value="Id"/>
    </f:facet>
    <h:outputText value="#{item.id}"/>
    </h:column>
    <h:column>
    <f:facet name="header">
    <h:outputText value="Descr"/>
    </f:facet>
    <h:outputText value="#{item.descr}"/>
    </h:column>
    </h:dataTable>
    Here my face-config.xml
    <managed-bean>
    <managed-bean-name>nationality</managed-bean-name>
    <managed-bean-class>com.dataobject.nationality.NationalityDO</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
    <navigation-case>
    <from-outcome>success</from-outcome>
    <to-view-id>/nationality/testNationality.jsp</to-view-id>
    </navigation-case>
    <navigation-case>
    <from-outcome>fail</from-outcome>
    <to-view-id>/nationality/testNationality.jsp</to-view-id>
    </navigation-case>
    </navigation-rule>
    For your information, the retrieve of data work successfully, this is the table description in oracle database which is varchar for id,
    SQL> desc nationality
    Name Null? Type
    ID NOT NULL VARCHAR2(4)
    DESCR VARCHAR2(20)
    SETUP_DATE TIMESTAMP(6)
    CHANGE_DATE TIMESTAMP(6)
    *If you feel that I should improve my writing in forum, I am really happy to know
    Thanks,
    unid

    thanks....
    Actually I already view the site many times before but after you told me then I get the idea,that's y working together is better, because i sometimes won't realize my mistake even it was the easiest one...
    So i just change my code in NationalityDA.java as
    while(rsReturn.next()){
    NationalityDO n=new NationalityDO();
    n.setId(rsReturn.getString(1));
    System.out.println("rsReturn.getString(1)"+ rsReturn.getString(1));
    n.setDescr(rsReturn.getString(2));
    System.out.println("rsReturn.getString(2)"+ rsReturn.getString(2));
    n.setSetupDate(rsReturn.getDate(3));
    System.out.println("rsReturn.getString(3)"+ rsReturn.getString(3));
    n.setChangeDate(rsReturn.getDate(4));
    System.out.println("rsReturn.getString(4)"+ rsReturn.getString(4));
    ls.add(n);
    Once again, thanks..and my 3 dukes are yours..
    -unid

  • How to get an XML string from a Java Bean without wrting to a file first ?

    I know we can save a Java Bean to an XML file with XMLEncoder and then read it back with XMLDecoder.
    But how can I get an XML string of a Java Bean without writing to a file first ?
    For instance :
    My_Class A_Class = new My_Class("a",1,2,"Z", ...);
    String XML_String_Of_The_Class = an XML representation of A_Class ?
    Of course I can save it to a file with XMLEncoder, and read it in using XMLDecoder, then delete the file, I wonder if it is possible to skip all that and get the XML string directly ?
    Frank

    I think so too, but I am trying to send the object to a servlet as shown below, since I don't know how to send an object to a servlet, I can only turn it into a string and reconstruct it back to an object on the server side after receiving it :
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class Servlet_Message        // Send a message to an HTTP servlet. The protocol is a GET or POST request with a URLEncoded string holding the arguments sent as name=value pairs.
      public static int GET=0;
      public static int POST=1;
      private URL servlet;
      // the URL of the servlet to send messages to
      public Servlet_Message(URL servlet) { this.servlet=servlet; }
      public String sendMessage(Properties args) throws IOException { return sendMessage(args,POST); }
      // Send the request. Return the input stream with the response if the request succeeds.
      // @param args the arguments to send to the servlet
      // @param method GET or POST
      // @exception IOException if error sending request
      // @return the response from the servlet to this message
      public String sendMessage(Properties args,int method) throws IOException
        String Input_Line;
        StringBuffer Result_Buf=new StringBuffer();
        // Set this up any way you want -- POST can be used for all calls, but request headers
        // cannot be set in JDK 1.0.2 so the query string still must be used to pass arguments.
        if (method==GET)
          URL url=new URL(servlet.toExternalForm()+"?"+toEncodedString(args));
          BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream()));
          while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
        else     
          URLConnection conn=servlet.openConnection();
          conn.setDoInput(true);
          conn.setDoOutput(true);           
          conn.setUseCaches(false);
          // Work around a Netscape bug
          conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
          // POST the request data (html form encoded)
          DataOutputStream out=new DataOutputStream(conn.getOutputStream());
          if (args!=null && args.size()>0)
            out.writeBytes(toEncodedString(args));
    //        System.out.println("ServletMessage args: "+args);
    //        System.out.println("ServletMessage toEncString args: "+toEncodedString(args));     
          BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
          while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
          out.flush();
          out.close(); // ESSENTIAL for this to work!          
        return Result_Buf.toString();               // Read the POST response data   
      // Encode the arguments in the property set as a URL-encoded string. Multiple name=value pairs are separated by ampersands.
      // @return the URLEncoded string with name=value pairs
      public String toEncodedString(Properties args)
        StringBuffer sb=new StringBuffer();
        if (args!=null)
          String sep="";
          Enumeration names=args.propertyNames();
          while (names.hasMoreElements())
            String name=(String)names.nextElement();
            try { sb.append(sep+URLEncoder.encode(name,"UTF-8")+"="+URLEncoder.encode(args.getProperty(name),"UTF-8")); }
    //        try { sb.append(sep+URLEncoder.encode(name,"UTF-16")+"="+URLEncoder.encode(args.getProperty(name),"UTF-16")); }
            catch (UnsupportedEncodingException e) { System.out.println(e); }
            sep="&";
        return sb.toString();
    }As shown above the servlet need to encode a string.
    Now my question becomes :
    <1> Is it possible to send an object to a servlet, if so how ? And at the receiving end how to get it back to an object ?
    <2> If it can't be done, how can I be sure to encode the string in the right format to send it over to the servlet ?
    Frank

Maybe you are looking for