Skip to Content

Hello Precision Marketing evaluation users,

in this tutorial i’m going to share with you a Java sample code that will help you build your calls to the Precision Marketing partner API.

I assume you have a Partner API Developer-Id and secret, if you don’t then please get yours or generate it as indicated in the previous tutorial: SPM Evaluation: First steps using the Partner API

The Java code below will:

    – (1) Create Segments from a csv template (POST)

    – (2) Get a Segment by code  (GET)

    – (3) Detete that Segment by ID (DELETE)

These 3 calls cover the POST, GET and DELETE  calls to the REST API which cover most cases.

Notes/troubleshooting:

Code (also attached):


package eclipsePackage;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
class Test {
    URL url = null;
    String urlStr = null;
    String paramStr = null;
    String signString = null; // Needless
    String strCmdUrl = null;
    String WEB_SERVER = "https://sprpartnerapisstaging.hana.ondemand.com";
    String URL_BASE = "/partnerapi/v1/rest";
    String DEVELOPER_ID="replace_with_your_developer_id";
    String SECRET = "replace_with_your_secret";
    String boundary =  "*****";
    String attachmentName = "csv";
    String attachmentFileName = "createSegments.csv";
    String crlf = "\r\n";
    String twoHyphens = "--";
    public static void main(String args[]) throws Exception {
//    Use this piece of code if you  are behind a proxy server. Update the proxy details accordingly
//      ProxySelector.setDefault(new ProxySelector() {
//
//            @Override
//            public List<Proxy> select(URI uri) {
//                return Arrays.asList(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.wdf.sap.corp", 8080)));
//            }
//
//            @Override
//            public void connectFailed(URI arg0, SocketAddress arg1, IOException arg2) {
//                throw new RuntimeException("Proxy connect failed", arg2);
//
//            }
//
//
//
//        });
      Test test = new Test();
      test.execute();
    }
    private  String createTransactionId() throws IOException{
        HttpURLConnection connection = null;
        JsonParser parser = null;
        JsonReader reader = null;
        JsonElement jElement = null;
        JsonObject jObj = null;
        System.out.println("-- Get Transaction ID");
        strCmdUrl = "/transactionid/";
        String urlbaseStr = WEB_SERVER + URL_BASE;
        urlStr = urlbaseStr + strCmdUrl + DEVELOPER_ID;
        System.out.println("URLStr : " + urlStr);
        url = new URL(urlStr);
        String transactionId = null;
        connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(false);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Accept", "*/*");
        //Json
        parser = new JsonParser();
        reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        jElement = parser.parse(reader);
        jObj = jElement.getAsJsonObject();
        transactionId = jObj.get("data").getAsJsonObject().get("transactionId").getAsString();
        System.out.println("Response : " + jElement.toString());
        System.out.println("-- New transactionId-- : " + transactionId);
        reader.close();
    //    System.out.println("-- Header field (0) -- : " + connection.getHeaderField(0));
        //  connection.
        connection.disconnect();
    return transactionId;
    }
    private void execute() throws IOException{
        String urlbaseStr = WEB_SERVER + URL_BASE;
        String transactionId= null;
        HttpURLConnection connection = null;
        JsonParser parser = null;
        JsonReader reader = null;
        JsonElement jElement = null;
        JsonObject jObj = null;
        // (1)POST call: create a segment
        System.out.println("-- (1) -- Create Segments");
        transactionId = createTransactionId();
        strCmdUrl = "/segments?";
        paramStr = "_transactionid="+ transactionId;
        urlStr = urlbaseStr + strCmdUrl + paramStr;
        System.out.println("URLStr : " + urlStr);
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary);
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("developer-id", DEVELOPER_ID);
        connection.setRequestProperty("developer-secret", SECRET);
        DataOutputStream request = new DataOutputStream(connection.getOutputStream());
        request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
        request.writeBytes("Content-Disposition: form-data; name=\"" + this.attachmentName + "\";filename=\"" + this.attachmentFileName + "\"" + this.crlf);
        request.writeBytes(this.crlf);
        request.write(fileToByteArray());
        request.writeBytes(this.crlf);
        request.writeBytes(this.twoHyphens + this.boundary + this.twoHyphens + this.crlf);
        request.flush();
        request.close();
        //Json
        parser = new JsonParser();
        reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        jElement = parser.parse(reader);
        jObj = jElement.getAsJsonObject();
        // Print return
        System.out.println("Response : " + jElement.toString());
        reader.close();
        connection.disconnect();
    // (2)GET call: get the segment
        System.out.println("-- (2) -- Get Segment by Code");
        transactionId = createTransactionId();
        strCmdUrl = "/segments?";
        paramStr = "_transactionid="+ transactionId +"&segmentcode=DemoSegmentCode_2807737227";
        urlStr = urlbaseStr + strCmdUrl + paramStr;
        System.out.println("URLStr : " + urlStr);
        url = new URL(urlStr);
        String segmentid = null;
        connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(false);
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("developer-id", DEVELOPER_ID);
        connection.setRequestProperty("developer-secret", SECRET);
        //Json
        parser = new JsonParser();
        reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        jElement = parser.parse(reader);
        jObj = jElement.getAsJsonObject();
        System.out.println("Response : " + jElement.toString());
        segmentid = jObj.get("data").getAsJsonObject().get("segmentId").getAsString();
        System.out.println("-- SegmentID returned - "+segmentid);
        reader.close();
        //  connection.
        connection.disconnect();
        //(3) DELETE : delete the segment
        System.out.println("-- (3) -- Delete the segment by ID");
        transactionId = createTransactionId();
        strCmdUrl = "/segments?";
        paramStr = "_transactionid="+ transactionId+"&id="+segmentid;
        urlStr = urlbaseStr + strCmdUrl + paramStr;
        System.out.println("URLStr : " + urlStr);
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setUseCaches(false);
        connection.setDoOutput(false);
        connection.setRequestMethod("DELETE");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Accept", "*/*");
        connection.setRequestProperty("developer-id", DEVELOPER_ID);
        connection.setRequestProperty("developer-secret", SECRET);
        //Json
        parser = new JsonParser();
        reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        jElement = parser.parse(reader);
        jObj = jElement.getAsJsonObject();
        // Print return
        System.out.println("Response : " + jElement.toString());
        reader.close();
        connection.disconnect();
    }
    private byte[] fileToByteArray(){
    FileInputStream fileInputStream=null;
        File file = new File("/Users/user1/Downloads/createSegments.csv");
        byte[] bFile = new byte[(int) file.length()];
        try {
            //convert file into array of bytes
    fileInputStream = new FileInputStream(file);
    fileInputStream.read(bFile);
    fileInputStream.close();
    return bFile;
    }catch(Exception e){
    e.printStackTrace();
    return null;
    }
}
}












How to get this code to work?

  1. Create you Java Package and copy/paste the java code (also attached)
  2. replace your developer_ID and secret
  3. copy the attached csv file to your local and update the path in the code.
  4. Reference the GSON library in your eclipse
  5. Check that there are no errors and run the code as Java application

You should get the below response:


-- (1) -- Create Segments
-- Get Transaction ID
URLStr : https://sprpartnerapisstaging.hana.ondemand.com/partnerapi/v1/rest/transactionid/<developer_id>
Response : {"meta":{"returnCode":"OK"},"data":{"transactionId":"3e886360-991e-4de3-baec-20bd54fcd278"}}
-- New transactionId-- : 3e886360-991e-4de3-baec-20bd54fcd278
URLStr : https://sprpartnerapisstaging.hana.ondemand.com/partnerapi/v1/rest/segments?_transactionid=3e886360-991e-4de3-baec-20bd54fcd278
Response : {"meta":{"returnCode":"OK"}}
-- (2) -- Get Segment by Code
-- Get Transaction ID
URLStr : https://sprpartnerapisstaging.hana.ondemand.com/partnerapi/v1/rest/transactionid/<developer_id>
Response : {"meta":{"returnCode":"OK"},"data":{"transactionId":"c7ce705a-87f8-47a7-bae9-ebb36c7b2657"}}
-- New transactionId-- : c7ce705a-87f8-47a7-bae9-ebb36c7b2657
URLStr : https://sprpartnerapisstaging.hana.ondemand.com/partnerapi/v1/rest/segments?_transactionid=c7ce705a-87f8-47a7-bae9-ebb36c7b2657&segmentcode=DemoSegmentCode_2807737227
Response : {"meta":{"returnCode":"OK"},"data":{"segmentId":2657,"segmentCode":"DemoSegmentCode_2807737227","segmentType":"DemoSegmentType","segmentName":"DemoSegmentName","segmentDescription":"DemoSegment","customerProfileIds":[],"offerIds":[]}}
-- SegmentID returned - 2657
-- (3) -- Delete the segment by ID
-- Get Transaction ID
URLStr : https://sprpartnerapisstaging.hana.ondemand.com/partnerapi/v1/rest/transactionid/<developer_id>
Response : {"meta":{"returnCode":"OK"},"data":{"transactionId":"82df6c7f-624d-4d8a-bc81-bb7d23e5537b"}}
-- New transactionId-- : 82df6c7f-624d-4d8a-bc81-bb7d23e5537b
URLStr : https://sprpartnerapisstaging.hana.ondemand.com/partnerapi/v1/rest/segments?_transactionid=82df6c7f-624d-4d8a-bc81-bb7d23e5537b&id=2657
Response : {"meta":{"returnCode":"OK"}}








Congrats, you just built your first calls to the Partner API in Java!

What now?

You should now be able to make all the other calls described in the SPM Partner API documentation, they are all built using the same pattern.

The full documentation of the partner API is available here: https://help.sap.com/spm  select the Partner Services API Documentation


have fun modeling your tenant, and send us feedback via the comments below or by writing to SAPprecisionmarketing-info@sap.com

Louay

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply