I have a WebView and I want to get this WebView's link from another class.
My another class gets this link from JSON data. Would you help me please? I am new at Java :/
Main.java;
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
engine.load("https://www.google.com");
}
});
Reader.java (Link is in here)
public class Readerr {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("https://api.myjson.com/bins/cs3x6");
String Link = json.get("link").toString();
}
}
Related
I need to access some data that it stored in a Json file that is in Resources file. The code compiles in eclipse but when I try to Export and run as JAR file I get this exception:
The location of the Json file is:
I tried to use:
Thread.currentThread().getContextClassLoader()
.getResourceAsStream("AutomationJson.json");
or
Thread.currentThread().getContextClassLoader()
.getResourceAsStream("/AutomationJson.json");
Main(){
InputStream jsonFileStream = getClass().getClassLoader().getResourceAsStream("AutomationJson.json");
String jsonString = readFromJARFile();
jsonData();
}
private void jsonData() {
JsonNode node = null;
try {
node = JsonHelper.parse(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
secondUserName = node.get("secondUserName").asText();
password = node.get("password").asText();
}
public String readFromJARFile() throws IOException {
InputStreamReader isr = new InputStreamReader(jsonFileStream);
BufferedReader br = new BufferedReader(isr);
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
isr.close();
return sb.toString();
}
The Json helper class:
public class JsonHelper {
private static ObjectMapper objectMapper = getDefaultMapper();
static ObjectMapper getDefaultMapper() {
ObjectMapper defaultMapper = new ObjectMapper();
defaultMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return defaultMapper;
}
public static JsonNode parse(String src) throws JsonProcessingException {
return objectMapper.readTree(src);
}
}
I tried using HttpRequestWrapper but it keeps giving me stream closed exception. Below is my HttpRequestWrapper code. I was trying to modify the request body in preHandle method. after modifying the request body I want to send it to the controller. It seems like HandlerInterceptorAdapter been called twice. In the second time it complains that the stream is closed. I've seen post related to this issue but I could not find a solution.
public class RequestWrapper extends HttpServletRequestWrapper {
private final String body;
public RequestWrapper(HttpServletRequest request) throws IOException {
super(request);
StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null;
try {
InputStream inputStream = request.getInputStream();
if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128];
int bytesRead = -1;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead);
}
} else {
stringBuilder.append("");
}
} catch (IOException ex) {
throw ex;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException ex) {
throw ex;
}
}
}
body = stringBuilder.toString();
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
ServletInputStream servletInputStream = new ServletInputStream() {
#Override public boolean isFinished() {
return false;
}
#Override public boolean isReady() {
return false;
}
#Override public void setReadListener(ReadListener readListener) {
}
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}
public String getBody() {
return this.body;
}
}
So I set up an Arduino as a JSON server, which's data I'd then like to log in a .log file on my desktop. The problem however is that the timer (javax.swing.timer) wont't work with any value longer than about +- 300ms. The rest of the code works fine, but maybe the JSON library has some influence on the timer? I'd be glad if someone were to help. The program does execute, and it doesn't show any error when I'm compiling it. This is most of the code, and I've marked the place where I think it fails with some asterisks:
public class ikd {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
getData();
}
public static void getData() throws IOException, JSONException {
//***********************************************
//***********************************************
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("yea");
}
};
new Timer(>+-300 works here but 400 doesn't!!!<, taskPerformer).start();
//***********************************************
//***********************************************
JSONObject json = readJsonFromUrl(">");
System.out.println(json.toString());
JSONArray arr = json.getJSONArray("kamers");
JSONObject tempObj = (JSONObject)arr.get(0);
String temp = tempObj.getString("temp");
String humidity = tempObj.getString("humidity");
String light = tempObj.getString("ldr");
System.out.println("Temperatuur: " + temp + ", Luchtvochtigheid: " + humidity + ", Lichtsterkte: " + light);
try{
PrintWriter writer = new PrintWriter("data.log", "UTF-8");
writer.println(temp + "," + humidity + "," + light);
writer.close();
} catch (Exception e) {
}
}
If I put the timer in the Main() method,nothing happens at all.
This is the console output with the timer running at 301 ms intervals:
301 ms interval:
And this is the console output at a 400 ms interval:
400 ms interval:
I'm sending a http request to get binary files (here i'm trying an image)
public class Main {
public static void main(String[] args) throws UnknownHostException,
IOException {
new Main(args);
}
public Main(String[] args) throws UnknownHostException, IOException {
lance(args);
}
private void lance(String[] args) throws UnknownHostException, IOException {
Lanceur lan = new Lanceur("www.cril.univ-artois.fr", "/IMG/arton451.jpg");
lan.requete();
}
}
public class Lanceur {
Socket s;
InputStream readStream;
OutputStream writeStream;
String host;
String ressource;
public Lanceur(String host, String ressource) throws UnknownHostException,
IOException {
s = new Socket(InetAddress.getByName(host), 80);
readStream = s.getInputStream();
writeStream = s.getOutputStream();
this.host = host;
this.ressource = ressource;
}
public void requete() throws IOException {
// String[] length = null;
writeStream.write(new String("GET " + ressource + " HTTP/1.1\r\n"
+ "Host: www.google.com\r\n" + "\r\n").getBytes());
writeStream.flush();
AnswerReader as = new AnswerReader(readStream);
as.read();
as.writeFile(this.ressource);
s.close();
}
}
public class AnswerReader {
BufferedReader br;
DataInputStream dis;
String status;
Map<String, String> attrs;
byte[] content;
public AnswerReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
dis = new DataInputStream(new BufferedInputStream(is));
}
public void read() throws NumberFormatException {
readStatus();
try {
readAttrs();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String contentL = attrs.get("Content-Length");
readContent(Integer.valueOf(contentL));
}
public void readStatus() {
try {
status = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void readAttrs() throws IOException {
attrs = new HashMap<String, String>();
String line;
for (line = br.readLine(); line.length() > 0; line = br.readLine()) {
int index = line.indexOf(':');
attrs.put(line.substring(0, index), line.substring(index + 2));
}
}
private void readContent(int size) {
this.content = new byte[size];
byte[] buff = new byte[1024];
int copied = 0;
int read = 0;
while (copied < size) {
try {
read = dis.read(buff);
if (read == -1)
break;
} catch (IOException e) {
e.printStackTrace();
}
// byte[] byteArray = new String(buff).getBytes();
System.arraycopy(buff, 0, content, copied, read);
copied += read;
}
System.out.println(copied + "///" + size);
}
public void writeFile(String name) throws IOException {
String tab[] = name.split("/");
String filename = tab[tab.length - 1];
FileOutputStream fos = new FileOutputStream("./" + filename);
fos.write(content);
fos.flush();
fos.close();
}
}
The problem comes from readContent(). The content-length is fine, but it doesn't read all the data. From this example it will reads that :
22325///38125
The BufferedReader is buffering some of the binary data. You'll have to find another way to read the header lines using the unbuffered input stream instead, e.g. DataInputStream.readLine(), deprecation or no.
But you should use HttpURLConnection. It's easier.
I'm using the following class to read a JSON file on some URL and make a JSONObject from it. When outputting something on the screen the program gets terminated without anything in the console. This is the code:
public class JsonReader {
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
System.out.println("in main!");
JSONObject json = readJsonFromUrl("http://somesubdomain.domain.com/blabla.json");
//System.out.println(json.get("id"));
}
}
It's really weird because it seems it doesn't even go in the main method. I just validated the JSON file and there's nothing wrong with it. Anybody any idea? Thanks.
EDIT: I found out that this works in a project on its own. This happens only when in the main package of the Android project.
Is this an android project? There is no public static void main(...) for android projects. You need to put this in an Activity.