Dropbox Core API JAVA Authorization Code - java

Using the dropbox core api tutorial I am able to upload a file.
However, my question is an exact replica of this SO post--- That is, once I have my authorization code and comment out the user auth lines so that I dont have to manually re-authorize approval every time I use dropbox I get the following errors:
Exception in thread "main" com.dropbox.core.DbxException$BadRequest: {"error_description": "code has already been used", "error": "invalid_grant"}
OR
Exception in thread "main" com.dropbox.core.DbxException$BadRequest: {"error_description": "code has expired (within the last hour)", "error": "invalid_grant"}
I am positive I have the correct authorization code.
I hope that I'm missing something, else whats the point of an API if you have to induce manual intervention every time you use it?
Edit: My Exact Code (keys have been scrambled)
import com.dropbox.core.*;
import java.io.*;
import java.util.Locale;
public class DropboxUpload {
public static void main(String[] args) throws IOException, DbxException {
// Get your app key and secret from the Dropbox developers website.
final String APP_KEY = "2po9b49whx74h67";
final String APP_SECRET = "m98f734hnr92kmh";
DbxAppInfo appInfo = new DbxAppInfo(APP_KEY, APP_SECRET);
DbxRequestConfig config = new DbxRequestConfig("JavaTutorial/1.0",
Locale.getDefault().toString());
DbxWebAuthNoRedirect webAuth = new DbxWebAuthNoRedirect(config, appInfo);
// Have the user sign in and authorize your app.
//String authorizeUrl = webAuth.start();
//System.out.println("1. Go to: " + authorizeUrl);
//System.out.println("2. Click \"Allow\" (you might have to log in first)");
//System.out.println("3. Copy the authorization code.");
//String code = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
DbxAuthFinish authFinish = webAuth.finish("VtwxzitUoI8DDDLx0PlLut5Gjpw3");
String accessToken = authFinish.accessToken;
DbxClient client = new DbxClient(config, accessToken);
System.out.println("Linked account: " + client.getAccountInfo().displayName);
File inputFile = new File("/home/dropboxuser/Documents/test.txt");
FileInputStream inputStream = new FileInputStream(inputFile);
try {
DbxEntry.File uploadedFile = client.uploadFile("/Public/test.txt",
DbxWriteMode.add(), inputFile.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
} finally {
inputStream.close();
}
DbxEntry.WithChildren listing = client.getMetadataWithChildren("/");
System.out.println("Files in the root path:");
for (DbxEntry child : listing.children) {
System.out.println(" " + child.name + ": " + child.toString());
}
FileOutputStream outputStream = new FileOutputStream("test.txt");
try {
DbxEntry.File downloadedFile = client.getFile("/Public/test.txt", null,
outputStream);
System.out.println("Metadata: " + downloadedFile.toString());
} finally {
outputStream.close();
}
}
}

You should be storing and reusing the access token, not the authorization code.
So after doing this once:
String accessToken = authFinish.accessToken;
You should just replace the whole thing with
String accessToken = "<the one you already got>";
BTW, if you just need an access token for your own account, you can generate one with the click of a button! See https://www.dropbox.com/developers/blog/94/generate-an-access-token-for-your-own-account.

Related

How to get response from http and unsecured https site from Codename one's ConnectionRequest ? issue in http and https in Android 10 (In Google Pixel)

I am new to Codenameone , I am having strange issue in Codenameone's ConnectionRequest API while fetching response from https site in google pixel device in which anroid 10 is installed.
fetching from https site is working fine.
However in the simulator it is fine and also with the other device that has android less than version 10.
what could be the solution for this OR am i doing somthing worng?
Here is my code and error i am getting in device
First Tried :
TextArea resultTextArea = new TextArea();
Button download = new Button("RUN");
download.addActionListener((e) -> {
ConnectionRequest cr = new ConnectionRequest(url, false);
SliderBridge.bindProgress(cr, progress);
NetworkManager.getInstance().addToQueueAndWait(cr);
if (cr.getResponseCode() == 200) {
String resultString = "";
try {
byte[] initialArray = cr.getResponseData();
resultString = new String(initialArray);
resultTextArea.setText(resultString);
} catch (Exception eee) {
resultString = "Error => " + resultString + eee.getMessage();
}
System.out.println(resultString);
}
});
Second Try: where url = http://192.168.2.100:8084/semms-webservice/rest/device/test/users
public void testURLConnectionResponse(String url) {
ConnectionRequest request = new ConnectionRequest();
request.setContentType("application/json");
request.setUrl(url);
request.setHttpMethod("GET");
TextArea resultTextArea = new TextArea();
String result = "";
result = "RESPONSE CODE :- " + request.getResponseCode() + " --- ";
Response<String> resultx = Rest.put(url).getAsString();
result += resultx.getResponseData();
resultTextArea.setText(result);
Form hi = new Form("Test Connection Response", new BoxLayout(BoxLayout.Y_AXIS));
Button mainFormButton = new Button("Back To Main Form");
mainFormButton.addActionListener((e) -> mainForm());
mainFormButton.setRippleEffect(true);
hi.add(mainFormButton);
hi.show();
// request will be handled asynchronously
NetworkManager.getInstance().addToQueue(request);
}
enter code here
I'm assuming this works in the simulator and fails on the device?
There are multiple reasons this can happen but in this case it looks like a subnet IP address. You're trying to connect to an internal company URL from a device which is probably on the operator network. Try connecting to the URL via the browser and see if it's reachable by the device.
As a workaround you can connect to the company internal wifi and see if the server is reachable.

How to get spreadsheets from a specific Google Drive folder?

The code provided in this tutorial (snippet given below) retrieves a list of all the spreadsheets for the authenticated user.
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://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());
}
}
}
But I don't want to get all the spreadsheets. I only want to get those spreadsheets that are in a particular folder (if the folder exists, otherwise terminate the program). Is it possible using this API? If yes, how?
As far as my understanding goes, the SpreadsheetFeed has to be changed. But I didn't get any example snippet against it.
I worked out the solution as follows:
First, get the fileId of that particular folder. Use setQ() to pass query checking for folder and folder name. The following snippet will be useful:
result = driveService.files().list()
.setQ("mimeType='application/vnd.google-apps.folder'
AND title='" + folderName + "'")
.setPageToken(pageToken)
.execute();
Then, get the list of files in that particular folder. I found it from this tutorial. Snippet is as follows:
private static void printFilesInFolder(Drive service, String folderId) throws IOException {
Children.List request = service.children().list(folderId);
do {
try {
ChildList children = request.execute();
for (ChildReference child : children.getItems()) {
System.out.println("File Id: " + child.getId());
}
request.setPageToken(children.getNextPageToken());
} catch (IOException e) {
System.out.println("An error occurred: " + e);
request.setPageToken(null);
}
} while (request.getPageToken() != null &&
request.getPageToken().length() > 0);
}
Lastly, check for spreadsheets and get worksheet feeds for them. The following snippet might help.
URL WORKSHEET_FEED_URL = new URL("https://spreadsheets.google.com/feeds/worksheets/" + fileId + "/private/full");
WorksheetFeed feed = service.getFeed(WORKSHEET_FEED_URL, WorksheetFeed.class);
worksheets = feed.getEntries();

is it possible to upload images from my web application to instagram?

is it possible to upload images from my web application to instagram ???
if yes then how ??
i have tried this bellow code. but i dont khnow how to upload image ??
String clientId = "XXXXXx";
String clientSecret = "XXXXXXX";
String callbackUrl = "http://xxxx.com/InstaGram/Auth";
InstagramService service = new InstagramAuthService().apiKey(clientId).apiSecret(clientSecret).callback(callbackUrl).scope("comments").build();
String authorizationUrl = service.getAuthorizationUrl(EMPTY_TOKEN);
System.out.println("** Instagram Authorization ** \n\n");
System.out.println("Copy & Paste the below Authorization URL in your browser...");
System.out.println("Authorization URL : " + authorizationUrl);
Scanner sc = new Scanner(System.in);
String verifierCode;
System.out.print("Your Verifier Code : ");
verifierCode = sc.next();
System.out.println();
Verifier verifier = new Verifier(verifierCode);
Token token = service.getAccessToken(EMPTY_TOKEN, verifier);
System.out.println("Token : " + token.getToken());
String accessToken = "7073519.44e6baf.d44336e2e99741f6a5bed94b26f1699c";
Token secretToken = new Token(accessToken, null);
Instagram instagram = new Instagram(secretToken);
UserInfo userInfo = instagram.getCurrentUserInfo();
MediaFeed mediaFeed = instagram.getRecentMediaFeed(userInfo.getData().getId());
// MediaFeed mediaFeed = instagram.getUserFeeds();
List<MediaFeedData> mediaList = mediaFeed.getData();
for (MediaFeedData data : mediaList) {
System.out.println("data : " + data.getId());
//instagram.setMediaComments(data.getId(), "Comment was created at " + new Date().toString());
}
System.out.println("***** User Info ******");
System.out.println("Username : " + userInfo.getData());
}
if there is any way then tell me...
plz help me..
Thanx...
There is no way to achive it.
http://instagram.com/developer/endpoints/media/
You can only get media via rest media endpoints.

Saving the first Image from URL

Here's my problem. I have a txt file called "sites.txt" . In these i type random internet sites. My Goal is to save the first image of each site. I tried to filter the Server response by the img tag and it actually works for some sites, but for some not.
The sites where it works the img src starts with http:// ... the sites it doesnt work start with anything else.
I also tried to add the http:// to the img src images which didnt have it, but i still get the same error:
Exception in thread "main" java.net.MalformedURLException: no protocol:
at java.net.URL.<init>(Unknown Source)
My current code is:
public static void main(String[] args) throws IOException{
try {
File file = new File ("sites.txt");
Scanner scanner = new Scanner (file);
String url;
int counter = 0;
while(scanner.hasNext())
{
url=scanner.nextLine();
URL page = new URL(url);
URLConnection yc = page.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine = in.readLine();
while (!inputLine.toLowerCase().contains("img"))inputLine = in.readLine();
in.close();
String[] parts = inputLine.split(" ");
int i=0;
while(!parts[i].contains("src"))i++;
String destinationFile = "image"+(counter++)+".jpg";
saveImage(parts[i].substring(5,parts[i].length()-1), destinationFile);
String tmp=scanner.nextLine();
System.out.println(url);
}
scanner.close();
}
catch (FileNotFoundException e)
{
System.out.println ("File not found!");
System.exit (0);
}
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
// TODO Auto-generated method stub
URL url = new URL(imageUrl);
String fileName = url.getFile();
String destName = fileName.substring(fileName.lastIndexOf("/"));
System.out.println(destName);
InputStream is = url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
byte[] b = new byte[2048];
int length;
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
I also got a tip to use the apache jakarte http client libraries but i got absolutely no idea how i could use those i would appreciate any help.
A URL (a type of URI) requires a scheme in order to be valid. In this case, http.
When you type www.google.com into your browser, the browser is inferring you mean http:// and automatically prepends it for you. Java doesn't do this, hence your exception.
Make sure you always have http://. You can easily fix this using regex:
String fixedUrl = stringUrl.replaceAll("^((?!http://).{7})", "http://$1");
or
if(!stringUrl.startsWith("http://"))
stringUrl = "http://" + stringUrl;
An alternative solution
Simply try with ImageIO that contains static convenience methods for locating ImageReaders and ImageWriters, and performing simple encoding and decoding.
Sample code:
// read a image from the URL
// I used the URL that is your profile pic on StackOverflow
BufferedImage image = ImageIO
.read(new URL(
"https://www.gravatar.com/avatar/3935223a285ab35a1b21f31248f1e721?s=32&d=identicon&r=PG&f=1"));
// save the image
ImageIO.write(image, "jpg", new File("resources/avatar.jpg"));
When you're scraping the site's HTML for image elements and their src attributes, you'll run into several different representations of URLs.
Some examples are:
resource = https://google.com/images/srpr/logo9w.png
resource = google.com/images/srpr/logo9w.png
resource = //google.com/images/srpr/logo9w.png
resource = /images/srpr/logo9w.png
resource = images/srpr/logo9w.png
For the second through fifth ones, you'll need to build the rest of the URL.
The second one may be more difficult to differentiate from the fourth and fifth ones, but I'm sure there are workarounds. The URL Standard leads me to believe you won't see it as often, because I don't think it's technically valid.
The third case is pretty simple. If the resource variable starts with //, then you just need to prepend the protocol/scheme to it. You can do this with the site object you have:
url = site.getProtocol() + ":" + resource
For the fourth and fifth cases, you'll need to prepend the resource with the entire site's URL.
Here's a sample application that uses jsoup to parse the HTML, and a simple utility method to build the resource URL. You're interested in the buildResourceUrl method. Also, it doesn't handle the second case; I'll leave that to you.
import java.io.*;
import java.net.*;
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;
public class SiteScraper {
public static void main(String[] args) throws IOException {
URL site = new URL("https://google.com/");
Document doc = Jsoup.connect(site.toString()).get();
Elements images = doc.select("img");
for (Element image : images) {
String src = image.attr("src");
System.out.println(buildResourceUrl(site, src));
}
}
static URL buildResourceUrl(URL site, String resource)
throws MalformedURLException {
if (!resource.matches("^(http|https|ftp)://.*$")) {
if (resource.startsWith("//")) {
return new URL(site.getProtocol() + ":" + resource);
} else {
return new URL(site.getProtocol() + "://" + site.getHost() + "/"
+ resource.replaceAll("^/", ""));
}
}
return new URL(resource);
}
}
This obviously won't cover everything, but it's a start. You may run into problems when the URL you're trying to access is in a subdirectory of the root of the site (i.e., http://some.place/under/the/rainbow.html). You may even encounter base64 encoded data URI's in the src attribute... It really depends on the individual case and how far you're willing to go.

jcifs.smb.SmbException: The network name cannot be found

The following is my piece of code
SmbFile catalExp = new SmbFile("smb://<Shared machine name>/Project share/Home/4. Folders/planning - Design & Exec/sample.txt",
new NtlmPasswordAuthentication(LoadProp.getShrdDomain(),"user","paswd"));
In this i am getting the error
jcifs.smb.SmbException: The network name cannot be found
at jcifs.smb.SmbTransport.send(SmbTransport.java:753)
at jcifs.smb.SmbSession.sessionSetup(SmbSession.java:140)
at jcifs.smb.SmbSession.send(SmbSession.java:103)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:132)
at jcifs.smb.SmbFile.connect(SmbFile.java:674)
at jcifs.smb.SmbFile.connect0(SmbFile.java:644)
at jcifs.smb.SmbFile.open0(SmbFile.java:700)
at jcifs.smb.SmbFile.createNewFile(SmbFile.java:2027)
Is this anything to do with the user rights to that particular shared folder or am I doing anything wrong
Please advice
I ran into this error message, and it turned out the problem was that my network path was incorrect. You'll want to ensure that the NtlmPasswordAuthentication object is configured correctly, that your network path is correct, and that you've set the jcifs.netbios.wins property correctly, as indicated in the first example on this page.
For example, to load a remote properties file:
final NtlmPasswordAuthentication AUTH = new NtlmPasswordAuthentication("domainname", "username", "password");
Config.setProperty("jcifs.netbios.wins", "10.10.1.1");
Properties props = new Properties();
InputStream in = new SmbFileInputStream(new SmbFile("smb://10.10.1.1:445/rootfolder/path/filename.properties", AUTH));
props.load(in);
(You'll need to add try/catch and input stream closing)
A good way to ensure that all of your parameters are correct is to test logging into and locating the file using a smb/cifs client. For example smbclient on linux/unix:
smbclient -Uusername -p 139 //10.10.1.1/rootfolder
The domain is displayed at the top when you login with smbclient:
Domain=[DOMAINNAME]
..and you can navigate to your file to make sure you've got the path correct.
After running into this issue for almost 1 day i realize that these exception is meaningless
I was just giving wrong path of server side location
Below is the peace of groovy code worked for me
String domain = "domain"
String user = "username"
String pass = "password"
String IP = "xx.yy.zz.aa"
String sharedFolder="//my//path//to//server//";
String path="smb://$IP"+sharedFolder+"test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(domain, user, pass );
SmbFile smbFile = new SmbFile(path,auth);
SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
smbfos.write("testing....and writing to a file".getBytes());
System.out.println("completed ...nice !");
Well I'm getting this error also but only on one device, my code that works on Android 4.04 is
String strprog = "STRING CREATED| "; //debug log string
try {
strprog += "NTLM| ";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("username:password");
strprog += "SMB| ";
SmbFile file = new SmbFile("smb://<pcname>/foldername/filename.txt",auth);
strprog += "EXIST| ";
String there = String.valueOf(file.exists());
strprog += "View| ";
TextView pp;
pp = (TextView) findViewById(R.id.tv);
pp.setText(there);
} catch (Exception e) {
// TODO Auto-generated catch block
strprog += "ERROR! ";
TextView ll;
ll = (TextView) findViewById(R.id.tv);
ll.setText(strprog + e.getStackTrace().toString() + " " + e.getMessage() + " " + e.getLocalizedMessage() );
}
The only difference I see is where you have your NtlmPasswordAuth compared to mine.
But as I stated for some reason this throws null input param on Andriod 2.0 when I dive deeper then smb://host but I hope this helps you out.
I had this problem, and it turned out that I did not see what the share name was that was mapped to my Windows shared drive... So, using Mac OS, I ran:
smbutil view smb://MYUSERNAME#HOSTNAME
After I was prompted for my password, I then was displayed a list of share names (that weren't evident when I looked at this stuff using Windows). Once I found my share name, it was as simple as using that when connecting with JCIFS:
new SmbFile("smb://HOSTNAME/SHARENAME/path/I/was/trying/to/access", auth);

Categories

Resources