My java swing timer is limited to a +- 300ms schedule - java

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:

Related

How to place add data on JavaFX TableView (Scene Builder) with JSON data

Currently I can retrieve the data of JSON from https://jsonplaceholder.typicode.com/albums.
As of now, I can parse the json data and call everyfield of it. The JSON includes the fields of id, userId, title
In my code, I declare them below
int id,userId
String title
and this is the current Output
Now I'm trying to place these values to FXML file to my Home.fxml
my Table View has columns of id,userId,title and these columns has fx:id of
field1, field2, field3
Here's the fxml
and the fx:id of TableView is fx:id="tableView"
What I want to try is to place the parsed data of JSON into the Table View. But I don't have idea how can I place them all.
My Main file codes
public class Main extends Application {
private static HttpURLConnection connection;
#Override
public void start(Stage primaryStage) throws Exception{
BufferedReader reader;
String line;
StringBuffer responseContent = new StringBuffer();
try {
URL url = new URL("https://jsonplaceholder.typicode.com/albums");
connection = (HttpURLConnection) url.openConnection();
// Request Setup
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
int status = connection.getResponseCode();
if (status > 299){
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
while((line = reader.readLine()) != null){
responseContent.append(line);
}
reader.close();
parse(responseContent.toString());
}
catch (MalformedURLException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
} finally{
connection.disconnect();
}
Scene scene = new Scene(FXMLLoader.load(getClass().getResource("Home.fxml")));
primaryStage.setScene(scene);
primaryStage.setTitle("Home");
primaryStage.show();
}
public static String parse(String responseBody){
JSONArray albums = new JSONArray(responseBody);
for (int i = 0; i < albums.length(); i++){
JSONObject album = albums.getJSONObject(i);
int id = album.getInt("id");
int userId = album.getInt("userId");
String title = (String) album.get("title");
System.out.println(id + " | " + title + " | " + userId);
}
return null;
}
public static void main(String[] args) { launch(args); }
}

Java Get Link From Another Class (Json)

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();
}
}

How to read binary data serialized via Avro using HTTP as transport?

I'm using Avro as the serialization protocol. My service is ready, every serialization/deserialization works fine in memory.
So now I'd like to test it to see if it works fine after HTTP transport.
I thought it's simple to write a method to test, but after a while, I'm not able to figure it out, here's what I've tried:
Using HttpClient:
String itemIds = "abc123";
System.out.println("itemIds are: " + itemIds + "\n\n\n");
String endpoint = "http://localhost:8080/api/v1/items?itemIds=" + URLEncoder.encode(itemIds, "UTF-8");
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(endpoint);
String USER_AGENT = "Mozilla/5.0";
request.addHeader("User-Agent", USER_AGENT);
request.addHeader("Content-Type", "avro/binary");
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
byte[] bytes = EntityUtils.toByteArray(response.getEntity());
SearchMaterializationDto deserializedReponse = SearchMaterializationAvroObjectSerializer.deserializeToSearchMaterialization(bytes);
System.out.println(deserializedReponse.toString());
This approach is throwing java.io.EOFException. when executing this line SearchMaterializationDto deserializedReponse = SearchMaterializationAvroObjectSerializer.deserializeToSearchMaterialization(bytes);
Here's my SearchMaterializationDto deserializedReponse = SearchMaterializationAvroObjectSerializer.deserializeToSearchMaterialization(bytes); method:
public static SearchMaterializationDto deserializeToSearchMaterialization(byte[] buffer) {
SearchMaterializationDto searchMaterializationDto = new SearchMaterializationDto();
try {
ObjectInput input = new ObjectInputStream(new ByteArrayInputStream(buffer));
searchMaterializationDto.readExternal(input);
} catch (IOException e) {
throw new RuntimeException(e);
}
return searchMaterializationDto;
}
And here's my SearchMaterializationDto.java class (listed only the invoked method):
#org.apache.avro.specific.AvroGenerated
public class SearchMaterializationDto extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord {
private static final org.apache.avro.io.DatumReader
READER$ = new org.apache.avro.specific.SpecificDatumReader(SCHEMA$);
#Override public void readExternal(java.io.ObjectInput in)
throws java.io.IOException {
READER$.read(this, SpecificData.getDecoder(in));
}
}
Using Avro Decoder as this example shows:
private static void decoderWay(String endpoint) throws IOException {
byte[] bytes = getBytes(endpoint);
Decoder decoder = DecoderFactory.get().binaryDecoder(bytes, null);
SpecificDatumReader<SearchMaterializationDto> reader = new SpecificDatumReader<SearchMaterializationDto>(SearchMaterializationDto.getClassSchema());
SearchMaterializationDto searchMaterializationDto = reader.read(null, decoder);
}
But it's also throwing EOFException:
Exception in thread "main" java.io.EOFException
at org.apache.avro.io.BinaryDecoder.ensureBounds(BinaryDecoder.java:473)
at org.apache.avro.io.BinaryDecoder.readLong(BinaryDecoder.java:160)
at org.apache.avro.io.BinaryDecoder.doReadItemCount(BinaryDecoder.java:363)
at org.apache.avro.io.BinaryDecoder.readMapStart(BinaryDecoder.java:408)
at org.apache.avro.io.ValidatingDecoder.readMapStart(ValidatingDecoder.java:211)
at org.apache.avro.generic.GenericDatumReader.readMap(GenericDatumReader.java:308)
at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:177)
at org.apache.avro.specific.SpecificDatumReader.readField(SpecificDatumReader.java:116)
at org.apache.avro.generic.GenericDatumReader.readRecord(GenericDatumReader.java:230)
at org.apache.avro.generic.GenericDatumReader.readWithoutConversion(GenericDatumReader.java:174)
at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:152)
at org.apache.avro.generic.GenericDatumReader.read(GenericDatumReader.java:144)
It turns out to be my serialization/deserilization code problem. I've changed it to the following and it works:
public static byte[] serializeSearchMaterializationToByteArray(SearchMaterializationDto searchMaterializationDto) {
return avroSerialize(SearchMaterializationDto.class, searchMaterializationDto);
}
public static <T> byte[] avroSerialize(Class<T> clazz, Object object) {
byte[] ret = null;
try {
if (object == null || !(object instanceof SpecificRecord)) {
return null;
}
T record = (T) object;
ByteArrayOutputStream out = new ByteArrayOutputStream();
Encoder e = EncoderFactory.get().directBinaryEncoder(out, null);
SpecificDatumWriter<T> w = new SpecificDatumWriter<T>(clazz);
w.write(record, e);
e.flush();
ret = out.toByteArray();
} catch (IOException e) {
}
return ret;
}
public static SearchMaterializationDto deserializeToSearchMaterialization(byte[] avroBytes) {
return avroDeserialize(avroBytes, SearchMaterializationDto.class, SearchMaterializationDto.getClassSchema());
}
public static <T> T avroDeserialize(byte[] avroBytes, Class<T> clazz, Schema schema) {
T ret = null;
try {
ByteArrayInputStream in = new ByteArrayInputStream(avroBytes);
Decoder d = DecoderFactory.get().directBinaryDecoder(in, null);
SpecificDatumReader<T> reader = new SpecificDatumReader<T>(clazz);
ret = reader.read(null, d);
} catch (IOException e) {
}
return ret;
}

Java http request on binary file - can't read correct content-length

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.

My JsonReader class get terminated without printing any output

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.

Categories

Resources