Created On:  02 November 2011

Problem:

How do I create a Testplan via the SilkCentral Services Exchange in Java using Apache HttpClient 4.x?

Resolution:

The code below demonstrates how to create a Testplan via the SilkCentral Services Exchange using Apache HttpClient 4.x using Java as the programming language:

public static void createTP(String sFileName, String sServer, int sPort,int iParentNode, String sUser, String sPassword){
     try
{
          URL sctm =
new URL("http", sServer, sPort,String.format("/servicesExchange?hid=%s&parentNodeID=%d&userName=%s&passWord=%s", "createTestPlan", iParentNode,sUser, sPassword));

          System.
out.println("URL: "+sctm.toString());

         
//Create an entity with the modified testplan xml file
         
MultipartEntity entTP = new MultipartEntity();
          entTP.addPart(sFileName,
new StringBody(ServExchange.loadTPUTF8(sFileName),"text/xml", Charset.forName("UTF-8")));

         
//add the testplan xml file entity to the HttpPost object
         
HttpPost postTP = new HttpPost(sctm.toExternalForm());
          postTP.setEntity(entTP);

         
//Execute the updateTestPlan method with the updated testplan xml
          HttpClient client = new DefaultHttpClient();

          System.
out.println(client.execute(postTP).toString());
     }
    
catch(Exception e){
          e.printStackTrace();
     }
}


//Reads the modified testplan xml file
public static String loadTPUTF8(String sFileName){
     BufferedReader in =
null;
     String s, UTF8Str =
""
;

    
try {
          in =
new BufferedReader(new FileReader(sFileName));

         
while( ( s = in.readLine() ) != null) {
               UTF8Str +=
new String(s.getBytes(),"UTF-8");
          }
     }
catch (Exception e) {
          e.printStackTrace();
     }

    
return UTF8Str;
}



Where:
    - sFileName is the path the XML file containing the testplan information
    - sServer is the SilkCentral server machines IP address or hostname
    - iPort is the port on which SilkCentral is accessed
    - iParentNode is the node id to which the testplan is to be added
    - sUser is the SilkCentral username to be used to perform the operation
    - sPassword is the password associated with the said SilkCentral account

To use the above we would simply need to make a call similar to the following, if the above method was contained in a class named ServExchange:

    ServExchange.createTP(

"C:\\test.xml", "bel-robertm7", 19120, 84, "admin", "admin");