Java Google Youtube Data API:: Unauthorized - java

I wanted to upload a video on youtube using Java Google Data API. I got the following cod from the Google Data Api documentation to upload a video.The only thing i need to change in this code in Client ID and Porduct key. i am using followinf method to authenticate
YouTubeService service = new YouTubeService(clientID, developer_key);
Client key is my Google Email id , tried with with wasy,
only provided Username e,g. "sampleuser"
or complete Gmail id e.g. "sampleuser#gmail.com" or "smapleuser#googlemail.com"
i got developer key by logging my Google mail id as mentioned "smapleuser#googlemail.com"
but i always got following exception
com.google.gdata.util.AuthenticationException: Unauthorized
at com.google.gdata.client.http.HttpGDataRequest.handleErrorResponse(HttpGDataRequest.java:600)
at com.google.gdata.client.http.GoogleGDataRequest.handleErrorResponse(GoogleGDataRequest.java:563)
at com.google.gdata.client.http.HttpGDataRequest.checkResponse(HttpGDataRequest.java:552)
at com.google.gdata.client.http.HttpGDataRequest.execute(HttpGDataRequest.java:530)
at com.google.gdata.client.http.GoogleGDataRequest.execute(GoogleGDataRequest.java:535)
at com.google.gdata.client.media.MediaService.insert(MediaService.java:400)
at YouTube.videoUpload(YouTube.java:115)
at YouTube.main(YouTube.java:43)
here is my code for video Upload
YouTubeService service = new YouTubeService("sampleuser#gmail.com",
"fakegoogleapplicationidjsuttoshowthatimgivingidhere");
// YouTubeService service = new YouTubeService("My Application");
VideoEntry newEntry = new VideoEntry();
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
mg.setTitle(new MediaTitle());
mg.getTitle().setPlainTextContent("My Test Movie");
mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Autos"));
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("cars");
mg.getKeywords().addKeyword("funny");
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent("My description");
mg.setPrivate(false);
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "mydevtag"));
mg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, "anotherdevtag"));
newEntry.setGeoCoordinates(new GeoRssWhere(37.0,-122.0));
// alternatively, one could specify just a descriptive string
// newEntry.setLocation("Mountain View, CA");
MediaFileSource ms = new MediaFileSource(new File("D:\\maths.mp4")
, "video/quicktime");
newEntry.setMediaSource(ms);
// "http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
String uploadUrl =
"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
try {
VideoEntry createdEntry = service.insert(new URL(uploadUrl), newEntry);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
please help , unable to find solution. thank you so much..looking for response

Try to add
service.setUserCredentials("email_here", "password_here");

Related

How do I create an Alfresco site programmatically from a repository webscript?

I've implemented an Alfresco repository webscript (in Java) to programmatically create a new site.
I notice that there's a SiteService interface which I thought could be used to do this -
SiteInfo site = siteService.createSite("site-dashboard", "mySite",
"mySite", "", SiteVisibility.PUBLIC);
However, this results in the creation of a non-functional site, and although it's visible within the Alfresco Share dashboard, I'm not able to use it.
I then came across this code sample, which is doing exactly what I want. BUT the code includes a section to do authentication, involving sending the user's login and password details to a dologin web service. Don't really want to do this.
But as the user has already logged in via Alfresco Share, they should already be authenticated.
If I call the create-site webscript from my code, as shown in the example (without the initial call to dologin), I'm getting a 401 (unauthorised) return code.
So my question is, how do I tell the create-site webscript about my authentication?
I read about using an authentication ticket here. Is this ticket stored in the session, and if so, how do I access it within my Java code? If I could get the ticket, then this would be sufficient to invoke the create-site webscript.
Update: I've added the alf_ticket parameter as suggested by the comment, but I'm still getting a 401 response.
My current code is:
public NodeRef createServiceChange(String serviceChangeName) {
HttpClient client = new HttpClient();
String ticket = authService.getCurrentTicket();
PostMethod createSitePost = new PostMethod("http://localhost:8081/share/service/modules/create-site");
JSONObject siteObject = new JSONObject();
try {
siteObject.put("shortName", serviceChangeName);
siteObject.put("visiblity", "Public");
siteObject.put("sitePreset", "site-dashboard");
siteObject.put("title", serviceChangeName);
siteObject.put("description", serviceChangeName);
siteObject.put("alf_ticket", ticket);
createSitePost.setRequestHeader("Content-Type", "application/json");
createSitePost.setRequestHeader("Accept", "application/json");
createSitePost.setRequestEntity(new StringRequestEntity(siteObject.toString(), "application/json", "UTF-8"));
int status = client.executeMethod(createSitePost);
System.out.println("create a site script status :: " + status);
if (status == HttpStatus.SC_OK) {
System.out.println("Site created OK");
}
else{
System.out.println("There is error in site creation");
}
} catch (JSONException err) {
err.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So I've managed to successfully create a site, programmatically, and here's what I did:
First, forget about writing a repository (platform) webscript. Creation of sites in Alfresco is done by invoking a Share module, so you'll need to implement either a page, or custom menu item to create a site. I was also getting a lot of problems with authentication, but if you log in to the system via Alfresco Share, and in your Javascript, use the provided Alfresco Ajax request, then authentication shouldn't be a problem.
Here are the components I used:-
Create a Share page to create your site. In the Freemarker template (.ftl) add a form to collect the site details.
Attach a button on the form to the following Javascript function. Note that I cobbled this together from various code fragments on the web, so it could use some cleaning up. But it basically works for me -
function create_site()
{
var sc_form = document.forms.namedItem('sc_form');
var name = sc_form.elements.namedItem('name').value;
var url = Alfresco.constants.URL_CONTEXT + "service/modules/create-site";
Alfresco.util.Ajax.request({
method : Alfresco.util.Ajax.POST,
url : url,
dataObj: {
sitePreset: "site-dashboard",
visibility: "PUBLIC",
title: name,
shortName: name,
description: name
},
requestContentType: Alfresco.util.Ajax.JSON,
successCallback:
{
fn: function(res){
alert("success");
alert(res.responseText);
},
scope: this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayPrompt(
{
title: Alfresco.util.message("message.failure", this.name),
text: "search failed"
});
},
scope: this
}
});
}

java how do I get the latest tweet for a particular user

I would like to get latest tweet from #Citi in java. I thought I should use twitter4j (BUT anything easier would be fine). I cannot tell from the documentation how to supply the "user" i.e. #Citi?
public static void main(String[] args) {
// TODO Auto-generated method stub
Twitter twitter = new TwitterFactory().getInstance();
List<Status> statusList = null;
try {
statusList = twitter.getUserTimeline("#Citi");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Status status : statusList) {
System.out.println(status.toString());
}
}
I tried the above but it crashes on getUserTimeline.
The code must create an instance of ConfigurationBuider and pass in your Twitter API credentials. Add the following.
public static void main(String[] args) {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("Your Cosumer Key")
.setOAuthConsumerSecret("Your Consumer Secret")
.setOAuthAccessToken("Your Access Token")
.setOAuthAccessTokenSecret("Your Access Token Secret");
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<Status> statusList = null;
try {
statusList = twitter.getUserTimeline("#Citi");
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Status status : statusList) {
System.out.println(status.toString());
}
}
A Twitter API account is required to use the Twitter API. Twitter requires this so they can track who is using their API and conduct activities such as rate limiting. To obtain a Twitter API account, first create a Twitter account, then create the API account at this page: https://dev.twitter.com/
have you looked into the provided examples?
http://twitter4j.org/en/code-examples.html
You need to have OAuth credentials configured in your twitter4j.properties
See: http://twitter4j.org/en/configuration.html
Regards
Create application in developer and you'll get consumer keys for the application. These are application specific keys to identify your application. Then you'll have to supply access tokens, which are user specific keys. With the combination of these four, Any application with any user given, you can get its tweets. If you want to get tweets in real time, user Streaming API, otherwise you can get last 20 Tweets with the code you posted.

Error on twitter api 1.1

protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean isSuccess = false;
try {
//Consumer key
String consumerKey = STATICVALUES.consumerKey;
//Consumer secret
String consumerSecret = STATICVALUES.consumerSecret;
twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(consumerKey ,consumerSecret);
AccessToken accessToken = new AccessToken(params[0], params[1]);
twitter.setOAuthAccessToken(accessToken);
twitter.updateStatus(params[2]);
Log.e("TAG", "true");
isSuccess = true;
}
catch (TwitterException e) {
isSuccess = false;
Log.e("TAG", "fail");
e.printStackTrace();
}
return isSuccess;
}
this is my code.
i use twitter4j-2.0.2 core. and i have a error, as you know, error about api 1.1
so i add twitter4j 3.0.3 core, but nothing's change.
i search about twitter api 1.1, but someone just add twitter4j 3.0.3 core, someone need change xml to json.
i write to editbox, and click button, this text send tiwtter.
what can i do? i need help!
Check this out.
https://github.com/vshivam/privly-android/blob/master/src/ly/priv/mobile/TwitterLinkGrabberService.java#L120
Dependencies :
/privly-android/libs/signpost-commonshttp4-1.2.1.2.jar
/privly-android/libs/signpost-core-1.2.1.2.jar
/privly-android/libs/twitter4j-core-3.0.3.jar

Secure WS client with UsernameToken(SOAP security header)

I'm trying to secure my WS client to be able to call the WS.
My code looks like this:
SendSmsService smsService = new SendSmsService();
SendSms sendSMS = smsService.getSendSms();
BindingProvider stub = (BindingProvider)sendSMS;
//Override endpoint with local copy of wsdl.
String URL ="";//here is the wsdl url
Map<String,Object> requestContext = stub.getRequestContext();
requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, URL);
//Set usernametoken
URL fileURL = loader.getResource("client-config.xml");
File file = new File(fileURL.getFile());
FileInputStream clientConfig = null;
try {
clientConfig = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
XWSSecurityConfiguration config = null;
try {
config = SecurityConfigurationFactory.newXWSSecurityConfiguration(clientConfig);
} catch (Exception e) {
e.printStackTrace();
log.warn("Exception: "+e.getMessage());
}
requestContext.put(XWSSecurityConfiguration.MESSAGE_SECURITY_CONFIGURATION, config);
//Invoke the web service
String requestId = null;
try {
requestId = sendSMS.sendSms(addresses, senderName, charging, message, receiptRequest);
} catch (PolicyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and the config file looks like this:
<xwss:JAXRPCSecurity xmlns:xwss="http://java.sun.com/xml/ns/xwss/config" optimize="true">
<xwss:Service>
<xwss:SecurityConfiguration dumpMessages="true"
xmlns:xwss="http://java.sun.com/xml/ns/xwss/config">
<xwss:UsernameToken name="username" password="password>
</xwss:SecurityConfiguration>
</xwss:Service>
<xwss:SecurityEnvironmentHandler>
util.SecurityEnvironmentHandler
</xwss:SecurityEnvironmentHandler>
</xwss:JAXRPCSecurity>
The SecurityEnviromentHandler is a dummy class that implements javax.security.auth.callback.CallbackHandler.
Authentication must be in compliance with Oasis Web Services Security Username Token Profile 1.0.
But I'm constantly getting "Security header not valid" error.
Where am I going wrong, can anyone tell me.
I used wsimport(JAX_WS 2.1 to generate classes for my client)
Note:Only thing I know about this WS is WSDL URL and user&pass for authentication
SOLUTION
I solved the problem. The thing that was going wrong is that client-config.xml file cause I didn't know how to set it properly. I ran into this example and used it:
http://www.javadb.com/using-a-message-handler-to-alter-the-soap-header-in-a-web-service-client
Just copied those 2 classes on the link into my projects structure and called them, something like this:
SendSmsService smsService = new SendSmsService();
HeaderHandlerResolver handlerResolver = new HeaderHandlerResolver();
smsService.setHandlerResolver(handlerResolver);
SendSms sendSMS = smsService.getSendSms();
Now it works perfectly!

Using the content handler API (JSR 211) to open applications

I want to be able to launch native and J2ME applications through my application using the content handler API (JSR 211) on a Nokia 6212.
At the moment, I am unable to do so, as it always states that there is "No Content Handler Found" and throws a javax.microedition.content.ContentHandlerException.
At the moment, I am trying to get the phone to launch its browser and go to a certain website, just to test that I can use the framework. I have tried many different Invocation objects:
//throw exceptions
new Invocation("http://www.somesite.com/index.html",
"application/internet-shortcut");
new Invocation("http://www.google.co.uk","text/html");
// a long shot, I know
new Invocation("http://www.somesite.com/text.txt","text/plain");
// massive long shot
new Invocation("http://www.google.co.uk","application/browser");
//appears to download the link and content (and definitely does in the Nokia
// emulator) and then throws an exception
new Invocation("http://www.google.co.uk");
new Invocation("http://www.somesite.com/index.html");
Below is the code that I have been using, please bear in mind the parameters often changed to generate the different Invocation objects.
/*
* Invokes an application using the Content Handler API
*/
public void doInvoke(String url, String mime, String payload){
Registry register = Registry.getRegistry(this.getClass().getName());
Invocation invoke = new Invocation(url, mime, null, false,
ContentHandler.ACTION_OPEN);
boolean mustQuit = false;
try {
mustQuit = register.invoke(invoke);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (ContentHandlerException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(mustQuit){
this.quit();
}
}
Try this:
Registry register = Registry.getRegistry(this.getClass().getName());
You must call Registry.getRegistry for the MIDlet inheritor. Just use your MIDlet for getting the class name.

Categories