Share via


Creating an Entity Using REST (Java)

[This document supports a preliminary release of a software product that may be changed substantially prior to final commercial release. This document is provided for informational purposes only.]

As described in Creating an Entity Using REST, the following Java example creates an entity in the specified container. For details about creating a Java application, see Building and Executing Java Samples.

Note

Credentials are required to access the service. To make a working sample, update following code and provide your existing authority id, container id and unique id for the new entity.

import java.io.IOException;
import java.net.*;
import java.io.*;

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;


public class CreateEntityUsingREST
{
// Provide your values for the member variables
 private static String UserId;
 private static String UserPw;
final private static String authorityId = "<YourExistingAuthorityId>";
final private static String containerId = "<YourExistingContainerId>";
final private static String sampleEntityId = "<NewEntityId>";
final private static String ssdsContentType = "application/x-ssds+xml";
final private static String HttpPostMethod = "POST";
final private static String EntityTemplate = "<Book xmlns:s='https://schemas.microsoft.com/sitka/2008/03/'"
+ " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"
+ " xmlns:x='http://www.w3.org/2001/XMLSchema' > "
+ " <s:Id>%s</s:Id> "
+ " <title xsi:type='x:string'>%s</title> "
+ "  <summary xsi:type='x:string'>%s</summary> "
+ " <isbn xsi:type='x:string'>%s</isbn> "
+ " <author xsi:type='x:string'>%s</author> "
+ " <publisher xsi:type='x:string'>%s</publisher> " + "</Book>";

public static void main(String[] args)
{
UserId = ReadFromConsole("UserName");
UserPw = ReadFromConsole("Password");

String containerUri = String.format(
"https://%s.data.database.windows.net/v1/%s", authorityId,
containerId);

// Create Book entity - request payload to send over the wire
String requestPayload = String.format(EntityTemplate, sampleEntityId,
"My first used book using REST", "Some Summary",
"1-77880-057-9", "Author A", "Publisher B");
// Create entity in a specific container
CreateEntity(containerUri, requestPayload);
}

private static String ReadFromConsole(String message)
{
String input = null;
System.out.print(message + ":");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
try
{
input = br1.readLine();
}
catch (IOException ioe) {
System.out.println("IO error reading login name!");
System.exit(1);  
}

return input;
}

private static void CreateEntity(String containerUri,
String requestPayload) throws IllegalArgumentException
{
if (containerUri == null || containerUri.isEmpty())
{
throw new IllegalArgumentException("containerUri");
}
if (requestPayload == null || requestPayload.isEmpty())
{
throw new IllegalArgumentException("requestPayload");
}

try
{
HttpMethod response = IssueRequest(HttpPostMethod, containerUri,
requestPayload, HttpStatus.SC_CREATED);

// Read the response body if there is data to read from the stream.
if(response.getResponseBodyAsStream().available() > 0)
{
   ObjectInputStream responseStream = new ObjectInputStream(response.getResponseBodyAsStream());
  String responseMsg = responseStream.readUTF();
   System.out.println("Response was: " + responseMsg);
}


} catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}

private static HttpMethod IssueRequest(String method, String uri,
String body, int expectedStatus) throws Exception,
IllegalArgumentException
{
if (method == null || method.isEmpty())
{
throw new IllegalArgumentException("method");
}
if (uri == null || uri.isEmpty())
{
throw new IllegalArgumentException("uri");
}
if (body == null || body.isEmpty())
{
throw new IllegalArgumentException("body");
}

// Define the HTTP client that we'll use.
HttpClient client = new HttpClient();
HttpMethod requestMethod = null;

if (method.equals(HttpPostMethod))
{
requestMethod = new PostMethod(uri);
            ((PostMethod) requestMethod).setRequestEntity(new StringRequestEntity(body, ssdsContentType, null));
} else
{
throw new Exception("Unsupported method type provided");
}

URL requestUrl = new URL(uri);

try
{
// Next, set the credentials we'll be using on the request.
Credentials defaultcreds = new UsernamePasswordCredentials(UserId,
UserPw);
client.getState().setCredentials(
new AuthScope(requestUrl.getHost(), 443,
AuthScope.ANY_REALM), defaultcreds);

// Then, state that we do want to do authentication on these
// requests.
requestMethod.setDoAuthentication(true);

// Provide custom retry handler if a retry is necessary
requestMethod.getParams().setParameter(
HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));

// Execute the method.
int statusCode = client.executeMethod(requestMethod);
if (statusCode != expectedStatus)
{
System.err.println("Method failed: "
+ requestMethod.getStatusLine());

throw new Exception("Expected status code not returned!");
}

} catch (HttpException e)
{
System.out.println(e.getMessage());
} catch (IOException e)
{
System.out.println(e.getMessage());
}

return requestMethod;
}
}

See Also

Concepts

Creating an Entity Using REST
SDS Data Model Overview (Authorities, Containers, Entities and Flexible Entities)