daniel.kuenstel

3 Posts

 

The official StreamWork Java API samples mainly discuss the usage of the API itself but are missing the OAuth authorizaton part. For somebody who is not familar with the OAuth specification this can easily mean lots of effort to understand and implement the necessary OAuth calls.
While it is important to know OAuth to implement a client it shouldn't be necessary to understand all details about OAuth just to execute the first few API calls. For this reason, this blog presents sample code to handle the authentication part and provides a base skeleton using the Scribe OAuth library to execute further API calls. For the actual usage of the SteamWork API itself, please refer to the official samples or the API documentation. The sample code of this blog is available as Code Exchange project.
 
Prerequisites:

    Create a new StreamWork account at https://streamwork.com/user_registrations/new if not already done.
    Register a consumer application at https://streamwork.com/oauth_clients and write down the consumer key and consumer secret. Both are required to execute the sample
    Download the sources from Code Exchange. Please use http://m2eclipse.sonatype.org/  to import the project into Eclipse.

       

      Configuration:</p><ol><li>Open class StreamWorkAppAuthorizationUtil, configure your proxy settings (if necessary) and enter the consumer app credentials within the init() method.</li><li>Execute StreamWorkAppAuthorizationUtil#test_getAccessTokenByUserPrompt() as JUnit 4 testcase to get a permanent access token for your StreamWork account. An access token (together with the according secret) allows to make calls to the StreamWork API in the context of the user.<br />The authorization requires the user to login to StreamWork and authorize the application. The testcase will prompt you to open your browser, do the authorization and paste the so called OAuth verifier back to the TestCase. The access token will then be retrieved automatically and printed to the screen.</li><li>Enter the access token retrieved in the last step to StreamWorkAppAuthorizationUtil. Now you are ready to make your first api call. Just execute the method #test_accessTokenValid() to verify everything is correct. In case an error appears please verify you have pasted the access token correctly.</li><li>Execute the method #test_demoApiAccess() as an demo for an API call. The required OAuth information is added automatically to the request. As sample output looks like this:<?xml version="1.0" encoding="UTF-8"?><activities total_number_of_activities="0"></activities> </li></ol><p>The mentioned steps should be sufficient to be able to call any API available by StreamWork.<br />To make the StreamWork usage more efficient, additional steps could be taken, e.g.</p><ul><li>Wrap the StreamWork api using JAXB or another XML binding framework to work directly using Java objects instead of parsing XML responses.</li><li>Write a servlet which intercepts the StreamWork authorizatoin response to make the authorization process more comfortable. It won't be required afterwards to manually paste the OAuth verifier string.</li></ul><p>So basically you should now be able to explore the available StreamWork api and implement your demo scenario.</p>

      This is another post  of our Netweaver Mobile 7.1 series where we share best practices and tips and tricks for development of mobile applications. The available blogs in this series are

      Stefan Henke reported in his last What you ever wanted to know about pda development in mobile 7.1 (part 2) howto connect to the database of Netweaver Mobile (minDB or db2e) using DBVisualizer. Sometimes it is also helpful to connect to the database from a standalone Java application using plain JDBC, e.g. for advanced or repeated tasks. So I will give you the sample code to do this. By reading this blog you can execute your first JDBC query within five minutes and avoid common pitfalls.

      Installation

      The code is packaged up as simple Eclipse project. Extract the attached zip file, open Eclipse or the Netweaver Developer Studio and import it using File -> Import -> Existing Project into workspace. You have to copy the JDBC driver to the lib directory and add it to the classpath (right click on the jar file select "Build Path" and "Add To Build Path"). You can get the driver from you Netweaver Mobile MI/lib folder. Afterwards you have to edit the jdbc.properties to define the connection settings of your database. Here you have to select whether you are using minDB or db2e (just uncomment the appropriate lines for your db) and maintain the path to your database in the jdbc.url in line. E.g. if you are using minDB and the MI folder of your Netweaver Mobile installation is located at C:NetweaverMobileMI, the file should look something like this:

      jdbc.user=dba
      jdbc.password=dba
      jdbc.driver=com.sap.sdb.minDB.DriverEmbeddedMinDB
      jdbc.url=jdbc:embeddedMinDB://?minDB=C:/NetweaverMobile/MI/data

      Afterwards you can run the demo query from the DemoQuery class, e.g. launch it by executing "Netweaver Mobile JDBC demo" from the launch configuration menu. The query will print the names of the installed Development Components, so make sure you have already deployed some applications to your client. The output will look something like this:

      Currently installed DCs:
      demo.sap.com~some_sample_app~implementation

      If the query is working you can start to write your own code.

      Caution

      Before you access the client via JDBC please make a backup of your data, you could destroy it. Do not modify any system tables of Netweaver Mobile, the client may stop working properly after doing this. Make sure the client is not running before you try to access its database. Never ever try to use JDBC code from within your current mobile application to access the running client.

      To access a minDB the client has to be started at least one time, since the database is created on the first startup.

      Sample Code

      Below you can see the classes and the jdbc.properties used for this sample. Just create an Eclipse project and paste the content into the appropriate classes. I had to post the code this way, since I couldn't upload the code as zip file. If you want to have the code as zip, please request it by mail. Sorry for this inconvenience.

      package com.sap.mobile.jdbcsample;
      import java.io.IOException;
      import java.sql.Connection;
      import java.sql.ResultSet;
      import java.sql.SQLException;
      import java.sql.Statement;
      /**
       * Sample code which shows howto query the database of Netweaver Mobile with plain JDBC.
       * The connection settings are maintained in /src/main/resources/jdbc.properties
       */
      public class DemoQuery {
       private final Connection connection;
       public DemoQuery(Connection connection) {
        this.connection = connection;
       }
       public static void main(String[] args) throws Exception {
        //init and create the database connection, maintain the connection settings in jdbc.properties
        JdbcConnectionManager jdbcConnectionManager = new JdbcConnectionManager(
          new DatabaseProperties());
        Connection connection = jdbcConnectionManager.createConnection();
        
        
        new DemoQuery(connection).run();
       }

       private void run() throws SQLException, IOException {
        
        Statement st1 = connection.createStatement();
        //hint: the easiest way to lookup the table names is using a graphical tool like db visualizer
        st1.execute("SELECT DO_NAME FROM CFS_APPLICATION");
        ResultSet rs = st1.getResultSet();
        System.out.println("Currently installed DCs:");
        while (rs.next()){
         System.out.println(rs.getString("DO_NAME"));
        }
       }
      }
       
      package com.sap.mobile.jdbcsample;
      import java.io.IOException;
      import java.io.InputStream;
      import java.util.Properties;
      /**
       * Stores database connections settings. The settings are loaded by default from
       * the jdbc.properties file which is read from the classpath and imports the
       * connection settings
       *
       * @see JdbcConnectionManager
       */
      public class DatabaseProperties {
       public static final String JDBC_PROPERTY_USER = "user";
       public static final String JDBC_PROPERTY_PASSWORD = "password";
       private String username;
       private String password;
       private String jdbcUrl;
       private String jdbcDriver;
       private Properties connectionProperties;
       /**
        * Loads the connection settings from /jdbc.properties classpath resource.
        *
        * @throws IOException
        */
       public DatabaseProperties() throws IOException {
        Properties jdbcProperties = loadPropertiesFromClassPath("/jdbc.properties");
        importSettings(jdbcProperties);
       }
       /**
        * Loads the connection setting from a given {@link Properties} object.
        *
        * @param connectionProperties
        * @throws IOException
        */
       public DatabaseProperties(Properties connectionProperties)
         throws IOException {
        importSettings(connectionProperties);
       }
       private Properties loadPropertiesFromClassPath(String jdbcPropResource) throws IOException {
        Properties p = new Properties();
        InputStream jdbcPropsIS = getClass().getResourceAsStream(
          jdbcPropResource);
        if (jdbcPropsIS == null) {
         throw new IllegalStateException(
           "Could not load " + jdbcPropResource + " from classpath because it could bot be found. " +
           "Verify " + jdbcPropResource + " is present on the root classpath.");
        }
        p.load(jdbcPropsIS);
        jdbcPropsIS.close();
        return p;
       }
       private void importSettings(Properties p) throws IOException {
        username = p.getProperty("jdbc.user", "");
        password = p.getProperty("jdbc.password", "");
        jdbcUrl = p.getProperty("jdbc.url");
        jdbcDriver = p.getProperty("jdbc.driver");
        connectionProperties = new Properties();
        connectionProperties.setProperty(JDBC_PROPERTY_USER, getUsername());
        connectionProperties.setProperty(JDBC_PROPERTY_PASSWORD, getPassword());
       }
       public String getJdbcUsername() {
        return username;
       }
       public String getJdbcUrl() {
        return jdbcUrl;
       }
       public String getJdbcDriver() {
        return jdbcDriver;
       }
       public String getUsername() {
        return username;
       }
       public String getPassword() {
        return password;
       }
       public Properties getConnectionProperties() {
        return connectionProperties;
       }
       public String toString() {
        return username + "@" + jdbcUrl + ", driver: " + jdbcDriver;
       }
      }
      package com.sap.mobile.jdbcsample;
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.SQLException;
      import java.util.logging.Logger;
      /**
       * Loads the JDBC driver and allows to create JDBC {@link Connection}s.
       * The connection and JDBC settings are loaded using {@link DatabaseProperties}.
       */
      public class JdbcConnectionManager {
       private final static Logger logger = Logger.getLogger(JdbcConnectionManager.class .getName());
       
       private final DatabaseProperties dbProps;
       public JdbcConnectionManager(DatabaseProperties dbProps) throws Exception {
        this.dbProps = dbProps;
        try{
         Class jdbcDriverClass = Class.forName(dbProps.getJdbcDriver());
         jdbcDriverClass.newInstance();
        }catch (ClassNotFoundException e) {
         throw new RuntimeException("Couldnt find the JDBC driver class "" + dbProps.getJdbcDriver()
          + "". Please ensure the jdbc driver is on the classpath and configured properly in jdbc.properties.", e);
        }
        logger.info("Loaded the " + dbProps.getJdbcDriver() + " JDBC driver.");
          }
       
       public Connection createConnection() throws SQLException{
              Connection connection = DriverManager.getConnection(dbProps.getJdbcUrl(), dbProps.getConnectionProperties());
              connection.setAutoCommit(false);
              return connection;
       }
      }

      jdbc.properties (just put it into the root classpath)


      jdbc.user=dba
      jdbc.password=dba
      ######
      #db2e#
      ######
      #ensure the project references the db2e jdbc driver db2ejdbc.jar to use minDB
      #the native db2e DLLs (DB2e.dll, DB2eJDBC.dll and CryptoPlugin.dll are required to be in the
      #java library path, e.g. copy them to your windows folder else a UnsatisfiedLinkError or
      #ClassNotFoundException may be thrown
      #It is also possible just to go to the context menu of db2ejdbc.jar and enter the full path to your
      #Netweaver Clients MI/bin folder in the Native Library tab
      jdbc.driver = com.ibm.db2e.jdbc.DB2eDriver
      #caution: the trailing "/" is important, dont forget it
      jdbc.url=jdbc:db2e:C:/NetweaverMobile/MI/data/

      #######
      #mindb#
      #######
      #ensure the project references the minDB jdbc driver minDBembedded.jar to use minDB
      #jdbc.driver=com.sap.sdb.minDB.DriverEmbeddedMinDB
      #jdbc.url=jdbc:embeddedMinDB://?minDB=C:/NetweaverMobile/MI/data
       

      This is another post  of our Netweaver Mobile 7.1 series where we share best practices and tips and tricks for development of mobile applications. The available blogs in this series are

      This is the 3rd post in this series. It describes how the autologin feature of Netweaver Mobile 7.1 helps to increase productivity during development.

      During development of an Netweaver Mobile application redeploying components and restarting the container is required quite often. It can become annoying to login to the container on each startup again, especially when the container is running on a PDA and no keyboard is available. It would be preferable to skip the login to shorten the roundtrip time.

      To achieve this Netweaver Mobile 7.1 offers a feature called "autologin" to supply the username and password credentials through Java system properties. So it is not necessary anymore to enter the credentials manually in the login screen. The name of the according system properties are mobile.dbguser.name and mobile.dbguser.password. These have to be appended to your startup command line. If you use myuser / mypass  as username / password the appropriate line is

      -Dmobile.dbguser.name=myuser -Dmobile.dbguser.password=mypass

      For the desktop version of the client it has to be added to MI/bin/startup.bat, the wince version uses MI/bin/launch.properties. E.g. after modification the startup.bat looks somehow like this:

      set MOBILE_JVM_OPTS=%MOBILE_JVM_OPTS% -Dmobile.home=.. -Dtomcat.home=..     omcat  -Dmobile.dbguser.name=myuser -Dmobile.dbguser.password=mypass 
      "%JAVA_HOME% injava" -Xmx512M -classpath "%MOBILE_BIN%sap.com~tc~mobile~cfs~startup~impl.jar" %MOBILE_JVM_OPTS% com.sap.tc.mobile.cfs.startup.pda.Startup %MOBILE_OPTS%

      If the container is started from within Eclipse the arguments can be added to the VM arguments of the launch configuration.

      Note: The user is not automatically created by setting these system properties, so you still have to manually create it on your first container login. To login with a different user you can just use the logoff menu entry to come to the login screen again.

      This hint applies to Netweaver Mobile 7.1 beginning with SP3 and a recent patch level.

      Filter Blog

      By date: