IOException when Uploading Videos to YouTube via Java API - java

I have been attempting to upload videos to YouTube via the JavaAPI using Direct Uploading. I have been having a problem when I call the insert() method, I get a IOException with the error message
"Error writing request body to the server"
I have verified that the File object I am creating is correct as well as all the details in my VideoEntry object. I have been using Fiddler to monitor the activity from my machine and no request is made to the upload API so the problem is not there. Here is a summary of the code I am using:
VideoEntry newVideo = new VideoEntry();
//Defined video properties such as title and description here.
MediaFileSource ms = new MediaFileSource(videoFile, "video/flv");
newVideo.setMediaSource(ms);
VideoEntry createdEntry = settings.insert(new URL(apiUrl), newVideo);
The IOException is thrown on the insert call (settings is my YouTubeService instance) and the API URL appears to be correct.
Prior to this I have succeeded in uploading this video using the C# API so I know the video file is valid.
--Update
This is the apiURL value:
http://uploads.gdata.youtube.com/feeds/api/users/default/uploads

Make certain that videoFile actually points to the correct local file. The File(String) constructor won't verify that it actually exists. The MediaFileSource constructor and VideoEntry.setMediaSource() method also never check that the file is valid. The error message "Error writing request body to the server" sounds like the insert method can not find the body of the message it is trying to send.
File videoFile = new File("...");
if (videoFile.exists() == false) {
System.err.println("FAIL");
}
to test if the file exists.

If you are under a firewall env and had configured your proxy settings in jvm system properties. The try configuring your youtube service as:
service.setChunkedMediaUpload(MediaService.NO_CHUNKED_MEDIA_REQUEST);
or in your case
settings.setChunkedMediaUpload(MediaService.NO_CHUNKED_MEDIA_REQUEST);
since as you say is your YouTubeService instance.
hope this helps.

Related

How to stream S3 object directly from Java web server to browser

What I have tried so far is
S3Object object = s3Object.getObject(new getObjectRequest(bucketName,FileName));
InputStreamResource inputStreamResource = object.getObjectContent();
// Setting Headers.
return new ResponseEntity(inputStreamResource,headers, HttpStatus.OK);
But this code is not streaming date to browser. I has first downloaded to server and then sent back to browser but requirement is to directly stream to browser without downloading at server.
Any pseudocode or link will help.
Thanks
Instead of calling getObject(), create a signed GET request and send a 302 redirect to the client. The browser will then retrieve the object directly from Amazon. In case you aren't already using it, the jets3t library makes dealing with S3 signatures much simpler.

Graph API in SSO is not working in Azure AD

I am trying to develop a Java web application with SSO by following this azure tutorial. I created an account in Azure and created an AD. Developed and deployed the code in Tomcat. When I try to access the page, I am getting the following error
Exception - java.io.IOException: Server returned HTTP response code: 403 for URL: https://graph.windows.net/ppceses.onmicrosoft.com/users?api-version=2013-04-05
I do not find enough answers for this error. I changed the api-version to 1.6. Even then it did not work.
MORE ANALYSIS:
After troubleshooting, I found out that the logged-in user info is fetched and is available in Sessions object. It errors out when its trying to read the response and convert into the String object. Following is the calling method where it errors out.
HttpClientHelper.getResponseStringFromConn(conn, true);
Actual method to write the response into String:
public static String getResponseStringFromConn(HttpURLConnection conn, boolean isSuccess) throws IOException {
BufferedReader reader = null;
if (isSuccess) {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
stringBuffer.append(line);
}
return stringBuffer.toString();
}
The actual issue is on the Graphic API where we try to read the response in the String format.
#Anand, According to Microsoft Graph error responses and resource types, the response code 403 means Forbidden below.
Access is denied to the requested resource. The user might not have enough permission.
Please move to the CONFIGURE tab of your application registered in your AAD domain on Azure classic portal, then check whether enable enough permission, please see the figure below.
I got the same error, been struggling with it a few days. What I noticed was that even if I checked ALL permissions for Windows Azure Active Directory I still got the 403. So, I deleted the app in App Registrations and created it again from scratch, generated new application key and readded reply urls. In Required Permissions/Windows Azure Active Directory check:
Sign in and read user profile
Access the directory as the signed-in user
I can now call me/memberOf successfully.
Hope it helps.
The below worked for me.
At the active directory app registrations -> app ->settings->permissions-> enable delegate permissions to read directory data. Save and close the blade. Also Click Grant Permissions and close the blade.
Once the above is done, Log out and Log in back with a fresh token to the application. (Guess the token with prior authorizations will not reflect the latest permission changes and hence the re-login may have worked in my case)

getting blobstore to callback to endpoint method

I am developing an app-engine connected android project using the eclipse plugin. When I upload an image to the blobstore, how do I make it callback an endpoint method? I find great posts here that can be used as reference to understand my question better (if you need to).
using blobstore with google cloud endpoint and android
Saving blobs with Google Endpoint
So really, I want to know how to make the callback url an endpoint method such as saveAnimalData below (I stole from referenced link)
#ApiMethod(name = "saveAnimalData", httpMethod = HttpMethod.POST)
public String saveAnimalData(AnimalData request) throws Exception {
}
You should be able to use
https://appid.appspot.com/_ah/api/apiname/version/saveAnimalData
As your final destination url when calling. blobstoreService.createUrl(destination) .
Just bear in mind that the request here is not your original submission. GAE will first call an internal URL (the one created by the blobstoreservice), store the blob and then call your destination URL so whatever info you send will be lost before reaching your endpoint (eg AnimalData will be null)

uploading png to server with java using POST data

Hi ive been having some trouble trying to transfer a png image to my webserver using java and php Ive tried using FTP but the software that Im scripting for blocks port 21 rendering it useless
I was directed to use form urlencoded data then use a POST request to get it
im completely lost on this topic and could just use some direction apparently file and image hosting sites use the same method to transfer files and images from the users computer to their servers.
maybe just an explanation of whats going on might help so that I can grasp what exactly im trying to do with java and php
Any help would be much appreciated!
I've also been facing the same kind of problem a short time ago.
After some researches, I found out that the HttpComponents library from Apache (http://hc.apache.org/) contains pretty much everything you'll need to build HTTP-POST request in a quite simple way.
Here is a method that will send a POST request with a file to a certain URL:
public static void upload(URL url, File file) throws IOException, URISyntaxException {
HttpClient client = new DefaultHttpClient(); //The client object which will do the upload
HttpPost httpPost = new HttpPost(url.toURI()); //The POST request to send
FileBody fileB = new FileBody(file);
MultipartEntity request = new MultipartEntity(); //The HTTP entity which will holds the different body parts, here the file
request.addPart("file", fileB);
httpPost.setEntity(request);
HttpResponse response = client.execute(httpPost); //Once the upload is complete (successful or not), the client will return a response given by the server
if(response.getStatusLine().getStatusCode()==200) { //If the code contained in this response equals 200, then the upload is successful (and ready to be processed by the php code)
System.out.println("Upload successful !");
}
}
In order to complete the upload, you must have a php code that handle that POST request,
here it is:
<?php
$directory = 'Set here the directory you want the file to be uploaded to';
$filename = basename($_FILES['file']['name']);
if(strrchr($_FILES['file']['name'], '.')=='.png') {//Check if the actual file extension is PNG, otherwise this could lead to a big security breach
if(move_uploaded_file($_FILES['file']['tmp_name'], $directory. $filename)) { //The file is transfered from its temp directory to the directory we want, and the function returns TRUE if successfull
//Do what you want, SQL insert, logs, etc
}
}
?>
The URL object given to the Java method must point to the php code, like http://mysite.com/upload.php and can be build very simply from a String. The file can also be build from a String representing its path.
I didn't take the time to test it properly, but it was build upon proper working solution, so I hope this will help you.

google app engine server reports error but on local server the code works fine

String sourceUrlString="http://maps.googleapis.com/maps/api/geocode/xml?address="+searchWord+"&sensor=true";//searchWord-parameter to be passed
Source source=new Source(new URL(sourceUrlString));
Element alpha=source.getFirstElement("location");
String beta[]=new String[100];
String lat=alpha.getContent().getFirstElement("lat").getContent().toString();
String lng=alpha.getContent().getFirstElement("lng").getContent().toString();
THE error pointed out by google app engine is in the above bold statements it says null pointer exception but on local server it returns the value and the code works fine.
wat are the possible solution to the above problem?and as of what i have come to conclusion is google app engine does not support Http request .is it true?
You need to use URL Fetch service to issue HTTP requests and receive responses:
One example:
import urllib2
url = "http://www.google.com/"
try:
result = urllib2.urlopen(url)
doSomethingWithResult(result)
except urllib2.URLError, e:
handleError(e)

Categories