/**
   * ABAP APIs often uses complex parameters. This example demonstrates how to read the values from
   * a structure.
   *
   * @throws com.sap.conn.jco.JCoException
   */
  public static void step3WorkWithStructure() throws JCoException {
    JCoDestination destination = JCoDestinationManager.getDestination(ABAP_AS_POOLED);
    JCoFunction function = destination.getRepository().getFunction("RFC_SYSTEM_INFO");
    if (function == null) throw new RuntimeException("RFC_SYSTEM_INFO not found in SAP.");

    try {
      function.execute(destination);
    } catch (AbapException e) {
      System.out.println(e.toString());
      return;
    }

    JCoStructure exportStructure = function.getExportParameterList().getStructure("RFCSI_EXPORT");
    System.out.println("System info for " + destination.getAttributes().getSystemID() + ":\n");

    // The structure contains some fields. The loop just prints out each field with its name.
    for (int i = 0; i < exportStructure.getMetaData().getFieldCount(); i++) {
      System.out.println(
          exportStructure.getMetaData().getName(i) + ":\t" + exportStructure.getString(i));
    }
    System.out.println();

    // JCo still supports the JCoFields, but direct access via getXXX is more efficient as field
    // iterator
    System.out.println(
        "The same using field iterator: \nSystem info for "
            + destination.getAttributes().getSystemID()
            + ":\n");
    for (JCoField field : exportStructure) {
      System.out.println(field.getName() + ":\t" + field.getString());
    }
    System.out.println();
  }
 @Override
 public void run(
     VariantTableContent content,
     Resource resource,
     IProgressMonitor monitor,
     Map<String, VCObject> seenObjects,
     List<Option> options)
     throws Exception {
   VariantTable table = content.getTable();
   JCoFunction deletefunc = maintainEntries(content, monitor, options, true);
   executeTransaction(monitor, "DELETE " + table.getName(), deletefunc);
   JCoFunction createfunc = maintainEntries(content, monitor, options, false);
   JCoTable entries = createfunc.getTableParameterList().getTable("VAR_TAB_ENTRIES");
   EList<Row> rows = content.getRows();
   List<VariantTableArgument> arguments = table.getArguments();
   for (Row row : rows) {
     for (VariantTableArgument arg : arguments) {
       String cstic = arg.getCharacteristic().getName();
       int index = arguments.indexOf(arg);
       entries.appendRow();
       Literal literal = row.getValues().get(index);
       entries.setValue("VTCHARACT", cstic);
       entries.setValue("VTLINENO", "" + rows.indexOf(row));
       entries.setValue("VTVALUE", getValue(literal));
     }
   }
   executeTransaction(monitor, "CREATE/CHANGE " + table.getName(), createfunc);
 }
  /**
   * The following example executes a simple RFC function STFC_CONNECTION. In contrast to JCo 2 you
   * do not need to take care of repository management. JCo 3 manages the repository caches
   * internally and shares the available function metadata as much as possible.
   *
   * @throws com.sap.conn.jco.JCoException
   */
  public static void step3SimpleCall() throws JCoException {
    // JCoDestination is the logic address of an ABAP system and ...
    JCoDestination destination = JCoDestinationManager.getDestination(ABAP_AS_POOLED);
    // ... it always has a reference to a metadata repository
    JCoFunction function = destination.getRepository().getFunction("STFC_CONNECTION");
    if (function == null) throw new RuntimeException("BAPI_COMPANYCODE_GETLIST not found in SAP.");

    // JCoFunction is container for function values. Each function contains separate
    // containers for import, export, changing and table parameters.
    // To set or get the parameters use the APIS setValue() and getXXX().
    function.getImportParameterList().setValue("REQUTEXT", "Hello SAP");

    try {
      // execute, i.e. send the function to the ABAP system addressed
      // by the specified destination, which then returns the function result.
      // All necessary conversions between Java and ABAP data types
      // are done automatically.
      function.execute(destination);
    } catch (AbapException e) {
      System.out.println(e.toString());
      return;
    }

    System.out.println("STFC_CONNECTION finished:");
    System.out.println(" Echo: " + function.getExportParameterList().getString("ECHOTEXT"));
    System.out.println(" Response: " + function.getExportParameterList().getString("RESPTEXT"));
    System.out.println();
  }
示例#4
0
 /**
  * Executes RFC_READ_TABLE with the current set of selected fields but without selection criteria.
  *
  * @return the contents read
  * @throws JCoException
  */
 public ITableContents read() throws JCoException {
   JCoFunction readFunction = template.getFunction();
   readFunction.getImportParameterList().setValue("QUERY_TABLE", tableName); // $NON-NLS-1$
   readFunction.getTableParameterList().getTable("OPTIONS").clear(); // $NON-NLS-1$
   setFieldList(readFunction);
   readFunction.execute(destination);
   return new TableContents(
       tableName,
       readFunction.getTableParameterList().getTable("FIELDS"), // $NON-NLS-1$
       readFunction.getTableParameterList().getTable("DATA")); // $NON-NLS-1$
 }
示例#5
0
 /**
  * Retrieves the table structure from the SAP R/3 system.
  *
  * @throws JCoException
  */
 private void loadStructure() throws JCoException {
   // call RFC_READ_TABLE without requesting any data
   JCoFunction readFieldListFunction = template.getFunction();
   readFieldListFunction
       .getImportParameterList()
       .setValue("QUERY_TABLE", tableName); // $NON-NLS-1$
   readFieldListFunction.getImportParameterList().setValue("NO_DATA", tableName); // $NON-NLS-1$
   readFieldListFunction.execute(destination);
   structure =
       new TableStructure(
           tableName,
           readFieldListFunction.getTableParameterList().getTable("FIELDS")); // $NON-NLS-1$
 }
示例#6
0
 /**
  * Adjusts the field list so that only the selected fields are read.
  *
  * @param readFunction
  */
 private void setFieldList(JCoFunction readFunction) {
   int length = 0;
   JCoTable fields = readFunction.getTableParameterList().getTable("FIELDS"); // $NON-NLS-1$
   fields.clear();
   if (selectedFields.isEmpty()) {
     for (final ITableField field : structure.getFieldList()) {
       length += field.getLength();
       fields.appendRow();
       fields.setValue("FIELDNAME", field.getFieldName()); // $NON-NLS-1$
     }
   } else {
     for (final String field : selectedFields) {
       try {
         length += structure.getField(field).getLength();
         fields.appendRow();
         fields.setValue("FIELDNAME", field); // $NON-NLS-1$
       } catch (FieldNotFoundException e) {
         throw new IllegalArgumentException(
             MessageFormat.format(Messages.TableReader_UnknownField, field), e);
       }
     }
   }
   if (length > 512) {
     throw new IllegalArgumentException(Messages.TableReader_ResultTooLong);
   }
 }
  public void run(
      Class object,
      Resource resource,
      IProgressMonitor monitor,
      Map<String, VCObject> seenObjects,
      List<Option> options)
      throws JCoException {
    beginTransaction();
    JCoFunction function = getJCoFunction(getBAPI(), monitor);
    JCoParameterList ipl = function.getImportParameterList();
    String classSpec = object.getName();
    String className = VcmlUtils.getClassName(classSpec);
    int classType = VcmlUtils.getClassType(classSpec);

    // handleOptions(options, ipl, "???", "???");

    ipl.setValue(getCLASSNUM(), className);
    ipl.setValue(getCLASSTYPE(), classType);
    JCoStructure classBasicDataNew = ipl.getStructure(getCLASSBASICDATA());
    classBasicDataNew.setValue("STATUS", VcmlUtils.createIntFromStatus(object.getStatus()));
    classBasicDataNew.setValue("CLASSGROUP", nullIfEmpty(object.getGroup()));
    classBasicDataNew.setValue("VALID_FROM", getToday()); // TODO set VALID_FROM for classes?
    classBasicDataNew.setValue("VALID_TO", "9999-12-31"); // TODO set VALID_TO for classes?
    JCoParameterList tpl = function.getTableParameterList();
    final JCoTable classDescriptionsNew = tpl.getTable(getCLASSDESCRIPTIONS());
    new DescriptionHandler() {
      @Override
      public void handleSingleDescription(Language language, String value) {
        classDescriptionsNew.appendRow();
        classDescriptionsNew.setValue("CATCHWORD", value);
        classDescriptionsNew.setValue("LANGU", VcmlUtils.getLanguageCharacter(language));
        classDescriptionsNew.setValue("LANGU_ISO", language.toString());
      }
    }.handleDescription(object.getDescription());
    JCoTable classCharacteristicsNew = tpl.getTable(getCLASSCHARACTERISTICS());
    List<Characteristic> cstics = object.getCharacteristics();
    classCharacteristicsNew.appendRows(cstics.size());
    for (Characteristic cstic : cstics) {
      classCharacteristicsNew.setValue("NAME_CHAR", cstic.getName());
      classCharacteristicsNew.nextRow();
    }
    execute(function, monitor, object.getName());
    if (processReturnTable(function)) {
      commit(monitor);
    }
    endTransaction();
  }
示例#8
0
  @Override
  public void handleRequest(JCoServerContext server, JCoFunction function)
      throws AbapException, AbapClassException {

    try {
      String authToken = function.getImportParameterList().getString("IV_TOKEN");
      SimpleDiadocApi api = new SimpleDiadocApi();
      api.updateCredentials(authToken);

      String fileName = function.getImportParameterList().getString("IV_FILENAME");
      byte[] content = function.getImportParameterList().getByteArray("IV_CONTENT");

      String result = api.Recognize(fileName, content);
      function.getExportParameterList().setValue("EV_RECOGNITIONID", result);

    } catch (Exception e) {
      throw new AbapClassException(e);
    }
  }
  public void run(
      Constraint object,
      Resource resource,
      IProgressMonitor monitor,
      Map<String, VCObject> seenObjects,
      List<Option> globalOptions)
      throws JCoException {
    // determine name of containing dependencyNet
    // TODO implement finding containing dependency net with ECoreUtils
    DependencyNet dependencyNet = null;
    VcmlModel model = (VcmlModel) object.eContainer();
    for (Object o :
        EcoreUtil.getObjectsByType(model.getObjects(), VcmlPackage.Literals.DEPENDENCY_NET)) {
      DependencyNet depNet = (DependencyNet) o;
      if (depNet.getConstraints().contains(object)) {
        dependencyNet = depNet;
        break;
      }
    }

    beginTransaction();
    JCoFunction function = getJCoFunction("CAMA_CNET_CONSTRAINT_MAINTAIN", monitor);
    JCoParameterList ipl = function.getImportParameterList();

    handleOptions(object.getOptions(), globalOptions, ipl, "CHANGE_NO", null);

    ipl.setValue("CONSTRAINT", object.getName());
    if (dependencyNet != null) {
      ipl.setValue("CONSTRAINT_NET", dependencyNet.getName());
    }
    ipl.setValue("DELETE_FLAG", "X");
    try {
      execute(function, monitor, "DELETE " + object.getName());
      endTransaction();
    } catch (AbapException e) {
      handleAbapException(e);
    }
  }
示例#10
0
  /**
   * Executes RFC_READ_TABLE with a set of selection criteria specified as strings.
   *
   * @param selectionCriteria
   * @return the contents read
   * @throws JCoException
   */
  public ITableContents read(String... selectionCriteria) throws JCoException {
    JCoFunction readFunction = template.getFunction();
    readFunction.getImportParameterList().setValue("QUERY_TABLE", tableName); // $NON-NLS-1$

    JCoTable options = readFunction.getTableParameterList().getTable("OPTIONS"); // $NON-NLS-1$
    options.clear();
    if (selectionCriteria != null) {
      for (final String criterion : selectionCriteria) {
        if (criterion.length() > 72) {
          throw new IllegalArgumentException(Messages.TableReader_SelectionCriteriaTooLong);
        }
        options.appendRow();
        options.setValue("TEXT", criterion); // $NON-NLS-1$
      }
    }

    setFieldList(readFunction);
    readFunction.execute(destination);
    return new TableContents(
        tableName,
        readFunction.getTableParameterList().getTable("FIELDS"), // $NON-NLS-1$
        readFunction.getTableParameterList().getTable("DATA")); // $NON-NLS-1$
  }
示例#11
0
  /**
   * A slightly more complex example than before. Query the companies list returned in a table and
   * then obtain more details for each company.
   *
   * @throws com.sap.conn.jco.JCoException
   */
  public static void step4WorkWithTable() throws JCoException {
    JCoDestination destination = JCoDestinationManager.getDestination(ABAP_AS_POOLED);
    JCoFunction function = destination.getRepository().getFunction("BAPI_COMPANYCODE_GETLIST");
    if (function == null) throw new RuntimeException("BAPI_COMPANYCODE_GETLIST not found in SAP.");

    try {
      function.execute(destination);
    } catch (AbapException e) {
      System.out.println(e.toString());
      return;
    }

    JCoStructure returnStructure = function.getExportParameterList().getStructure("RETURN");
    if (!(returnStructure.getString("TYPE").equals("")
        || returnStructure.getString("TYPE").equals("S"))) {
      throw new RuntimeException(returnStructure.getString("MESSAGE"));
    }

    JCoTable codes = function.getTableParameterList().getTable("COMPANYCODE_LIST");
    for (int i = 0; i < codes.getNumRows(); i++) {
      codes.setRow(i);
      System.out.println(codes.getString("COMP_CODE") + '\t' + codes.getString("COMP_NAME"));
    }

    // move the table cursor to first row
    codes.firstRow();
    for (int i = 0; i < codes.getNumRows(); i++, codes.nextRow()) {
      function = destination.getRepository().getFunction("BAPI_COMPANYCODE_GETDETAIL");
      if (function == null)
        throw new RuntimeException("BAPI_COMPANYCODE_GETDETAIL not found in SAP.");

      function.getImportParameterList().setValue("COMPANYCODEID", codes.getString("COMP_CODE"));

      // We do not need the addresses, so set the corresponding parameter to inactive.
      // Inactive parameters will be  either not generated or at least converted.
      function.getExportParameterList().setActive("COMPANYCODE_ADDRESS", false);

      try {
        function.execute(destination);
      } catch (AbapException e) {
        System.out.println(e.toString());
        return;
      }

      returnStructure = function.getExportParameterList().getStructure("RETURN");
      if (!(returnStructure.getString("TYPE").equals("")
          || returnStructure.getString("TYPE").equals("S")
          || returnStructure.getString("TYPE").equals("W"))) {
        throw new RuntimeException(returnStructure.getString("MESSAGE"));
      }

      JCoStructure detail = function.getExportParameterList().getStructure("COMPANYCODE_DETAIL");

      System.out.println(
          detail.getString("COMP_CODE")
              + '\t'
              + detail.getString("COUNTRY")
              + '\t'
              + detail.getString("CITY"));
    } // for
  }
示例#12
0
  public void run(ProcedureRunner runner) throws Exception {
    CompositeMap context = runner.getContext();
    logger = LoggingContext.getLogger(context, LOGGING_TOPIC);
    logger.config("jco-invoke");
    logger.config("===================================");
    logger.log(Level.CONFIG, "config:{0}", new Object[] {this});

    ServiceInstance service = (ServiceInstance) ServiceInstance.getInstance(context.getRoot());

    //		HttpServiceInstance service = (HttpServiceInstance) HttpServiceInstance
    //				.getInstance(context.getRoot());
    CompositeMap target = null;
    CompositeMap model = null;
    if (service != null) model = service.getServiceContext().getModel();
    else model = context.getRoot().getChild("model");
    if (model == null) model = context.getRoot().createChild("model");
    if (return_target != null) {
      String t = TextParser.parse(return_target, context);
      target = (CompositeMap) model.getObject(t);
      if (target == null) target = model.createChildByTag(t);
    }
    JCoDestination destination = sapConfig.getJCoDestination(sid);
    String functionName = function;

    JCoFunctionTemplate ftemplate = destination.getRepository().getFunctionTemplate(functionName);
    logger.info("function template:" + functionName);
    if (ftemplate == null) {
      logger.log(Level.SEVERE, "Function '" + function + "' not found in SAP system.");
      throw new IllegalArgumentException("Function '" + function + "' not found in SAP system.");
    }
    // Create a function from the template
    JCoFunction function = ftemplate.getFunction();
    JCoParameterList input = function.getImportParameterList();
    JCoParameterList output = function.getExportParameterList();
    if (parameters != null)
      for (int i = 0; i < parameters.length; i++) {
        Parameter param = parameters[i];
        if (param.Return_field == null) {
          Object o =
              param.Source_field == null ? param.Value : context.getObject(param.Source_field);
          String value = o == null ? "" : o.toString();
          input.setValue(param.Name, value);
          logger.log(Level.CONFIG, "parameter {0} -> {1}", new Object[] {param.Name, value});
        }
      }
    if (structures != null) {
      for (int i = 0; i < structures.length; i++) {
        Structure structure = structures[i];
        structure.setLogger(logger);
        if (structure.isImport()) {
          JCoStructure stc = structure.getJCOStructure(input);
          structure.fillJCOStructure(stc, context);
          input.setValue(structure.Name, stc);
        }
      }
    }
    // Set import table
    if (tables != null) {
      JCoParameterList list = function.getTableParameterList();
      for (int i = 0; i < tables.length; i++) {
        Table table = tables[i];
        table.setLogger(logger);
        if (table.isImport()) {
          JCoTable tbl = table.getJCOTable(list);
          Object o = context.getObject(table.Source_field);
          logger.config(
              "transfer import table " + table.Name + " from '" + table.Source_field + "':" + o);
          if (o instanceof CompositeMap) table.fillJCOTable(tbl, (CompositeMap) context);
        }
      }
    }

    // Call the remote system and retrieve return value
    logger.config("call function " + function);
    function.execute(destination);
    if (parameters != null) {
      for (int i = 0; i < parameters.length; i++) {
        Parameter param = parameters[i];
        if (param.Return_field != null) {
          if (target == null)
            throw new ConfigurationError(
                "<jco-invoke>:must set 'return_target' attribute if there is return field");
          String vl = output.getString(param.Name);
          if (vl == null && !param.Nullable)
            throw new IllegalArgumentException(
                "jco-invoke: return field " + param.Name + " is null");
          String f = TextParser.parse(param.Return_field, context);
          target.putObject(f, vl);
          logger.config("return: " + param.Name + "=" + vl + " -> " + f);
        }
      }
    }
    if (structures != null) {
      for (int i = 0; i < structures.length; i++) {
        Structure structure = structures[i];
        structure.setLogger(logger);
        if (structure.isImport()) continue;
        if (structure.Target == null)
          throw new ConfigurationError(
              "Must set 'target' attribute for Structures " + structure.Name);
        JCoStructure stc = structure.getJCOStructure(output);
        CompositeMap result = (CompositeMap) context.getObject(structure.Target);
        if (result == null) result = context.createChildByTag(structure.Target);
        structure.fillCompositeMap(stc, result);
      }
    }
    // Get export tables
    if (tables != null) {
      JCoParameterList list = function.getTableParameterList();
      if (list == null)
        throw new IllegalArgumentException("Function '" + function + "' doesn't return tables");
      for (int i = 0; i < tables.length; i++) {
        Table table = tables[i];
        if (table.isImport()) continue;
        if (table.Target == null)
          throw new ConfigurationError("Must set 'target' attribute for table " + table.Name);
        table.setLogger(logger);
        JCoTable records = table.getJCOTable(list);
        // Fetch as CompositeMap

        CompositeMap result = (CompositeMap) context.getObject(table.Target);
        if (result == null) result = context.createChildByTag(table.Target);
        table.fillCompositeMap(records, result);
        int rc = 0;
        if (result.getChilds() != null) rc = result.getChilds().size();
        logger.config(
            "loading export table "
                + table.Name
                + " into path '"
                + table.Target
                + "', total "
                + rc
                + " record(s)");
      }
    }
  }