PUT mp4 file using AWS presigned url - amazon-web-services

Currently I'm having issues sending a mp4 video file over put request to a presigned AWS url. We have it generated but when I send the video, its just a 32kb file that doesn't play.
My current code is as follows:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Cache-Control", "no-cache");
connection.setRequestProperty("Content-Type", "video/mp4");
DataOutputStream request = new DataOutputStream(connection.getOutputStream());
byte[] buffer = new byte[BUFFER_SIZE];
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
while (inputStream.read(buffer) != -1) {
request.write(buffer);
}
I get OK - 200 Response Code but I think my video file is being messed up somehow?
What am I doing wrong?

This streaming code is incorrect:
byte[] buffer = new byte[BUFFER_SIZE];
InputStream inputStream = ...;
while (inputStream.read(buffer) != -1) {
request.write(buffer);
}
It should be more like this:
int length;
byte[] buffer = new byte[BUFFER_SIZE];
InputStream inputStream = ...;
while ((length = inputStream.read(buffer)) != -1) {
request.write(buffer, 0, length);
}

Related

How can get byte of pdf before download? - Grails

I can download pdf file from AWS, download is working fine but I need get byte before download.
String awsBucket = params.awsBucket
String awsKey = params.awsKey
String fileName = params.fileName
String pdfLink = params.pdfLink
File file = grailsApplication.mainContext.getResource('WSCredential.properties').file
FileInputStream fileInputStream = new FileInputStream(file)
AmazonS3 s3Client = new AmazonS3Client(new PropertiesCredentials(fileInputStream))
GetObjectRequest getObjectRequest = new GetObjectRequest(awsBucket, awsKey)
userReceipt = s3Client.getObject(getObjectRequest)
if (userReceipt)
{
response.setContentType("application/image/png")
response.setHeader("Content-disposition", "attachment;filename=\"${fileName}\"")
response.outputStream << userReceipt.getObjectContent()
}
If you mean the size of PDF, then you can use HeadObject.

microsoft speech api bad request

can anyone check if there are error/s on my code: this is to pass byte for the microsoft speech api, however i received 400 bad request error. wav file format is correct since i used the sample from microsoft. any help would be appreciated!
public void speechToText(){
String Key = "mysubscriptionkey";
try {
File file = new File("filepath", "filename.wav");
URL url = new URL("https://westus.stt.speech.microsoft.com/speech/recognition/interactive/cognitiveservices/v1?langauge=en-US&format=simple");
HttpURLConnection con =(HttpURLConnection)url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.addRequestProperty("Content-type", "audio/wav; codec=\"audio/pcm\"; samplerate=16000");
con.addRequestProperty("Ocp-Apim-Subscription-Key", Key);
byte[] bytes = ReadFully(file);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.write(bytes);
Scanner scanner = new Scanner(con.getInputStream());
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
catch (Exception e)
{
e.printStackTrace();
}
--this one to read audio
public byte[] ReadFully(File file){
ByteArrayOutputStream out = new ByteArrayOutputStream();
try{
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[1024];
int bytesRead;
OutputStream outputstream ;
while ((bytesRead = in.read(buffer)) != -1){
out.write(buffer, 0, bytesRead);
}
}
catch (Exception e){
e.printStackTrace();
}
return out.toByteArray();
}

saaj exception - Unable to parse content type: null

I'm fairly new to webservices and working through a SAAJ example of sending and recieving attachments (binary files). I can get it to work when the client sends the file but not when it requests it. I get an exception on the client side:
ERROR: 'Content is not allowed in prolog.'
24-Oct-2012 13:59:28 com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory createEnvelope
SEVERE: SAAJ0511: Unable to create envelope from given source
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source
Anybody have any ideas???my client code is as follows:
SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
SOAPConnection con = scf.createConnection();
SOAPFactory soapFactory = SOAPFactory.newInstance();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage msg = mf.createMessage();
SOAPHeader header = msg.getSOAPHeader();
header.detachNode();
SOAPBody body = msg.getSOAPBody();
Name bodyName = soapFactory.createName(
"remoteOpen", "remoteOpen",
"http://schemas.remoteOpen.com/remoteOpen");
SOAPBodyElement bodyElement = body.addBodyElement(bodyName);
SOAPElement projectName = bodyElement.addChildElement("projectName");
projectName.addTextNode("filename");
msg.saveChanges();
// create the endpoint and send the message
URL endpoint = new URL("http://localhost:8080/RemoteSaveProject/OpenServlet");
SOAPMessage response = con.call(msg, endpoint);
con.close();
SOAPBody responseBody = response.getSOAPBody();
SOAPElement ackElem = (SOAPElement)responseBody.getFirstChild();
String acknowledgement = ackElem.getValue();
the server code looks like this:
MimeHeaders mimeHeaders = new MimeHeaders();
Enumeration en = request.getHeaderNames();
while (en.hasMoreElements())
{
String headerName = (String)en.nextElement();
String headerVal = request.getHeader(headerName);
StringTokenizer tk = new StringTokenizer(headerVal, ",");
while (tk.hasMoreTokens()){
mimeHeaders.addHeader(headerName, tk.nextToken().trim());
}
}
SOAPMessage message = mf.createMessage(mimeHeaders, request.getInputStream());
SOAPBody body = message.getSOAPBody();
Name bodyName = soapFactory.createName(
"remoteOpen", "remoteOpen",
"http://schemas.remoteOpen.com/remoteOpen");
Iterator projects = body.getChildElements(bodyName);
SOAPElement project = (SOAPElement)projects.next();
Iterator projectNameIter = project.getChildElements(soapFactory.createName("projectName"));
SOAPElement projectNameEle = (SOAPElement)projectNameIter.next();
String projectName = projectNameEle.getValue();
File file = new File(projectName);
SOAPMessage reply = mf.createMessage();
SOAPHeader header = reply.getSOAPHeader();
header.detachNode();
SOAPBody replyBody = reply.getSOAPBody();
SOAPBodyElement bodyElement = replyBody.addBodyElement(soapFactory.createName("ack"));
bodyElement.addTextNode("OK");
DataHandler dh = new DataHandler(new FileDataSource(file));
AttachmentPart attachment = reply.createAttachmentPart(dh);
attachment.setContentId("123");
reply.addAttachmentPart(attachment);
reply.saveChanges();
response.setStatus(HttpServletResponse.SC_OK);
putHeaders(reply.getMimeHeaders(), response);
response.setContentType("text/xml");
ServletOutputStream replyOS = response.getOutputStream();
reply.writeTo(replyOS);
replyOS.flush();
replyOS.close();
putHeaders looks like:
Iterator it = headers.getAllHeaders();
while (it.hasNext())
{
MimeHeader header = (MimeHeader) it.next();
String[] values = headers.getHeader(header.getName());
if (values.length == 1)
{
res.setHeader( header.getName(), header.getValue());
}
else
{
StringBuffer concat = new StringBuffer();
int i = 0;
while (i < values.length)
{
if (i != 0)
{
concat.append(',');
}
concat.append(values[i++]);
}
res.setHeader(header.getName(), concat.toString());
}
}
If you are using Google app engine, like me, the problem is that GAE doesn't support com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ParameterList which is used internally somewhere in the call chain of javax.xml.soap.SOAPConnection.call(). So you must use a workaround.
I personally did it by using java.net.HttpURLConnection instead of javax.xml.soap.SOAPConnection and manually sending and parsing SOAP messages.

trying to upload video using graph api

I have been trying to implement a video upload facebook feature for my mobile app for a while now but never really succeeded with rest. I learnt yesterday that the graph alternative was available.
After getting a few errors to do with access key mainly i have gotten to the point where output stream succesfully writes the movie file and the input stream just receives an empty json array once i have written the 3gp file.
Anyone any idea why I would get an empty json array and no video gets published when i get all my code to run, i get 200 response code and the server sends me a non error response?
Any help greatly appreciated.
Here is the class that gets the blank json array (send method). I have appended the token to the url and in the table to be sure. I am sorry if the code is untidy buts it just been a day of trial and error.
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import net.rim.device.api.io.http.HttpProtocolConstants;
public class HttpMultipartRequest2
{
static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";
byte[] postBytes = null;
String url = null;
Hashtable paramsTable;
public HttpMultipartRequest2(String url, Hashtable params,
String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
{
this.url = url;
String boundary = getBoundaryString();
paramsTable = params;
String boundaryMessage = getBoundaryMessage(boundary, params, fileField, fileName, fileType);
String endBoundary = "\r\n--" + boundary + "--\r\n";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write(boundaryMessage.getBytes());
bos.write(fileBytes);
bos.write(endBoundary.getBytes());
this.postBytes = bos.toByteArray();
bos.close();
}
String getBoundaryString() {
return BOUNDARY;
}
String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType)
{
StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");
Enumeration keys = params.keys();
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
String value = (String)params.get(key);
res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")
.append("\r\n").append(value).append("\r\n")
.append("--").append(boundary).append("\r\n");
}
res.append("Content-Disposition: form-data; name=\"").append(fileField)
.append("\"; filename=\"").append(fileName).append("\"\r\n")
.append("Content-Type: ").append(fileType).append("\r\n\r\n");
Log.info(("res "+res.toString()));
return res.toString();
}
public String send() throws Exception
{
StringBuffer sb = new StringBuffer();
HttpConnection hc = null;
InputStream is = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] res = null;
try
{
Log.info("before hc open"+ url);
hc = (HttpConnection) Connector.open(url);
hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());
hc.setRequestProperty("access_token", (String)paramsTable.get("access_token"));
hc.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH, String.valueOf(postBytes.length));
hc.setRequestProperty( "x-rim-transcode-content", "none" );
ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream dos = hc.openOutputStream();
is = hc.openInputStream();
Log.info("before dos write responsecode");// + hc.getResponseCode());
out.write(postBytes, 0, postBytes.length);
//Log.info("flushing"+ hc.getResponseCode());
Log.info("after doswrite responsecode");
dos.write(out.toByteArray());
dos.flush();
Log.info("after flush");
if(dos!=null)
dos.close();
int ch;
Log.info("before openinput ");
Log.info("after openinput ");
while ((ch = is.read()) != -1)
{
bos.write(ch);
sb.append((char)ch);
Log.info("char"+(char)ch);
}
res = bos.toByteArray();
Log.info("Response recieved from Server is : " + sb.toString() );
}
catch(Exception e)
{
Log.info(hc.getResponseCode() + "sexce"+e);
}
catch(OutOfMemoryError error)
{
Log.info("outofmemory " + error);
System.gc();
}
finally
{
try
{
if(bos != null)
bos.close();
if(is != null)
is.close();
if(hc != null)
hc.close();
}
catch(Exception e2)
{
Log.info("finally exception"+ e2);
}
}
return sb.toString();
}
}
Are you trying to upload to a user's feed or to a page? There is an Open Bug regarding posting to pages.
Also, could you post some code?
Assuming that you've read the documentation:
Facebook Graph API->Video
And that you are using graph-video.facebook.com, not graph.facebook.com.

How to call .Net webservice in Blackberry?

I would like to call .Net webservice from my Blackbrry application. How can I call webservice from my app and which protocol is user and which jar file i have to used to call webservice. and how to get responce from webservice in Blackberry?
you can use something like this (you probably need to setup correct request headers and cookies):
connection = (HttpConnection) Connector.open(url
+ ConnectionUtils.getConnectionString(), Connector.READ_WRITE);
connection.setRequestProperty("ajax","true");
connection.setRequestProperty("Cookie", "JSESSIONID=" + jsessionId);
inputStream = connection.openInputStream();
byte[] responseData = new byte[10000];
int length = 0;
StringBuffer rawResponse = new StringBuffer();
while (-1 != (length = inputStream.read(responseData))) {
rawResponse.append(new String(responseData, 0, length));
}
int responseCode = connection.getResponseCode();
if (responseCode != HttpConnection.HTTP_OK) {
throw new IOException("HTTP response code: " + responseCode);
}
responseString = rawResponse.toString();