PUT Object operation is used to add an object to the bucket.
Following code is used to PUT object in the bucket.
HttpURLConnection object is used to create a PUT request with URL containing path to objectName. For a successful request, HttpStatus.SC_OK response code is returned.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpStatus;
public class ObjectOperations {
/*
* This program adds a object to the bucket
* @param serverURL: URL of S3 Compatible REST server(http://<S3 server IP> : <S3 server port> /queryio/). For example: http://192.168.0.1:5667/queryio/
* @param token: authorization token.
* @param bucketName: Name of the bucket in which object will be added
* @param objectName: Name of the object to be added
* @param filePath: Path of the local file that will be uploaded
*/
public static void putObject(String os3Url, String token, String bucket, String object, String filePath) throws Exception
{
HttpPut request = new HttpPut(os3Url + bucket + "/" + object); //HttpPut instance with path of the object to be created
request.addHeader("authorization", token); //Provides token for authorization
RandomAccessFile f = new RandomAccessFile(filePath, "r"); //Instance to read object provided on filepath
byte[] b = new byte[(int)f.length()]; //get total length of object in bytes.
f.read(b); //read number of bytes from object
request.setEntity(new ByteArrayEntity(b)); //assign PUT request with byte array of object to be uploaded
DefaultHttpClient client = new DefaultHttpClient(); //Create object of DefaultHttpClient
HttpResponse response = client.execute(request); //Executes the client request
if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) //Check for OK response
{
System.err.println(response.getStatusLine().getReasonPhrase());
throw new Exception("Put Object failed"); //Create object operation failed
}
}