I have a written a program that takes in user input, but now I want to be able to save that input by editing a Google spreadsheet every time a user submits the form. So basically, the Google spreadsheet is constantly being updated.
Can anyone provide a tutorial on how I might be able to achieve this? I'm writing in Java using Eclipse, so which plug-ins would I need?
I have already tried using some of the sample code provided in the Google Spreadsheets API (adding a list row section), but I can't seem to get it to work.
import com.google.gdata.client.spreadsheet.*;
import com.google.gdata.data.spreadsheet.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.*;
import java.util.*;
public class MySpreadsheetIntegration {
public static void main(String[] args)
throws AuthenticationException, MalformedURLException, IOException, ServiceException {
SpreadsheetService service =
new SpreadsheetService("MySpreadsheetIntegration-v1");
// TODO: Authorize the service object for a specific user (see other sections)
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://docs.google.com/spreadsheets/d/1OcDp1IZ4iuvyhndtrZ3OOMHZNSEt7XTaaTrhEkNPnN4/edit#gid=0");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL,
SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
if (spreadsheets.size() == 0) {
// TODO: There were no spreadsheets, act accordingly.
}
// TODO: Choose a spreadsheet more intelligently based on your
// app's needs.
SpreadsheetEntry spreadsheet = spreadsheets.get(0);
System.out.println(spreadsheet.getTitle().getPlainText());
// Get the first worksheet of the first spreadsheet.
// TODO: Choose a worksheet more intelligently based on your
// app's needs.
WorksheetFeed worksheetFeed = service.getFeed(
spreadsheet.getWorksheetFeedUrl(), WorksheetFeed.class);
List<WorksheetEntry> worksheets = worksheetFeed.getEntries();
WorksheetEntry worksheet = worksheets.get(0);
// Fetch the list feed of the worksheet.
URL listFeedUrl = worksheet.getListFeedUrl();
ListFeed listFeed = service.getFeed(listFeedUrl, ListFeed.class);
// Create a local representation of the new row.
ListEntry row = new ListEntry();
row.getCustomElements().setValueLocal("firstname", "Joe");
row.getCustomElements().setValueLocal("lastname", "Smith");
row.getCustomElements().setValueLocal("age", "26");
row.getCustomElements().setValueLocal("height", "176");
// Send the new row to the API for insertion.
row = service.insert(listFeedUrl, row);
}
}
seem to be very late but surely this is going to help others! The problem is in your SPREADSHEET_FEED_URL and authentication of SpreadSheetService instance because the official SpreadSheets Api has not shared detailed explaination regarding that.You need to get an authentication token and set it on SpreadSheetService Instance like below to get it work:
private void getAuthenticationToken(Activity activity, String accountName){
//Scopes used to get access to google docs and spreadsheets present in the drive
String SCOPE1 = "https://spreadsheets.google.com/feeds";
String SCOPE2 = "https://docs.google.com/feeds";
String scope = "oauth2:" + SCOPE1 + " " + SCOPE2;
String authenticationToken = null;
try {
accessToken= GoogleAuthUtil.getToken(activity, accountName, scope);
}
catch (UserRecoverableAuthException exception){
//For first time, user has to give this permission explicitly
Intent recoveryIntent = exception.getIntent();
startActivityForResult(recoveryIntent, RECOVERY_REQUEST_CODE);
}catch (IOException e) {
e.printStackTrace();
} catch (GoogleAuthException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST_CODE){
if(resultCode == RESULT_OK){
if(data != null){
String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null && !accountName.equals("")){
//To be called only for the first time after the permission is given
getAuthenticationToken(activity, accountName);
}
}else {
Utility.showSnackBar(linearLayout, Constants.INTENT_DATA_NULL);
}
}
}
}
And finally below code to get all spreadsheets in an email account:
public class MySpreadsheetIntegration {
public void getSpreadSheetEntries()
throws AuthenticationException, MalformedURLException, IOException, ServiceException {
SpreadsheetService service =
new SpreadsheetService("MySpreadsheetIntegration-v1");
service = new SpreadsheetService(applicationName);
service .setProtocolVersion(SpreadsheetService.Versions.V3);
service .setAuthSubToken(accessToken);
// Define the URL to request. This should never change.
URL SPREADSHEET_FEED_URL = new URL(
"https://spreadsheets.google.com/feeds/spreadsheets/private/full");
// Make a request to the API and get all spreadsheets.
SpreadsheetFeed feed = service.getFeed(SPREADSHEET_FEED_URL, SpreadsheetFeed.class);
List<SpreadsheetEntry> spreadsheets = feed.getEntries();
// Iterate through all of the spreadsheets returned
for (SpreadsheetEntry spreadsheet : spreadsheets) {
// Print the title of this spreadsheet to the screen
System.out.println(spreadsheet.getTitle().getPlainText());
}
}
}
Related
I am using ex3ndr for creating a telegram client. now i want to send a message witch has a photo and a caption or description. I send photo using this code snippet:
private static void sendMedia(PeerState peerState, String fileName) {
TLAbsInputPeer inputPeer = peerState.isUser() ? new TLInputPeerContact(peerState.getId()) : new TLInputPeerChat(peerState.getId());
int task = api.getUploader().requestTask(fileName, null);
api.getUploader().waitForTask(task);
int resultState = api.getUploader().getTaskState(task);
Uploader.UploadResult result = api.getUploader().getUploadResult(task);
TLAbsInputFile inputFile;
if (result.isUsedBigFile()) {
inputFile = new TLInputFileBig(result.getFileId(), result.getPartsCount(), "file.jpg");
} else {
inputFile = new TLInputFile(result.getFileId(), result.getPartsCount(), "file.jpg", result.getHash());
}
try {
TLAbsStatedMessage res = api.doRpcCall(new TLRequestMessagesSendMedia(inputPeer, new TLInputMediaUploadedPhoto(inputFile), rnd.nextInt()), 30000);
res.toString();
} catch (IOException e) {
e.printStackTrace();
}
}
but I donot know how can add caption to this photo?(this code snippet is a sample from this url: ex3ndr sample
)
ex3ndr library only support layer 12 of Telegram API where sendMedia method doesn't support captions in photos. That's means this library is not able to send captions with photos, the layer should be updated before being able of doing so (and the repository seems to be abandoned).
I am using the Youtube API v3 for the first time, to receive all my videos from my youtube channel in my Java Web-application. But I like to categorize them by special categories.
What I do is, that I got my webpage and I like to display a categorized list by videos from my channel. I use a public key to identify my application.
The idea I have, is to set tags for the videos, query them and to identify the category by that special tag.
The question is, is it possible to query all the videos from my channel by a tag?
Something like I use a QueryTerm that filters by that tag and makes me receive the videos by that tag.
The code to receive the videos looks like that at the moment.
// Create the youtube object
YouTube youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException{}}).setApplicationName("MyApp").build();
// Initialize the search
YouTube.Search.List search = null;
try
{
search = youtube.search().list("id,snippet");
}
catch(IOException e1)
{
throw new PipeletExecutionException("Failure during sending youtube search request");
}
// Set API-Key
search.setKey(cfg_apiKey);
search.setChannelId(cfg_channelId);
// Set Request Query
// search.setQ(queryTerm);
// search.type("playlist"); oder search.type("channel");
search.setType("playlist");
// Set Fields, filters onle the filds that are defined
search.setFields("items(id/videoId,snippet(title,description,thumbnails))");
// Call the API and consume the results
SearchListResponse searchResponse = null;
// List<SearchResult> searchResultList = searchResponse.getItems();
try
{
searchResponse = search.execute();
System.out.println(searchResponse.toPrettyString());
}
catch(IOException e)
{
throw new PipeletExecutionException("Failure during sending youtube search request");
}
dict.put(DN_YOUTUBE_LISTS, searchResponse);
I just started using YouTube API for Java and I'm having a tough time trying to figure out why things don't work since exception/stack trace is no where to be found. What I'm trying to do is to get list of videos uploaded by current user.
GoogleTokenResponse tokenFromExchange = new GoogleTokenResponse();
tokenFromExchange.setAccessToken(accessToken);
GoogleCredential credential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(TRANSPORT).build();
credential.setFromTokenResponse(tokenFromExchange);
YouTube.Channels.List channelRequest = youtube.channels().list("contentDetails");
channelRequest.setMine(true);
channelRequest.setFields("items/contentDetails,nextPageToken,pageInfo");
ChannelListResponse channelResult = channelRequest.execute();
I don't see anything wrong with this code and also tried removing multiple things, but still not able to get it to work. Please let me know if you have run into a similar issue. The version of client library I'm using is v3-rev110-1.18.0-rc.
YouTube API has some working code and you can use it.
public static YouTubeService service;
public static String USER_FEED = "http://gdata.youtube.com/feeds/api/users/";
public static String CLIENT_ID = "...";
public static String DEVELOPER_KEY = "...";
public static int getVideoCountOf(String uploader) {
try {
service = new YouTubeService(CLIENT_ID, DEVELOPER_KEY);
String uploader = "UCK-H1e0S8jg-8qoqQ5N8jvw"; // sample user
String feedUrl = USER_FEED + uploader + "/uploads";
VideoFeed videoFeed = service.getFeed(new URL(feedUrl), VideoFeed.class);
return videoFeed.getTotalResults();
} catch (Exception ex) {
Logger.getLogger(YouTubeCore.class.getName()).log(Level.SEVERE, null, ex);
}
return 0;
}
This simple give you the number of videos a user has. You can read through videoFeed using printEntireVideoFeed prepared on their api page.
I am using Dailymotion cloud in my android app to upload videos to server.
i want to display progress bar while uploading but i don't know how can i get byte by byte value to update progress bar.
This is dailymotion cloud api link Dailymotion cloud api link
While searching on internet i found this progress bar in java but i don't know how can i implement into this method of dailymotion api.
I am using async task to display progress bar
Here is android code for uploading
try
{
CloudKey cloud = new CloudKey(user_id, api_key);
File f = new File(selectedVideoPath);
String media_id = cloud.mediaCreate(f);
System.out.println(media_id);
Log.d("Testing", "media_id is"+media_id);
}
And here is Dailymotion API's Cloud.class mediacreate() in which i want to display progress bar .. any idea
public String mediaCreate(File f) throws Exception
{
return this.mediaCreate(f, null, null);
}
public String mediaCreate(File f, DCArray assets_names, DCObject meta) throws Exception
{
String upload_url = this.fileUpload();
PostMethod filePost = null;
int status;
try
{
filePost = new PostMethod(upload_url);
Part[] parts = {
new FilePart("file", f)
};
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK)
{
ObjectMapper mapper = new ObjectMapper();
DCObject json_response = DCObject.create(mapper.readValue(filePost.getResponseBodyAsString(), Map.class));
return this.mediaCreate(json_response.pull("url"), assets_names, meta);
}
else
{
throw new DCException("Upload failed.");
}
}
catch (Exception e)
{
throw new DCException("Upload failed: " + e.getMessage());
}
finally
{
if (filePost != null)
{
filePost.releaseConnection();
}
}
}
I'm not able to find any api support for doing this with the DailyMotion class that you mentioned.
If you can edit the source of that library, then you could try extending MultipartRequestEntity and add support for callbacks for progress, and then just plug in that new class in the DailyMotion code in the mediaCreate method:
filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
.. replace MultipartRequestEntity by the new one, eg. ExtendedMultipartRequestEntity.
See the answer by Tuler and others at File Upload with Java (with progress bar) to see how to do it.
Once you are getting updates via the callback, then you can hook up progress bar.
I would like to be able to make a request to Twitter with Pentaho's REST client request however this software does not have any concept of oauth. I found this (Implement OAuth in Java)neat java class that I would like to implement with Pentaho's java class tranformation but I am so new to Pentaho this task will be very difficult. I am hoping someone can help me out with this....
I found this great twitter java library called twitter4J and imported the core classes into the pentaho directory pentaho/design-tools/data-integration/libext and wrote the below custom user java class.
// NO COLLECTION TYPE SAFETY ALLOWED, MUST CAST ALL OBJECTS
import twitter4j.*;
import twitter4j.auth.*;
import twitter4j.conf.*;
//import other libs here
//put your vars here
// Variables
private Twitter twitter = null;
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException
{
Object[] r = getRow();
if (r==null)
{
setOutputDone();
return false;
}
if (first) {
first=false;
paging = new Paging();
paging.setCount(100);
}
oauth_user_key = get(Fields.In, "oauth_user_key").getString(r);
oauth_user_secret = get(Fields.In, "oauth_user_secret").getString(r);
consumer_key = get(Fields.In, "consumer_key").getString(r);
consumer_secret = get(Fields.In, "consumer_secret").getString(r);
//wierd long/string thing here (pentho compiles java wierd)
user_id = get(Fields.In, "source_user_id").getInteger(r);
Long user = user_id;
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setIncludeEntitiesEnabled(true)
.setOAuthConsumerKey(consumer_key)
.setOAuthConsumerSecret(consumer_secret)
.setOAuthAccessToken(oauth_user_key)
.setOAuthAccessTokenSecret(oauth_user_secret);
twitter = new TwitterFactory(cb.build()).getInstance();
try {
//be creative with twitter4j here and output rows with results (may require a loop)
} catch (TwitterException e){
logDebug(e.getMessage());
return true;
}
logBasic("twitter collect done" );
return true;
}