I am new to WebAPIs, and I was asked to acquire the longitude and latitude of a specific location with the help of a certain website's APIs. (website deleted), and I was provided with an asset key as well.
I think my question here is, how do I import this API into my program in Java?
Here's a simple example of Assets query from that page using the provided demo key:
EXAMPLE QUERY
https://api.nasa.gov/planetary/earth/assets?lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY
[this is in Java 6, modify to suit your Java version]
import java.io.BufferedReader;
import java.lang.StringBuilder;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.net.URL;
import java.net.URLConnection;
import java.io.IOException;
public class NasaRestAPIExample {
public static void main(String[] args) throws IOException {
String query = "lon=100.75&lat=1.5&begin=2014-02-01&api_key=DEMO_KEY";
URLConnection connection = new URL("https://api.nasa.gov/planetary/earth/assets?" + query).openConnection();
connection.connect();
BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream(), Charset.forName("UTF-8")));
StringBuilder sb = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
sb.append(line);
}
System.out.println(sb.toString());
}
}
output:
{"count": 61, "results": [{"date": "2014-02-04T03:30:01", "id": "LC8_L1T_TOA/LC81270592014035LGN00"}, ...
Related
import java.net.*;
import java.io.*;
import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class UrlReaderTest {
public static void main(String[] args) throws Exception {
URL url = new URL("https://www.amazon.com/");
String s = null;
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new
InputStreamReader(url.openStream()));
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
}
in.close();
} catch (IOException e) {
System.err.println("Error");
}
s = contentBuilder.toString();
Document document = Jsoup.parse(s);
System.out.println(document.text());
}
}
What i am getting has mainly symbols like these: Η1?0 Π??0ή=tθ Jr?/β#Q? l?r{ΪεI/ ΉΟ~νJ?j?Ά-??ΙiLs?YdHλ²ύ?α?η?ογV"ηw[:?0??νSQψyθ?*²?γpI? ??²ρνl???2JμΚ?ΣS?Αl4ςRΛ\KR545υ?SK
Is there anything i can do to transform that in a form that i can use?
I can't find something specific online.
Edit: What i want specificly is to decrypt that information. What i want for example is to be able to take the text from an event page from facebook search it to find the keywords i want and use those somewhere else.
As #t.m.adam noted in his comment, the problem is that the response from stream is gzipped (compressed). So, if you want to read it from the URL stream, you need to pass it through a GZIPInputStream before InputStreamReader (see this answer). Alternatively, as #t.m.adam suggests, you can use Jsoup's built-in connect() method:
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class UrlReaderTest {
public static void main(String[] args) {
System.out.println(System.getProperty("java.classpath"));
try {
Document doc = Jsoup.connect("https://www.amazon.com").get();
System.out.print(doc.text());
}
catch (IOException e) {
System.err.println("Error");
}
}
}
I'm a java beginner and I'm doing a small project about dictionary, now I want to save word and translate mean in file, because my native language often have space like chicken will be con gà so, I must use other way, not by space, but I really don't know how to do that, a word and it translation in one line, separate by "tab", mean multi space like chicken con gà now I want to get 2 words and store it in my array of Words which I created before, so I want to do something like
w1=word1inline;
w2=word2inline;
Word(word1inline,word2inline);(this is a member of array);
please help me, thanks a lot, I just know how to read line from file text, and use split to get word but I am not sure how to read by multi space.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class docfile {
public static void main(String[] args)
{
String readLine;
ArrayList<String>str=new ArrayList<>(String);
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((readLine = b.readLine()) != null) {
str.add()=readLine.split(" ");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you stick to using tabs as a separator, this should work:
package Application;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Application {
public static void main(String[] args) {
String line;
ArrayList<String> str = new ArrayList<>();
try {
File file = new File("text.txt");
BufferedReader b = new BufferedReader(new FileReader(file));
while ((line = b.readLine()) != null) {
for (String s : line.split("\t")) {
str.add(s);
}
}
str.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why not just use a properties file?
dict.properties:
chicken=con gá
Dict.java:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;
public class Dict {
public static void main(String[] args) throws IOException {
Properties dict = new Properties();
dict.load(Files.newBufferedReader(Paths.get("dict.properties")));
System.out.println(dict.getProperty("chicken"));
}
}
Output:
con gá
If your line is like this chicken con gà you can use indexof() method to find the first space in the string.
Then you can substring each word by using substring() method.
readLine = b.readLine();
ArrayList<String>str=new ArrayList<>();
int i = readLine.indexOf(' ');
String firstWord = readLine.substring(0, i);
String secondWord = readLine.substring(i+1, readLine.length());
str.add(firstWord);
str.add(secondWord);
I am testing a rest API and I want to build a simple java program to do the following (I am new to java). I export in a file multiple JSON responses from JMeter and then I want them to be checked for all the mandatory response parameters. I want the program to read the paramters from a CSV file and to check for each of them everywhere in the JSONs (they are more than 600). Currently I am using this snippet but it just compares what are the differences between the two files:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public Test(){
System.out.println("Test.Test()");
}
public static void main(String[] args) throws Exception {
BufferedReader br1 = null;
BufferedReader br2 = null;
String sCurrentLine;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
br1 = new BufferedReader(new FileReader("C:\\Users\\text1.txt"));
br2 = new BufferedReader(new FileReader("C:\\Users\\text2.txt"));
while ((sCurrentLine = br1.readLine()) != null) {
list1.add(sCurrentLine);
}
while ((sCurrentLine = br2.readLine()) != null) {
list2.add(sCurrentLine);
}
List<String> tmpList = new ArrayList<String>(list1);
tmpList.removeAll(list2);
System.out.println("content from SavedResponses.txt which is not there in DBResponses.txt");
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i)); //content from test.txt which is not there in test2.txt
}
System.out.println("content from DBResponses.txt which is not there in SavedResponses.txt");
tmpList = list2;
tmpList.removeAll(list1);
for(int i=0;i<tmpList.size();i++){
System.out.println(tmpList.get(i)); //content from test2.txt which is not there in test.txt
}
}
}
Any help is highly appreciated!
I want to add some code to the C source code, so I try to use ASTRewrite.
My Github project: cdt-rewrite
My code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTIfStatement;
import org.eclipse.cdt.core.dom.ast.IASTStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
import org.eclipse.cdt.core.dom.ast.gnu.c.GCCLanguage;
import org.eclipse.cdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.cdt.core.model.ILanguage;
import org.eclipse.cdt.core.parser.DefaultLogService;
import org.eclipse.cdt.core.parser.FileContent;
import org.eclipse.cdt.core.parser.IncludeFileContentProvider;
import org.eclipse.cdt.core.parser.ScannerInfo;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.ltk.core.refactoring.Change;
public class Main {
public static void main(String[] args) throws Exception {
IASTTranslationUnit u = getTranslationUnit(new File("D:/test.c"));
System.out.println(u.getRawSignature());
ASTRewrite rw = ASTRewrite.create(u);
u.accept(new ASTVisitor(true) {
#Override
public int visit(IASTStatement stm) {
if (stm instanceof IASTIfStatement){
rw.insertBefore(stm.getParent(), stm,
rw.createLiteralNode("callTo(1,2,3);"), null);
}
return PROCESS_CONTINUE;
}
});
Change c = rw.rewriteAST();
c.perform(new NullProgressMonitor());
//String changedSource = someHowGetCode(c);
}
static IASTTranslationUnit getTranslationUnit(File source) throws Exception{
FileContent reader = FileContent.create(
source.getAbsolutePath(),
getContentFile(source).toCharArray());
return GCCLanguage.getDefault().getASTTranslationUnit(
reader,
new ScannerInfo(),
IncludeFileContentProvider.getSavedFilesProvider(),
null,
ILanguage.OPTION_IS_SOURCE_UNIT,
new DefaultLogService());
}
static String getContentFile(File file) throws IOException {
StringBuilder content = new StringBuilder();
String line;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file)))) {
while ((line = br.readLine()) != null)
content.append(line).append('\n');
}
return content.toString();
}
}
But when I run this code, an exception is occur:
int test(int x){
if (x < 0)
return 0;
int i, s = 0;
for (i = 1; i < x; i++)
s = s + i;
return s;
}
Exception in thread "main" java.lang.NullPointerException
at org.eclipse.cdt.internal.formatter.ChangeFormatter.formatChangedCode(ChangeFormatter.java:92)
at org.eclipse.cdt.internal.core.dom.rewrite.changegenerator.ChangeGenerator.generateChange(ChangeGenerator.java:117)
at org.eclipse.cdt.internal.core.dom.rewrite.changegenerator.ChangeGenerator.generateChange(ChangeGenerator.java:104)
at org.eclipse.cdt.internal.core.dom.rewrite.ASTRewriteAnalyzer.rewriteAST(ASTRewriteAnalyzer.java:26)
at org.eclipse.cdt.core.dom.rewrite.ASTRewrite.rewriteAST(ASTRewrite.java:212)
at Main.main(Main.java:44)
Does anyone know how to solve this exception?
Thanks you
AFAIK This code is dependent on running in OSGi, but you appear to have made a Java project with a main. You need to a plug-in project with a MANIFEST.MF that references what you require.
You can create an Eclipse Application if you want to control the entry point to the program. If you want to graduate this rewriting code to be part of Eclipse/CDT, then different entry points such as an Eclipse Command tied to a menu/toolbar/key combination may be what you want.
Hi, I am totally new in java.
This is my java code:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedReader;
public class readw {
public static void main(String[] args) throws IOException {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\run\\input.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} finally {
reader.close();
}
String[] array = lines.toArray();
}
}
When I am trying to compile it I got this type of error:
line 8: can not find symbol List (L)and ArrayList(A)
I am trying to get content of my text file and want to set in to as a array.
Add
import java.util.ArrayList;
import java.util.List;
yes its work now i want to see the array result. how?
With
System.out.println(lines);
You need to import all the classes you use.
import java.util.ArrayList;
import java.util.List;