Set JCO CLient via code

Hi All,
I need to use the same WD for several R/3 clients.
Is there a way that I could use several JCO reference and there for set the modeldata and the metadata reference that I need via code.
Regards,
Orlando Covault

Hi,
There are tow options for JCO creations:
1: If you know at design time which JCO connections you want to use and that they are available on your system: create a Model for every connection.
2: If you want to create these connections dynamically change the JCO connection everytime you call your model like this:
IWDDynamicRFCModel model;
model = (IWDDynamicRFCModel) WDModelFactory.getModelInstance(ModelName.class);
model.setJcoClient(connection)
--> continue calling code.
or:
model.setSystemName(<<JCO ClientName>>)
see: http://help.sap.com/javadocs/NW04S/current/wd/com/sap/tc/webdynpro/modelimpl/dynamicrfc/IWDDynamicRFCModel.html
Also you can refer the blog from Anilkumar Vippagunta at
/people/anilkumar.vippagunta2/blog/2007/02/06/dynamic-jco-creation
regards
amit bagati

Similar Messages

  • Stored Procedure parameter (@Carrier) used in report and can't be set via code

    I have a report that has regular Crystal parameters that I am setting correctly via code.  However, one report actually uses one of the database parameters from the stored procedure that the report was created from.  It is the only report like this and I'm using the same code in an attempt to set it's value.  Although no error is thown, if I look at the parameter value in the IDE it is set correctly, but the field on the report just shows up blank.  I have changed the way the report is created.  Previously, I used the report.export method to create the actual file via a stored procedure.  Now, I'm running the stored procedure first and creating a datatable.  This allows me to execute the SP only once to see if it has data, because only then do I want to create the actual report.  I'm using the SetDataSource method to pass the datatable into Crystal and then using the report.export method to create the report with data.  Everything seems to work, except this stored procedure parameter (@Carrier) is not actually being populated to display on the report.
    Not sure what to look at.  Any suggestions?
    Thanks.

    crpe32.dll is version 13.0.5.891.  This was developed in VS2012 and VB.NET.  I'm using ADO.Net to connect to a MS SQL Server database.
    MainReport.SetDataSource(DTbl)
    bRC = PopulateAllSubReports(MainReport)
    If Not bRC Then Throw New Exception("Received an error in PopulateAllSubReports.")
    bRC = PopulateCrystalParameters(MainReport, SP)
    If Not bRC Then Throw New Exception("Received an error in PopulateCrystalParameters.")
    'Actually create the output file.
    bRC = ExportData(MainReport)
    Private Function PopulateCrystalParameters(myReportDocument As ReportDocument, SP As ReportStoredProcedureCrystal) As Boolean
         Dim myParameterFieldDefinitions As ParameterFieldDefinitions = Nothing
         Dim myParameterFieldDefinition As ParameterFieldDefinition = Nothing, ParamValue As String = ""
         Dim bRC As Boolean, Param As SqlParameter = Nothing
         Try
         myParameterFieldDefinitions = myReportDocument.DataDefinition.ParameterFields
    '*********************Report Parameters***************************
         For Each myParameterFieldDefinition In myParameterFieldDefinitions
              myParameterFieldDefinition.CurrentValues.Clear()
              Select Case myParameterFieldDefinition.ParameterFieldName.Trim.ToUpper
              Case "@CARRIER"
                   If SP.DBParameters.ContainsKey("@CARRIER") Then
                        Param = SP.DBParameters("@CARRIER")
                        ParamValue = NullS(Param.Value).Trim
                        bRC = SetCurrentValueForParameterField(myParameterFieldDefinition, ParamValue)
                        If Not bRC Then Return False
                   End If                           
              End Select
         Next
         Return True
         Catch ex As Exception
         GmcLog.Error("ReportKey = " & Me.ReportKey.ToString & ", " & ex.Message, ex)
         Return False
         End Try
    End Function
    Private Function SetCurrentValueForParameterField(myParameterFieldDefinition As ParameterFieldDefinition, submittedValue As Object) As Boolean
         Dim currentParameterValues As ParameterValues = Nothing
         Dim myParameterDiscreteValue As ParameterDiscreteValue = Nothing
         Try
         myParameterDiscreteValue = New ParameterDiscreteValue
         myParameterDiscreteValue.Value = NullS(submittedValue).Trim
         currentParameterValues = New ParameterValues
         currentParameterValues.Add(myParameterDiscreteValue)
         myParameterFieldDefinition.ApplyCurrentValues(currentParameterValues)
         Return True
         Catch ex As Exception
         GmcLog.Error("ReportKey = " & Me.ReportKey.ToString & ", " & ex.Message, ex)
         Return False
         Finally
         myParameterDiscreteValue = Nothing
         currentParameterValues = Nothing
         End Try
    End Function
    Private Function SetDBSourceForSubReport(mySubReport As ReportDocument) As Boolean
         Dim myTables As Tables = Nothing, myTable As Table = Nothing, DTbl As DataTable, SP As StoredProcedure = Nothing
         Try
         myTables = mySubReport.Database.Tables
         For Each myTable In myTables
              Dim SPName As String = myTable.Location.Substring(0, myTable.Location.IndexOf(";"c))
              SP = New StoredProcedure(ConnectionString, SPName, CommandType.StoredProcedure)
              DTbl = SP.FillTable
              mySubReport.SetDataSource(DTbl)
              SP = Nothing
         Next
         Return True
         Catch ex As Exception
         GmcLog.Error("ReportKey = " & Me.ReportKey.ToString & ", " & ex.Message, ex)
         Return False
         Finally
         If Not SP Is Nothing Then SP = Nothing
         If Not myTable Is Nothing Then myTable = Nothing
         If Not myTables Is Nothing Then myTables = Nothing
         End Try
    End Function
    Private Function PopulateAllSubReports(myReportDocument As ReportDocument) As Boolean
         Try
         Dim mySections As Sections = myReportDocument.ReportDefinition.Sections
         For Each mySection As Section In mySections
              Dim myReportObjects As ReportObjects = mySection.ReportObjects
              For Each myReportObject As ReportObject In myReportObjects
                   If myReportObject.Kind = ReportObjectKind.SubreportObject Then
                        Dim mySubreportObject As SubreportObject = CType(myReportObject, SubreportObject)
                        Dim subReportDocument As ReportDocument = mySubreportObject.OpenSubreport(mySubreportObject.SubreportName)
                        Dim bRC = SetDBSourceForSubReport(subReportDocument)
                        If Not bRC Then Return False
                   End If
              Next
         Next
         Return True
         Catch ex As Exception
         GmcLog.Error("ReportKey = " & Me.ReportKey.ToString & ", " & ex.Message, ex)
         Return False
         End Try
    End Function

  • Error sending IDOC from JCO Client to PI AEX 7.3.1

    Hi All
    We have a requirement to send an IDOC from a non SAP System to our ECC via PI AEX :
    JCO.Client --> PI AEX --> SAP ECC
    At this time, we are testing this scenario with a JAVA Client with JCO Library (3.0.10).
    Destination to PI is OK
    Destination to our SAP ECC (for IDocRepository) is OK
    But by sending the IDOC to PI we are getting the following error, Exception is raised on the PI System and sent back to the JCO Client :
    com.sap.conn.jco.JCoException: (104) JCO_ERROR_SYSTEM_FAILURE: while trying to invoke the method java.lang.Object.hashCode() of an object loaded from local variable 'key' (raised by system <extern>|PiSystem)
        at com.sap.conn.jco.rt.MiddlewareJavaRfc.generateJCoException(MiddlewareJavaRfc.java:670)
        at com.sap.conn.jco.rt.MiddlewareJavaRfc$JavaRfcClient.execute(MiddlewareJavaRfc.java:1881)
        at com.sap.conn.jco.rt.ClientConnection.execute(ClientConnection.java:1120)
        at com.sap.conn.jco.rt.ClientConnection.execute(ClientConnection.java:953)
        at com.sap.conn.jco.rt.RfcDestination.execute(RfcDestination.java:1465)
        at com.sap.conn.jco.rt.AbapFunction.execute(AbapFunction.java:319)
        at com.sap.conn.idoc.jco.JCoIDoc.send(JCoIDoc.java:323)
        at com.sap.conn.idoc.jco.JCoIDoc.send(JCoIDoc.java:353)
        at sap_connector_examples.IDocClientExampleToJavaPO_pbs.main(IDocClientExampleToJavaPO_pbs.java:97)
    Caused by: RfcException: [<extern>|PiSystem]
        message: while trying to invoke the method java.lang.Object.hashCode() of an object loaded from local variable 'key'
        Return code: RFC_SYS_EXCEPTION(3)
        error group: 104
        key: RFC_ERROR_SYSTEM_FAILURE
    Exception raised by <extern>|PiSystem
    PI Destination:
    jco.destination.repository_destination=ABAP_AS_WITHOUT_POOL
    jco.client.gwhost=PiSystem
    jco.client.gwserv=sapgw01
    jco.client.tpname=XI_IDOC_DEFAULT_PID
    jco.client.type=E
    ECC Destination: (ABAP_AS_WITHOUT_POOL)
    jco.client.lang=en
    jco.client.client=100
    jco.client.passwd=****
    jco.client.user=User
    jco.client.sysnr=00
    jco.client.ashost=ECCSystem
    We have already set the PI VM System parameter  jco.allow_non_abap_partner to 1
    ECC User has S_RFC Rolle
    I will be thankful for any advise.
    Thank You
    Regards
    Stéphane

    Hi
    InboundRA (Resource Adapter) is green (Fully available).
    What do you mean by maintaining JCO RFC Destination in PI ?
    We have set the inboundRA Properties has follow :
    ProgramID : XI_IDOC_DEFAULT_PID
    DestinationName : XI_IDOC_DEFAULT_DESTINATION
    Local: true
    mutliRepository : ED1=XI_IDOC_DEFAULT_DESTINATION_ED1;ES4=XI_IDOC_DEFAULT_DESTINATION_ES4;MD1=XI_IDOC_DEFAULT_DESTINATION_MD1;ES1=XI_IDOC_DEFAULT_DESTINATION_ES1;PD1=XI_IDOC_DEFAULT_DESTINATION_PD1;
    GatewayServer and Service are pointing to our PI System
    BindingKey : PI_AAE_IDOC
    And for each Repository we created a destination in NWA pointing to the corresponding ECC System.
    (target host pointing to the ECC System and the Gateway host  pointing to the PI System)
    Our Installation isn't new but it is the first time we are configuring the System for this scenario:
    JCO.client --> PI AEX
    Regards
    Stéphane

  • JCo Client Programming and Error Handling

    Hi all,
    I was wondering if anybody could help me out with some advice on error handling when writing code to send messages to SAP via a JCo Client, particularly IDocs.
    I understand from my reading that IDocs are always sent asyncronously to the SAP system from JCo, using JCO.Client.send(). So it is possible (and I have some test code working to do this) to force an exception with say a malformed IDoc, and catch the exception in my code.
    But due to the asyncronous nature of the send functionality for IDoc, I cannot see any way of getting back any "business level" exceptions (e.g. Order Number does not exist, Unknown Material, etc.)
    So my question is, is it possible to receive any of these type of error messages when sending IDocs to an SAP system using JCo? Perhaps by setting up a JCo Server with the correct error/exception listeners to receive these messages - but are they even sent out in the way?
    If not what is the process for handling them?
    It is of course possible to look in the SAP system using txn WE02 and see the problem/error but that does not help me to propagate this back to the sending application or to maintain state alignment between the two apps.
    Any advice much appreciated!!
    Chris

    Hi Anil,
    you should check on those trheads:
    <a href="https://www.sdn.sap.com/irj/sdn/thread?messageID=3104772&#3104772">https://www.sdn.sap.com/irj/sdn/thread?messageID=3104772&#3104772</a>
    <a href="https://www.sdn.sap.com/irj/sdn/thread?messageID=579794&#579794">https://www.sdn.sap.com/irj/sdn/thread?messageID=579794&#579794</a>
    Regards,
    Gianluca Barile

  • Error connecting using JCO.Client: null

    Hi,
    I created a WD app which uses  the RFC FM.  I followed How-To-build-webdynpro.pdf document to create the WD and trying to deploy and run, I see the view page but when I trigger the action via button UI element I get following error as exception in the try catch block of execute method
    In the NWA I see
    Could not create JCOClientConnection for logical System: 'WD_MODELDATA_DEST' - Model
    An exception has occurred: Erorr accessing cache [region]='XCM_SESSION_SCOPE'.
    [EXCEPTION]
    com.sap.isa.core.cache.Cache$Exception: Cannot return access for region 'XCM_SESSION_SCOPE'. Cache is not ready
    I'm using following existing JCO definition by configuring them with correct parameters.  Tested them successfully
    WD_RFC_METADATA_DEST
    WD_MODELDATA_DEST
    What am I missing?  In SM04 tcode I see 2 connections are opened with 2 Megabyte not released for a long time.  I think if connections are released correctly it should drop to 1 megabyte.  Is there anything that I need to do just after execute method as shown below (I have replaced function module with <FM> in below code)
    try {
             wdContext.node<FM>_Input().current<FM>_Get_InputElement().modelObject().execute();
         } catch(Exception exception) {
              msgMgr.reportException(exception.getLocalizedMessage(), false);
          wdContext.nodeOutput().invalidate();
          msgMgr.reportSuccess("Success");
    The error is in the catch block which is displayed on the view page.
    Thanks
    Praveen
    I modified the above code and put in finally block to close the connections as follows, please let me know if this is OK.  I still get error message as "Error connecting using JCO.Client: null" but no additional connections in the SM04 after adding finally block.
    try {
             wdContext.node<FM>_Input().current<FM>_Get_InputElement().modelObject().execute();
         } catch(Exception exception) {
              msgMgr.reportException(exception.getLocalizedMessage(), false);
         }finally {
              // disconnect the connection
              wdContext.<FM>_Get_InputElement().modelObject().modelInstance().disconnectIfAlive();     
    Edited by: Praveen11 on Oct 5, 2009 9:06 AM

    Thanks Satish.
    The issue is resolved.  I think it was to do with permission, as I was running directly from NWDS deploy and run the session didn't have proper authorisation or something that was causing this error.
    When I copy pasted the URL in the correct browser session window I got no error and function module was successfully executed.   However the issue now is that values are not showing up in the view may be to do with mapping context or model  I'll review and post back as different thread.
    Thanks
    Praveen

  • URGENT: JCO.Client: null

    Hello
    We're using SAP EP 7.0 with webdynpro connected to SAP R3 4.6C by SapLogon Ticket.
    The connection can be done with certificates for our customers (authentification header) or via logon/password for internal test on our LAN.
    These webdynpro work fine on the LAN but when we connect via the web we have the error below :
    com.sap.tc.webdynpro.modelimpl.dynamicrfc.WDDynamicRFCExecuteException: Error connecting using JCO.Client: null
    Do you have any idea ?
    It's on our production environment so very urgent )
    Thanks

    Hi
    1.May be JCO's are not configured properly.Check your JCO's are up and running by pinging it in ContentAdmin->WebDynpro.
    2. its a simple problem of connection pooling. In your JCO connection settings change the maximum connections to 200. It will work.it  is good After you execute the Model please release the connection. The reason you are getting this JCO Client null is because the connection is not getting released.
    When you say the following code
    wdContext.current<BAPI_INPUT>.modelObject().execute();
    //Get the reference to the model and release the connection
    If your Model name is say "MO_Mymodel"  then
    MO_Mymodel model = (MO_Mymodel) WDModelFactory.getModelInstance(MO_Mymodel.class);
    model.disconnectIfAlive();
    This should release your connections. Also ensure you release the connections even if there is a exception :).
    Please refer the below forum also:
    Error connection using  JCO.Client :null
    JCO.Client: null
    com.sap.mw.jco.JCO$Exception: (102) JCO_ERROR_COMMUNICATION: JCO.Client not
    Thanks
    susmita

  • How to set  JCO.Table as input parameter

    RunTest.java
    Reservation reservation=new InvReservation();
              reservation.setRSNUM("0001");
              reservation.setMATNR("cellphone");
              reservation.setMENGE(1.0);
              reservation.setLGORT("MAINWH");
              reservation.setWERKS("HQ");
              reservation.setSERNR("AP");
              reservation.setVBELN("SD");
              try{
              Collection col=reservation.confirmReservation();
              for(Iterator it=col.iterator();it.hasNext();){
                   InvReservation invRes=(InvReservation)it.next();
                   System.out.println(invRes.getRSNUM()+"  "+invRes.getMBLNR()+"  "+invRes.getMATNR() +" "
                              +invRes.getMENGE()+" " +invRes.getSERNR()+"  " +invRes.getDMBTR() +"  "
                              +invRes.getZSUBRC()+"  "+invRes.getZEMSG());
              }catch(Exception ex){
                   System.out.println("main: " +ex );
    Reservation.java
    public Collection confirmReservation() throws CustomException{
              Reservation outgoingRes = new InvReservation();
              Collection col=new ArrayList();
                   JCO.Function function = null;
                   JCO.Client client = null;
                   String functionName = "ZMM_OSB_CONFIRM_RESERVATION";
                   try{
                        function = con.createFunction(functionName);
                        client = JCO.getClient(con.getConnectionPool());
                                            if (function != null) {
                             Table codes=function.getTableParameterList().getTable("ZOSB");
              int j=codes.getNumRows();  //it did not enter the for loop
                             for(int i=0;i<codes.getNumRows();i++){
                                  Reservation incomingRes1=new InvReservation();
                                  codes.setRow(i);
                                  incomingRes1.setRSNUM(codes.getString("RSNUM"));
                                  incomingRes1.setMATNR(codes.getString("MATNR"));
                                  incomingRes1.setMENGE(codes.getDouble("MENGE"));
                                  incomingRes1.setLGORT(codes.getString("LGORT"));
                                  incomingRes1.setWERKS(codes.getString("WERKS"));
                                  incomingRes1.setSERNR(codes.getString("SERNR"));
                                  incomingRes1.setVBELN(codes.getString("VBELN"));
                                  col.add(incomingRes1);
                                   System.out.println("RSNUM:" +codes.getString("RSNUM") + 't' +
                                        "MATNR:"+ codes.getString("MATNR") + 't' +
                                        "MENGE:" +codes.getDouble("MENGE") + 't' +
                                        "LGORT:" +codes.getString("LGORT") + 't' +
                                        "WERKS:" +codes.getString("WERKS") + 't' +
                                        "SERNR:" +codes.getString("SERNR") + 't' +
                                        "VBELN:" +codes.getString("VBELN"));
                              System.out.println("after set successful");
                              client.execute(function);     
                              int  count= function.getExportParameterList().getFieldCount();
                             JCO.Field ZSUBRCField=function.getExportParameterList().getField("ZSUBRC");
                             JCO.Field ZEMSGField=function.getExportParameterList().getField("ZEMSG");
                              for(int i=0; i<count; i++) {
                                if(ZSUBRCField.getName().equals("ZSUBRC")){
                                       outgoingRes.setZSUBRC(ZSUBRCField.getString()); 
                                  }else if(ZEMSGField.getName().equals("ZEMSG")){
                                       outgoingRes.setZEMSG(ZEMSGField.getString()); 
                             System.out.println(ZSUBRCField.getName() + ":t" + ZSUBRCField.getString());
                             System.out.println(ZEMSGField.getName() + ":t" + ZEMSGField.getString());
                              Table excodes = function.getTableParameterList().getTable("ZOSBMSEG");
                              for(int i=0;i<excodes.getNumRows();i++){
                                   Reservation outgoingRes1 = new InvReservation();
                                   excodes.setRow(i);
                                   outgoingRes1.setRSNUM(excodes.getString("RSNUM"));
                                   outgoingRes1.setMBLNR(excodes.getString("MBLNR"));
                                   outgoingRes1.setMATNR(excodes.getString("MATNR"));                              
                                   outgoingRes1.setMENGE(excodes.getDouble("MENGE"));
                                   outgoingRes1.setSERNR(excodes.getString("SERNR"));
                                   outgoingRes1.setDMBTR(excodes.getDouble("DMBTR"));
                                   outgoingRes1.setZSUBRC(ZSUBRCField.getString());
                                   outgoingRes1.setZEMSG(ZEMSGField.getString());
                                   col.add(outgoingRes1);
                                   System.out.println("RSNUM:" +excodes.getString("RSNUM") + 't' +
                                              "MBLNR:" +excodes.getString("MBLNR") + 't' +
                                        "MATNR:" +excodes.getString("MATNR") + 't' +
                                        "MENGE:" +excodes.getDouble("MENGE")+ 't' +
                                        "SERNR:" +excodes.getString("SERNR") + 't' +
                                        "MENGE:" +excodes.getDouble("DMBTR") + 't' +
                                        "ZSUBRC:" +ZSUBRCField.getString() + 't' +
                                        "ZEMSG:" +ZEMSGField.getString());
                             System.out.println("all ok");
                   }catch(Exception ex){
                        System.out.println("Caught an exception: n" + ex);
                        throw new CustomException(ex);
                   }finally{
                        if (client != null) {
                             System.out.println("Connection Closed");
                             JCO.releaseClient(client);
                   return col;
    everytime , when i debug, i found that it didnot enter the for loop and the j value always equals =0
    int j=codes.getNumRows();
    and always come up with this
    JCO_ERROR_RESOURCE: Trying to access row values in a table which does not have any rows yet
    Result:
    AFTER CREATEFUNCTION:Name:   ZMM_OSB_CONFIRM_RESERVATION
    Input: 
    null
    Output:
    | PARAMETERS 'OUTPUT'
    ZEMSG
    ZSUBRC
    01234567890123456789012345678901234567890123456789
    0   1
    as stated the input is null...i dunno why i cant set the input table parameter
    Message was edited by:
            yzme yzme
    Message was edited by:
            yzme yzme
    Message was edited by:
            yzme yzme

    new code
    public Collection confirmReservation() throws CustomException{
              // TODO Auto-generated method stub
              Reservation outgoingRes = new InvReservation();
              Collection col=new ArrayList();
                   JCO.Function function = null;
                   JCO.Client client = null;
                   String functionName = "ZMM__CONFIRM_RESERVATION";
                   try{
                        function = con.createFunction(functionName);
                        client = JCO.getClient(con.getConnectionPool());
                        System.out.println("AFTER CREATEFUNCTION:" + function );
                        if (function != null) {
                             JCO.ParameterList tabInput = function.getTableParameterList();
                             JCO.Table inputTable = tabInput.getTable("ZOSBIMSEG");
                             inputTable.appendRow();
                             System.out.println("checking table input:" +this.getRSNUM()+"  " +this.getMATNR()+ ""
                                                 +this.getMENGE()+" " +this.getLGORT()+" " +this.getWERKS() +" "
                                                 +this.getSERNR()+" " +this.getVBELN());
                                                      inputTable.setValue(this.getRSNUM(),"RSNUM");
                             inputTable.setValue(this.getMATNR(),"MATNR");
                             inputTable.setValue(this.getMENGE(),"MENGE");
                             inputTable.setValue(this.getLGORT(),"LGORT");
                             inputTable.setValue(this.getWERKS(),"WERKS");
                             inputTable.setValue(this.getSERNR(),"SERNR");
                             inputTable.setValue(this.getVBELN(),"VBELN");
                                                       System.out.println("after set successful");
                              client.execute(function);     
                              int  count= function.getExportParameterList().getFieldCount();
                             JCO.Field ZSUBRCField=function.getExportParameterList().getField("ZSUBRC");
                             JCO.Field ZEMSGField=function.getExportParameterList().getField("ZEMSG");
                              for(int i=0; i<count; i++) {
                                if(ZSUBRCField.getName().equals("ZSUBRC")){
                                       outgoingRes.setZSUBRC(ZSUBRCField.getString()); 
                                  }else if(ZEMSGField.getName().equals("ZEMSG")){
                                       outgoingRes.setZEMSG(ZEMSGField.getString()); 
                             System.out.println(ZSUBRCField.getName() + ":t" + ZSUBRCField.getString());
                             System.out.println(ZEMSGField.getName() + ":t" + ZEMSGField.getString());
                              Table excodes = function.getTableParameterList().getTable("ZOSBMSEG");
                              for(int i=0;i<excodes.getNumRows();i++){
                                   Reservation outgoingRes1 = new InvReservation();
                                   excodes.setRow(i);
                                   //add here
                                   outgoingRes1.setRSNUM(excodes.getString("RSNUM"));
                                   outgoingRes1.setMBLNR(excodes.getString("MBLNR"));
                                   outgoingRes1.setMATNR(excodes.getString("MATNR"));                              
                                   outgoingRes1.setMENGE(excodes.getDouble("MENGE"));
                                   outgoingRes1.setSERNR(excodes.getString("SERNR"));
                                   outgoingRes1.setDMBTR(excodes.getDouble("DMBTR"));
                                   outgoingRes1.setZSUBRC(ZSUBRCField.getString());
                                   outgoingRes1.setZEMSG(ZEMSGField.getString());
                                   //outgoingRes.setMENGE(java.lang.Double.parseDouble(codes.getString()));
                                   col.add(outgoingRes1);
                                   System.out.println("RSNUM:" +excodes.getString("RSNUM") + 't' +
                                              "MBLNR:" +excodes.getString("MBLNR") + 't' +
                                        "MATNR:" +excodes.getString("MATNR") + 't' +
                                        "MENGE:" +excodes.getDouble("MENGE")+ 't' +
                                        "SERNR:" +excodes.getString("SERNR") + 't' +
                                        "MENGE:" +excodes.getDouble("DMBTR") + 't' +
                                        "ZSUBRC:" +ZSUBRCField.getString() + 't' +
                                        "ZEMSG:" +ZEMSGField.getString());
                             System.out.println("all ok");
                   }catch(Exception ex){
                        System.out.println("Caught an exception: n" + ex);
                        throw new CustomException(ex);
                   }finally{
                        if (client != null) {
                             System.out.println("Connection Closed");
                             JCO.releaseClient(client);
                   return col;
    Just to let's you know something here...
    the input parameter is a table structure...so when i execute this.
    Caught an exception:
    java.lang.NullPointerException
    JCO.ParameterList list = function.getImportParameterList();
                              list.setValue(this.getRSNUM(),"RSNUM");
                              list.setValue(this.getMATNR(),"MATNR");
                              list.setValue(this.getMENGE(),"MENGE");
                              list.setValue(this.getLGORT(),"LGORT");
                              list.setValue(this.getWERKS(),"WERKS");
                              list.setValue(this.getSERNR(),"SERNR");
                              list.setValue(this.getVBELN(),"VBELN");
    so i changed to ....
    it get what i want....
    but again the result of the input is still null
         JCO.ParameterList tabInput = function.getTableParameterList();
                             JCO.Table inputTable = tabInput.getTable("ZOSBIMSEG");
                             inputTable.appendRow();
                             System.out.println("checking table input:" +this.getRSNUM()+"  " +this.getMATNR()+ ""
                                                 +this.getMENGE()+" " +this.getLGORT()+" " +this.getWERKS() +" "
                                                 +this.getSERNR()+" " +this.getVBELN());
                                                      inputTable.setValue(this.getRSNUM(),"RSNUM");
                             inputTable.setValue(this.getMATNR(),"MATNR");
                             inputTable.setValue(this.getMENGE(),"MENGE");
                             inputTable.setValue(this.getLGORT(),"LGORT");
                             inputTable.setValue(this.getWERKS(),"WERKS");
                             inputTable.setValue(this.getSERNR(),"SERNR");
                             inputTable.setValue(this.getVBELN(),"VBELN");
    AFTER CREATEFUNCTION:Name:   ZMM_OSB_CONFIRM_RESERVATION
    Input: 
    null
    Output:
    | PARAMETERS 'OUTPUT'
    | ZEMSG                                            | ZSUBRC |
    |01234567890123456789012345678901234567890123456789|   0   1|
    |                                                  |00000000|

  • Dynamic JCO Client

    Hi,
    there is a way to create a dynamic JCO.Client?
    I have this code:
    JCO.Client jcoclient =   JCO.createClient(
                         "data",
                        "data",
                         "password",
                         "it",
                        "10.140.5.122",
                        "12");
              jcoclient.connect();
    I want to get dynamically from the system the parameters for method "createClient". It's possible??There is a way??
    THANS

    >
    Andrea Ruocco wrote:
    > Hi,
    > there is a way to create a dynamic JCO.Client?
    > I have this code:
    >
    >
    > I want to get dynamically from the system the parameters for method "createClient". It's possible??There is a way??
    > THANS
    To avoid hard coding the JCO connection details, take a look at the [Destination Service API|http://help.sap.com/saphelp_nw04/helpdata/en/8b/8e7dac1e661d44bf2a676fd3948cc6/frameset.htm].
    Here is a [blog|https://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/10300] on how to use the SAP Enterprise Connector (which is used to call JCOs) with the Destination Service API. Once the Destination service is set up, you can then create your JCO.client as follows
    final InitialContext ctx = new InitialContext();
    final DestinationService dstService = (DestinationService)ctx.lookup(DestinationService.JNDI_KEY);
    if (dstService == null)
      throw new NamingException("Destination Service not available");
    RFCDestination dst;
    // get the ERPR3 destination created in visual administrator
    dst = (RFCDestination) dstService.getDestination("RFC", "ERPR3");
    Properties jcoProperties = dst.getJCoProperties(); 
    //Establish a direct connection
    JCO.Client client = JCO.createClient(jcoProperties);
    client.connect();

  • Abap Rfc External Debug from a Jco Client Connection

    Hi to all,
    i have developed a Java Application on Sap J2ee (SAP-JEE 7.01 SP6) , using the Jco2 integrated.
    I'm using direct connection , calling Custom Functions Module on  Abap Stack.
    I have a question about Abap Debugging:
    now i debug the abap function setting an external session breakpoint (SE37) and  the abap debug stops  correctly on breakpoint that i've set.
    But sometimes i notice the strange situation that during my debug another debug session (identical to the first) is open on my sap gui (it seems that Jco sends another request while i'm debugging the first )
    Reading the jco documentation i've seen this method that i never used: JCO.Client setAbapDebug(boolean debug)
            Enables/disables abap debug.
    Note:If the connection is already established the method will close and reopen the connection.
    have I  to set this in my java code in addition to abap external breakpoint? Why Jco.Client sends another request?
    Thanks for the answers
    Alessandro

    Anyone know?
    Thanks,
    Augusto Póvoa.

  • What happens if JCO.Client object not disconnected?

    Hi All,
    Can anyone tell me what happens if a JCO.Client( which is connected to SAP) is not disconnected? Will it be connected? or JCO disconnects it after sometime? or SAP itself disconnects it?
      JCO.Client client = JCO.createClient(....);
      client.connect();
    If I run this simple code and leave it, what will happen to the connection opened?
    Thanks in advance.

    We are using JCO with SAP J2EE and have found something strange.  We are setting the idle_timeout property and the SAP user is logging off, however we accumulate DISCONNECTED sessions in the SAP gateway.  If the gateway limit is reached, additional connections fail.  We used a modified version of the sample program to isolate the problem.
    Test Program:
    import java.io.IOException;
    import com.sap.mw.jco.*;
    public class Test {
        public static void main(String args[]) {
            byte instring[] = new byte[20];
            JCO.Client jcoClient = JCO.createClient("200", "user", "password", "EN",
                    "bhha.na.pg.com", "00");
            jcoClient.setProperty("idle_timeout","60");    
            jcoClient.connect();
            System.out.print("Read:");
            System.out.flush();
            try {
                System.in.read(instring);
            } catch (IOException e) {
                e.printStackTrace();
    During 60 second period, transaction smgw shows the following information as expected.  There is also a logged in user in SM04.
       44  7BWGF21  javaw    t0331        CONNECTED    <unknown 99703871 INT  15:13:10 0    0
    After 60 seconds, the user disappears from SM04, however the smgw connection goes to a disconnect state as follows.
       44  7BWGF21  javaw    t0331        DISCONNECT   <unknown 99703871 INT  15:14:44 0    0
    This session stays in this state until the enter key is pressed and the java app terminates.  This is problem with a J2EE server app were the java process does not terminate.
    Thanks,
    Harry

  • Security Issue while running client object code

    Hi Team,
    I have client object code to create SharePoint list items and i am using the below codes,
     ClientContext clientContext = new ClientContext("MyCompanySiteName");
     List olist = clientContext.Web.Lists.GetByTitle("Employee");
     ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
      for (int i = 13; i <= 25; i++)
                        ListItem oListItem = olist.AddItem(itemCreateInfo);
                        oListItem["Title"] = "TEST" + i.ToString();
                        oListItem.Update();
                        clientContext.ExecuteQuery();
    Here my question is , i have list with 4 mandatory fields and i have run this code against the same list.
    Where i can able to create list items without filling mandatory fileds using this above code.
    How we are creating list items , without entering/filling Mandtory fields in SharePoint list.
    Is this security issue or bug in SharePoint client object code.
    Thanks
    S.Jeeva
    Jeeva

    Hi!
    I agree with sadomovalex.
    This is by design and it is not security issue, it is rather consistency issue. It should be resolved via checking for required values before use or via implementing event receivers that throw errors if the required values are not set.
    If my suggestion helped you to solve your problem, please don't forget to mark it as Answer

  • Clearing Payment to a G/L account set up in Reason Code

    I am having a problem posting an overpayment/underpayment to a G/L account using a reason code. What I am attempting to do is, using F-28, have the remainder of an underpayment post to a G/L account attached to the reason codes. What I need to have work is that in F-28 I do not want to have to enter any data on what the residual amount is, it should just take whatever is not paid and apply it to the G/L account tied to the reason code.  I have set 3 new reason codes in OBBE to test different possibilities with the checkboxes in that transaction, and have attached each of the reason codes to accounts using OBXL. What is happening now is that when I enter a short pay amount for an invoice and I enter a reason code in the RCd field in the residual tab - I hit save and it seems to try to attach the remaining amount to an account that is currently tied to a blank reason code in our setup in OBXL. I would think that since I am placing a code in the RCD field, that it would use the account tied to that. I have also tried to use the reason code field below, but encounter the same results or, with one of my codes that has the "charge off difference via separate account" checkbox checked, it will not allow that code in that field below.
    There must be a way to take the shortpay amoun,t and without entering the residual amount anywhere, use the G/L account tied to the reason code to post the remainder to. Can anybody help on what I may need to do to get this to work?
    Thanks -
    PS. This is not a tolerance issue as I have set the tolerances for both the customer and the user high enough to allow under/overpayments.

    No... this is SAP standard.... if you are treating them as residual payment and the GL is seperate than the small diff GL we have to enter the amount there..... as system cannot understand whats the differnece when we dont put the amount there......
    we can always see the field NOT ASSIGNED in the bootom.. it is just the matter of copy paste for the user.... it has to come thro user discipline.... i dont see a standard sap way of doing it,....

  • Currency setting in multiple company code.

    Dear all,
    we are having 3 company codes in one client.
    and we have to set the Currency setting for multiple company codes.
    Tcodes
    S_BCE_68000174 - Enter Translation Rates
    S_ALR_87003642 - Open and Close Posting Periods
    it is not allowing us to set the values at a same time for different company codes by different users
    it says " DATA LOCKED BY OTHER USER, ONLY DISPLAY MODE."
    Pls assist
    Thanks

    Ask for access to delete lock entries. If access is provided, use T code sm12 to delete the lock entries.
    @ Irfan you cannot do that. Only one user can use a table at a time.
    It is like using an ATM. Only one person can withdraw money at a time.
    Edited by: Dummy_Variable on Jul 27, 2011 9:34 AM

  • Supplying username and password to repository via code

    Hi There,
    Is there a way to supply the username and password to the webdav repository via code or in the address line? We have an ActiveX object accessing files and would like to avoid the repository prompting.
    Thanks

    With Script I can do it as follows.. See VerifyConnection
    Option Explicit
    Const iTimeOutInSecs = 60
    Const ForWriting = 2
    Rem ************** MAIN *****************
    main
    Wscript.quit
    Sub Main
      Dim WShell, FileSystem
      Dim davControl
      Dim objArgs, targetPath, serverURL, username, password, rootFolder, filter
      Dim fileUploadList, result
      Dim folderList, filelist
      Dim status
      Dim spoolFile
      Set wShell     = WScript.CreateObject("WScript.Shell")
      Set fileSystem = WScript.CreateObject("Scripting.FileSystemObject")
      Set spoolFile = fileSystem.OpenTextFile("httpUploadLoad.log", ForWriting, True)
      Set objArgs = WScript.Arguments
      targetPath  = objArgs(0)
      serverUrl   = objArgs(1)
      username    = objArgs(2)
      password    = objArgs(3)
      rootFolder  = objArgs(4)
      If objArgs.length = 6 Then
        filter    = objArgs(5)
      Else
        filter = Empty
      End If
      Set fileUploadList = CreateObject("Msxml2.DOMDocument.4.0")
      fileUploadList.async = False
      result = fileUploadList.load(targetPath)
      If (result = False) Then
        MsgBox "Failure while loading or parsing file : " & targetPath,vbCritical
        Wscript.quit
      End If
      Set davControl = new DavControlClass
      davControl.setServer serverURL, username, password
      davControl.setSpoofile(spoolfile)
      status = verifyHttpConnection(davControl, username)
      Set folderList =  fileUploadList.documentElement.selectNodes("/Upload/directories/directory")
      createFolders davControl, rootFolder, folderList, username, password, filter
      Set fileList =  fileUploadList.documentElement.selectNodes("/Upload/files/file")
      uploadFiles davControl, rootFolder, fileList, username, password, filter
      spoolfile.close()
    End Sub
    Function verifyHttpConnection(davControl,username)
      Dim status, targetFolder
      targetFolder = "/home/" & username
      status = davControl.verifyConnection(targetFolder)
      verifyHttpConnection = status
    End Function
    Sub createFolders(davControl, rootFolder, folderList, username, password, filter)
      Dim i, targetFolder, targetFolderPath
      For i = 0 to folderList.length - 1
        Set targetFolder = folderList.item(i)
        targetFolderPath = rootFolder & targetFolder.text
        If IsNull(filter) or (InStr(targetFolder.text,filter) = 1) Then
          'wscript.echo "Making " & targetFolderPath
          davControl.makeDir targetFolderPath,true
        End If
      Next
    End Sub
    Sub uploadFiles(davControl, rootFolder, fileList, username, password, filter)
      Dim i, targetFile, targetFilename, localFilename
      For i = 0 to fileList.length - 1
        Set targetFile = fileList.item(i)
        targetFilename = rootFolder & targetFile.text
        localFilename = Right(replace(targetFile.text,"/","\"),Len(targetFile.text)-1)
        If IsNull(filter) or (InStr(targetFile.text,filter) = 1) Then
          'wscript.echo "Uploading " &localFilename & " as " & targetFilename
          davControl.uploadFile localFIlename, targetFileName, "FORCE"
        End If
      Next
    End Sub
    Class DavControlClass
      Private HTTPUser
      Private HTTPPassword
      Private HTTPServer
      Private installParameters
      Private windowsShell
      Private XMLHTTP_CLASS_ID
      Private HttpObject
      Private spoolFile
      Dim     folderStatusList
      Private Sub Class_Initialize()
        XMLHTTP_CLASS_ID = "Msxml2.XMLHTTP.6.0"
        Set HttpObject = CreateObject(XMLHTTP_CLASS_ID)
        folderStatusList = Empty
      End Sub  
      Public Sub setSpoofile(file)
        Set spoolFile = file
      End Sub
      Public Sub setParameters(wshell, params)
        Set installParameters = params
        Set windowsShell = wShell
        setServer params.getServerURL(), params.getUser(), params.getPassword()
      End Sub
      Public Sub setServer(serverURL,serverUser,serverPassword)
        HTTPServer   = serverURL
        HTTPUser     = serverUser
        HTTPPassword = serverPassword
      End Sub
      Public Function getServerURL
        getServerURL= HTTPServer
      End Function       
      Public Function verifyConnection(target)
        On Error Resume Next
        HttpObject.Open "HEAD", HTTPServer & target, false, HTTPUser, HTTPPassword
        If Err.Number <> 0 Then
          WScript.echo "verifyConnection() - Fatal Error encountered accessing : " & HTTPServer & target & ". Status (" & Hex(Err.number)  & ") " & Err.Description
          Wscript.quit         
        End If
        On Error GoTo 0 
        HttpObject.setRequestHeader "Content-type", "text/xml"
        HttpObject.setRequestHeader "Depth", "1"
        On Error Resume Next
        HttpObject.send ("")
        If Err.Number <> 0 Then
          WScript.echo "resetConnection() - Fatal Error encountered accessing : " & HTTPServer & target & ". Status (" & Hex(Err.number)  & ") " & Err.Description
          Wscript.quit         
        End If
        On Error GoTo 0 
        If HTTPObject.status <> 200 Then
          MsgBox "Unable to access " & getServerURL() & target & ". HTTP Status = " & HTTPObject.status & ". Please correct installParameters.xml and restart Installation",vbCritical
          Wscript.quit
        End If
        spoolfile.writeline "HTTP Successfully Connected to '" & getServerURL() & target
        verifyConnection = HTTPObject.status
      End Function
      Public Function uploadFile (local, remote, mode)
        Dim returnCode, rc
        returnCode = doHead(remote)
        If returnCode = 401 Then
          MsgBox "uploadFile() - Unauthorized (Status (" & returnCode & "). Unable to upload '" & local & "' into '" & remote & "'.  Please check installParameters.xml and log files.",vbCritical
          Wscript.quit         
        End If
        If returnCode = 200 Then
          If mode = "ERROR" Then
            MsgBox "uploadFile() - Installation Failed. Resource Exists : '" & remote & "'. Please check installParameters.xml and restart Installation",vbCritical
            Wscript.quit
          End If
          If mode = "SKIP" Then
            uploadFile = returnCode
            Exit Function
          End If
          If mode = "FORCE" Then
            rc = doDelete(remote)
          End If
        End If
        uploadFile = doPut (local, remote, null)
        If uploadFile = 500 Then
          MsgBox "UploadFile() - Upload Failed (Status (" & uploadFile & "). Unable to upload '" & local & "' into '" & remote & "'.  Retry in Progress.",vbCritical
          uploadFile = doPut (local, remote, null, user, password)
          If uploadFile = 500 Then
            MsgBox "UploadFile() -  Installation Failed (Status (" & uploadFile & "). Unable to upload '" & local & "' into '" & remote & "'.  Please check installParameters.xml and log files.",vbCritical
            Wscript.quit         
          End If
        End If
        If uploadFile = 401 Then
          MsgBox "UploadFile() - Unauthorized (Status (" & uploadFile & "). Unable to upload '" & local & "' into '" & remote & "'.  Please check installParameters.xml and log files.",vbCritical
          Wscript.quit         
        End If
      End Function
      Public Function makeDir(targetFolder,force)
        Dim Status, ParentFolder
        status = doHEAD(targetFolder)
        If not IsEmpty(folderStatusList) Then
          folderStatusList.add targetFolder, status
        End If
        If (status = 404 or status = 409) and force Then
          parentFolder = Mid(targetFolder,1,InStrRev(targetFolder,"/")-1)
          makeDir parentFolder,true
          status = doMKCOL(targetFolder)
        End If
        makeDir = status   
        If status = 401 Then
          MsgBox "doMKCOL() - Unauthorized (Status (" & status & "). Unable to create '" & targetFolder & "'.  Please check installParameters.xml and log files.",vbCritical
          Wscript.quit         
        End If
      End Function
      Public Function doHEAD(remote)
        ' Dim HttpObject
        ' Set HttpObject = CreateObject(XMLHTTP_CLASS_ID)
        ' HttpObject.Open "HEAD", HTTPServer & remote, false, user, password
        HttpObject.Open "HEAD", HTTPServer & remote, false
        HttpObject.setRequestHeader "Content-type", "text/xml"
        HttpObject.setRequestHeader "Depth", "1"
        On Error Resume Next
        HttpObject.send ("")
        If Err.Number <> 0 Then
          WScript.echo "doHEAD() - Fatal Error encountered accessing : " & HTTPServer & remote & ". Status (" & Hex(Err.number)  & ") " & Err.Description
          Wscript.quit         
        End If
        On Error GoTo 0 
        doHead = HttpObject.status
      End Function
      Public Function doPUT(local,remote,contentType)
        Dim tmStart
        Dim tmCurr
        Dim iTimeTaken
        Dim currentStatus
        Dim ado_stream
        Dim uploadCount, uploadStatus
        Set ado_stream = CreateObject("ADODB.Stream")
        ado_stream.Type = 1
        ado_stream.Open()
        On Error Resume Next
        ado_stream.LoadFromFile(local)
        If Err.Number <> 0 Then
          WScript.echo "doPUT() - Fatal Error encountered reading File : " & local & ". Status (" & Hex(Err.number)  & ") " & Err.Description
          Wscript.quit         
        End If
        On Error GoTo 0 
        HttpObject.Open "PUT", HTTPServer & remote, false
        If not IsNull(contentType) Then
          HttpObject.setRequestHeader "Content-type", contentType
        End If
        tmStart = Now
        On Error Resume Next
        HTTPObject.send(ado_stream.Read(-1))
        If Err.number <> 0 Then
          '  Unexpected errors can occur as a result of the HTTP request being passed to wrong database instance
          '  when multiple databases are using the same listener.
          WScript.echo "doPUT() - Fatal Error encountered uploading File : " & local & ". Status (" & Hex(Err.number)  & ") " & Err.Description
          WScript.quit
       Else
          currentStatus = HTTPObject.status
        End If
        On Error GoTo 0 
        uploadCount = 1
        uploadStatus = doHead(remote)
        Do While uploadStatus <> 200 and uploadCount < 6
          '  Unexpected errors can occur as a result of the HTTP request being passed to wrong database instance
          '  when multiple databases are using the same listener.
          spoolfile.writeline "Http Error encountered uploading " & local & " to " & HTTPServer & remote &". Status=" & currentStatus
          currentStatus = retryPUT(local,remote,contentType)
          uploadCount = uploadCount + 1
          uploadStatus = doHead(remote)
        Loop
        If uploadStatus = 200 Then
          tmCurr = Now
          spoolFile.writeLine "Uploaded File " & local & ". Elapsed Time = " & CInt(DateDiff("s", tmStart, tmCurr)) & " seconds."
        Else
          WScript.echo "doPUT - Fatal Error uploading file (" & HTTPServer & remote & ") : Status=" & HTTPObject.status
          WScript.quit
        End If
        doPut = currentStatus
        ado_stream.Close()
      End Function
      Public Function retryPUT(local,remote,contentType)
        Dim ado_stream
        Set ado_stream = CreateObject("ADODB.Stream")
        ado_stream.Type = 1
        ado_stream.Open()
        On Error Resume Next
        ado_stream.LoadFromFile(local)
        If Err.number <> 0 Then
          WScript.echo "doPUT() - Fatal Error encountered reading File : " & local & ". Status (" & Hex(Err.number)  & ") " & Err.Description
          Wscript.quit         
        End If
        On Error GoTo 0 
        HttpObject.Open "PUT", HTTPServer & remote, true
        If not IsNull(contentType) Then
          HttpObject.setRequestHeader "Content-type", contentType
        End If
        On Error Resume Next
        HTTPObject.send(ado_stream.Read(-1))
        If Err.Number <> 0 Then
          ado_stream.Close()
          WScript.echo "doPUT() - Fatal Error encountered sending File : " & local & " to " & HTTPServer & remote &". Status (" & Hex(Err.number)  & ") " & Err.Description & ". Retrying ...."
          Wscript.quit         
        Else   
          Do While HTTPObject.readyState <> 4
            WScript.Sleep(1000)
          Loop
        End If
        On Error GoTo 0 
        ado_stream.Close()
        retryPut =  HTTPObject.status         
      End Function
      Public Function doMKCOL(remote)
        ' wscript.echo "doMKCOL (" & HTTPServer & remote & ")"
        Dim currentStatus
        HttpObject.Open "MKCOL", HTTPServer & remote, false
        HttpObject.setRequestHeader "Content-type", "text/xml"
        On Error Resume Next
        HttpObject.send("")
        If Err.Number <> 0 Then
          WScript.echo "doMKCOL() - Fatal Error encountered making Folder : " & HTTPServer & remote &". Status (" & Hex(Err.number)  & ") " & Err.Description
          Wscript.quit         
        End If
        On Error GoTo 0 
        If  HTTPObject.status <> 201 Then
          WScript.echo "doMKCOL() - Fatal Error encountered making Folder : " & HTTPServer & remote &". Status (" & HTTPObject.status & ")."
          Wscript.quit         
        End If
        doMKCOL = HTTPObject.status
      End Function
      Public Function doDELETE(remote)
        HttpObject.Open "DELETE", HTTPServer & remote, false
        HttpObject.setRequestHeader "Content-type", "text/xml"
        On Error Resume Next
        HttpObject.send("")
        If Err.Number <> 0 Then
          WScript.echo "doMKCOL() - Fatal Error deleting : " & HTTPServer & remote &". Status (" & Hex(Err.number)  & ") " & Err.Description
          Wscript.quit         
        End If
        On Error GoTo 0 
        doDELETE = HTTPObject.status
        If HTTPObject.status <> 201  and HTTPObject.status <> 204 and HTTPObject.status <> 207 and HTTPObject.status <> 404 Then
          wscript.echo "doDELETE (" & HTTPServer & remote & ") : Status=" & HTTPObject.status
        End If
      End Function
    End Class

  • Setting Fields value via reflection

    I'm starting from a c# code:
              internal void RefreshFromObject(object objFromUpdate)
                   if (this.GetType()==objFromUpdate.GetType())
                        PropertyInfo[] fieldsFrom = objFromUpdate.GetType().GetProperties();
                        PropertyInfo[] fieldsThis = this.GetType().GetProperties();
                        for(int idxProp=0; idxProp<fieldsFrom.Length;idxProp++)
                             if (fieldsThis[idxProp].CanWrite && fieldsFrom[idxProp].CanRead)
                                  fieldsThis[idxProp].SetValue(this, fieldsFrom[idxProp].GetValue(objFromUpdate,null),null);
                   else
                        throw new ObjectTypeNotValidException("Object type from which update current instance not valid. Use same type.");
    Now I have to translate it in Java:
    Class clazz = objFromUpdate.getClass();
    Class thisClazz = this.getClass();
    do {
         Field[] fieldsFrom = clazz.getDeclaredFields();
         Field[] fieldsThis = thisClazz.getDeclaredFields();
         try {
              fieldsThis[idxProp].set(thisClazz, fieldsFrom[idxProp].get(clazz));
         catch (IllegalAccessException iaccEx) {
              System.out.println("IllegalAccessException");
         catch (IllegalArgumentException iaccEx) {
              System.out.println("IllegalArgumentException");
    clazz = clazz.getSuperclass();
    thisClazz = thisClazz.getSuperclass();
    } while (clazz != null && clazz != Object.class);
    My problem is that I don't know if the field type is one of primitive, for which I should use the particular setters and getters.
    My questions are:
    1) is there in Java a more elegant way to set fields values via reflection?
    2) how can I know if a field i changable (equivalent to the method CanWrite of c#?
    Thanks a lot to each one that will answer me.
    Marco

    Hi georgemc,
    thanks for replying. I-m new with java forum, so I don't know if it is correct the code tags...
    Anyway... the problem is that the Field of reflected object could be both of Object types or primitive types. So I cannot use the general method "set" when changing Field's value.
    Maybe somebody else had the same problem...
    Seems in C# it is a very easy thing... not in java :(
    Marco
    Class clazz = objFromUpdate.getClass();
    Class thisClazz = this.getClass();
    do {
    Field[] fieldsFrom = clazz.getDeclaredFields();
    Field[] fieldsThis = thisClazz.getDeclaredFields();
    try {
    fieldsThis[idxProp].set(thisClazz, fieldsFrom[idxProp].get(clazz));
    catch (IllegalAccessException iaccEx) {
    System.out.println("IllegalAccessException");
    catch (IllegalArgumentException iaccEx) {
    System.out.println("IllegalArgumentException");
    clazz = clazz.getSuperclass();
    thisClazz = thisClazz.getSuperclass();
    } while (clazz != null && clazz != Object.class);

Maybe you are looking for

  • Balance Sheet translation at spot rate at ANY point in time

    My client produces its financial accounts in AUD.  They will have open items in AR, AP and Bank in foreign currencies.  WITHOUT running periodic valuation they wish to produce a Balance Sheet at any point in time during the month applying the applica

  • In Credit Memo Net Value is coming 0.

    Dear SD Expert, I have created Credit Memo with Reference Credit memo request. While creating Credit memo (VF01) the Net Value is 0. But the Billed quantity is coming correct in the system. In Credit Memo request(VA01) every thing is ok, Quantity and

  • IPod touch 4g not syncing

    When I try to sync my ipod touch 4g I get the message "Internal device error" or "ipod cannot be synced". The next time the ipod is plugged in, itunes only gives me the option to restore it or set it up as a new ipod. Restoring it never works and set

  • I recently purchased U2 Any DVD Ripper on Mac App Store and can not get it to work!  Help!!

    I can not find any documentation on how to use this software.  I can not figure out how to get it to copy a DVD to Mp4 format on my media hard drive, allowing me to watch the video on my apple tv.  Please help or direct me to get a refund for this $1

  • Invoice output  at header level

    hi friends, here i have one problem i.e my clint want to have purchaze order number in the invoice print out if the invoice print out is taking at header level asume that there are two items in the invoice those two items are from diffrent delivery d