post data to influx database - java

I have logs in the form of string. I want to send these logs form my application to influx Database. So, i have written these functions.
private String formatAsJsonArrayString(List<String> logs) {
Gson gson = new Gson();
return gson.toJson(logs);
}
public void startFlushToInfluxDbThread() {
Thread flushToInfluxDbThread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
try {
Thread.sleep(influxPostWaitTime);
List<String> logs = extractNEntries(queue, 1000);
String dataToPost = formatAsJsonArrayString(logs);
postToInfluxDB(dataToPost);
} catch (Exception e) {
e.printStackTrace();
}
}
}
but now i am unable to think how to write postToInfluxDB() function. Can somebody guide me to do this? I mean to say, how connection will be made and all that related stuff.

Related

Task manager (java)

Program must accept requests to add and remove tasks from the list through the server. After starting, server accepts connections in an infinite loop and reads from them a line containing json of the form:
{ "type": "ADD", "task": "Название задачи" }
where type is the type of operation (ADD or REMOVE) and task is the task itself. After processing the request, a list of all tasks should be displayed in the console. After connecting, my console gives null. What can be wrong?
Server class:
public class TodoServer {
public TodoServer(int port, Todos todos) {
while (true) {
try (ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
System.out.println("New connection accepted");
final String json = in.readLine();
Gson gson = new Gson();
String type = gson.fromJson("\"type\"", String.class);
String task = gson.fromJson("\"task\"", String.class);
if (type.equals("ADD")) {
todos.addTask(task);
} else if (type.equals("REMOVE")) {
todos.removeTask(task);
}
System.out.println(todos.getAllTasks());
} catch (IOException e) {
System.out.println("Соединение разорвано");
}
}
}
public void start() throws IOException {
int port = 8989;
System.out.println("Starting server at " + port + "...");
}
}
Task class:
public class Todos {
static ArrayList <String> tasks = new ArrayList<>();
public void addTask(String task) {
tasks.add(task);
Collections.sort(tasks);
}
public void removeTask(String task) {
tasks.remove(task);//...
}
public String getAllTasks() {
return tasks.toString();
}
public ArrayList<String> getListTask() {
return tasks;
}
}
The Main class which the server starts:
public class Main {
public static void main(String[] args) throws IOException {
Todos todos = new Todos();
TodoServer server = new TodoServer(8989, todos);
server.start();
}
}
From what you've shown here, your parsing and use of JSON is the issue. As a starting point, you read a String json but then do nothing with it.
You'll want to parse that value into an object, and then access values out of it (like you would a dictionary or map). How to do that with GSON should have plenty of documentation and examples readily available.
If you are using an IDE for development, I also recommend using this as a great opportunity for trying the debugger out - setting breakpoints, inspecting values, etc!
It would be better to define a simple POJO to represent a task:
#Data
class MyTask {
private String type;
private String task;
}
Here #Data is a Lombok annotation which provides the boilerplate code of getters/setters/default constructor/toString/hashCode/equals.
Then the instance of such POJO is deserialized from JSON abd processed as needed:
final String json = in.readLine();
MyTask task = new Gson().fromJson(json, MyTask.class);
if ("ADD".equals(task.getType())) {
todos.addTask(task.getTask());
} else if ("REMOVE".equals(task.getType())) {
todos.removeTask(task.getTask());
}
System.out.println(todos.getAllTasks());

Watson Speech to Text request using Websockets and JAVA

I am trying to request a transcription of an MP3 file using Websockets and Java. The following is a snippet of my Maven dependency followed by the java code . I've put breakpoints in each of the Override methods but not hitting any of them. What am I doing wrong?
Maven Dependency:
<dependency>
<groupId>com.ibm.watson.developer_cloud</groupId>
<artifactId>java-sdk</artifactId>
<version>6.1.0</version>
</dependency>
Code:
SpeechToText speechToText = new SpeechToText();
speechToText.setEndPoint("https://stream.watsonplatform.net/speech-to-text/api/v1/recognize");
speechToText.setUsernameAndPassword("{myUsername}", "{myPassword}");
try {
RecognizeOptions recognizeOptions = new RecognizeOptions.Builder()
.audio(new FileInputStream("KATL-App-Final-All-Aug-01-2017-1630.mp3-edited.mp3"))
.contentType("audio/mp3")
.model("en-US_NarrowbandModel")
.interimResults(true)
.build();
BaseRecognizeCallback baseRecognizeCallback
= new BaseRecognizeCallback() {
#Override
public void onListening() {
System.out.println("Listening");
}
#Override
public void onConnected() {
System.out.println("Connected");
}
#Override
public void onTranscription(SpeechRecognitionResults speechRecognitionResults) {
System.out.println(speechRecognitionResults);
}
#Override
public void onDisconnected() {
System.exit(0);
}
};
speechToText.recognizeUsingWebSocket(recognizeOptions,
baseRecognizeCallback);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
for (;;) {
Thread.sleep(1000);
}
I think I have identified the problem, which is your end point.
The SpeechToText.recognizeUsingWebSocket() method contains this helpful(?) line of code:
HttpUrl.Builder urlBuilder = HttpUrl.parse(getEndPoint() + "/v1/recognize").newBuilder();
So try changing the end point to https://stream.watsonplatform.net/speech-to-text/api or better yet don't set it and just construct SpeechToText using the constructor:
SpeechToText(String username, String password)
This will remove the need to invoke setUsernameAndPassword() and use the default end point:
private static final String URL = "https://stream.watsonplatform.net/speech-to-text/api";

when sending post request with codeName one, Json String is empty

I am trying to send a POST request with a JSON BODY in CodeName one.
It reaches the server with an empty Json String.
Here is the code that makes the connection and sends the message:
JSONObject json = new JSONObject();
class MyConnection extends ConnectionRequest {
public Map<String, Object> results;
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser jp = new JSONParser();
results = jp.parseJSON(new InputStreamReader(input, "UTF-8"));
}
#Override
protected void handleErrorResponseCode(int code, String message) {
showError("The server returned the error code: " + code);
}
#Override
protected void handleException(Exception err) {
showError("There was a connection error: " + err);
}
#Override
protected void postResponse() {
try {
json.put("AAA", "AAA");
json.put("BBB", "BBB");
json.put("CCC", "CCC");
} catch (JSONException ex) {
ex.printStackTrace();
}
}
#Override
protected void buildRequestBody(OutputStream os) throws IOException {
os.write(json.toString().getBytes("UTF-8"));
}
}
---
MyConnection connec = new MyConnection ();
connec.setUrl("http://testServoce/addUser");
connec.setPost(true);
connec.setContentType("application/json");
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
connec.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(connec);
I'm not sure what your intention was but it looks like you misunderstood the goal of the postResponse method. It's unrelated to the POST web method and is just called after the response completed on the EDT. So changing the JSON value there is irrelevant.
Also it looks like you are using two separate JSON parsers for some reason. The builtin one and the org.json one from one of the cn1libs.

How to design a class that can pass data from server when data is finish downloading

I'm new on Android development and I'm learning how to use MVP pattern correctly in recently.
Now I'm facing a tricky problem, hope can get some helpful suggestion or solution from here.
First, here is my presenter
public class MVPPresenter {
private MVPView mvpView;
public MVPPresenter(MVPView mvpView) {
this.mvpView = mvpView;
}
public void loadData() {
mvpView.startLoading();
final List<MVPModel> list = new ArrayList<>();
//the part that I trying to extract starts here.
Call call = DataRetriever.getDataByGet(URLCombiner.GET_FRONT_PAGE_ITEMS);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
mvpView.errorLoading();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try {
JSONObject result = new JSONObject(response.body().string());
int errorCode = result.getInt("ErrorCode");
if (errorCode == 0) {
JSONArray value = result.getJSONObject("Value").getJSONArray("hot");
for (int i = 0; i < value.length(); i++) {
MVPModel mvpModel = new MVPModel();
String name = null;
String image = null;
try {
name = value.getJSONObject(i).getString("title");
image = URLCombiner.IP + value.getJSONObject(i).getString("pic");
} catch (JSONException e) {
e.printStackTrace();
}
mvpModel.setName(name);
mvpModel.setImage(image);
list.add(mvpModel);
}
if (list.size() > 0) {
mvpView.successLoading(list);
mvpView.finishLoading();
} else {
mvpView.errorLoading();
}
} else {
mvpView.errorLoading();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
mvpView.errorLoading();
}
}
});
//the part that I trying to extract ends here.
}
}
As you can see, I'm trying to extract the part which is using OKHttp libs into a class (I call it data manager) which I hope it can handle every task between server and client. But here's the thing, when I trying to pass the result from the data manager to presenter, I got NullPointException because of the async mechanism.
I would like to know how to passing the data, which is come from server in async, to the presenter when the data has finish downloading.
And here's my ideal data manager, I know this might looks stupid but I think this can make my problem more clearly.
public class LoadServerData {
private static JSONArray arrayData = new JSONArray();
public static JSONArray getServerData() {
Call call = DataRetriever.getDataByGet(URLCombiner.GET_FRONT_PAGE_ITEMS);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try {
JSONObject result = new JSONObject(response.body().string());
int errorCode = result.getInt("ErrorCode");
if (errorCode == 0) {
arrayData = result.getJSONObject("Value").getJSONArray("hot"); //the data I would like to return.
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
return arrayData; //this is gonna be an empty data.
}
}
I've reading some article that might can solve my problem, but still not getting any fine answer. Perhaps I've using wrong keyword I think. Hopes you guys can give me some ideas or solutions to help me or inspire me.
P.S. version of OKhttp libs is 3.7.0
Create a simple Listener so it can be called whenever the server call finishes:
public class LoadServerData {
public static interface Listener {
public void onSuccess(JSONArray data);
public void onError(Exception error);
}
public static void getServerData(Listener listener) {
Call call = DataRetriever.getDataByGet(URLCombiner.GET_FRONT_PAGE_ITEMS);
call.enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
listener.onError(e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()) {
try {
JSONObject result = new JSONObject(response.body().string());
int errorCode = result.getInt("ErrorCode");
if (errorCode == 0) {
JSONArray arrayData = result.getJSONObject("Value").getJSONArray("hot"); //the data I would like to return.
listener.onSuccess(arrayData);
} else {
listener.onError(...);
}
} catch (JSONException e) {
e.printStackTrace();
listener.onError(e);
}
} else {
listener.onError(...);
}
}
});
}
}

Android JAVA: Reading variables that a thread is accessing

I've got an app with several screens. In addition, I have a globally-running timer that occasionally (every minute or so) attempts to refresh their transaction data from a website and store it in a JSONArray (static JSONArray jTransactions).
When you go to the Transaction screen, the first thing it does is populate a ListView with the contents of jTransactions, and it will refresh the displayed info every few seconds. However if the web-thread is currently running, I get null values for everything.
I've got enough coder savvy to know that it's a threading issue, but I'm not experienced enough with JAVA/Android development to know how to handle it. And my Google-fu may be weak but the only answers I found either didn't apply or involved heavy rewriting.
I guess my question is this - how can I alter my code so that there's no direct collision between my activity and the fetch thread?
Also I fully accept that my code is probably ugly; as I said, I'm still learning the platform.
Here's a pared-down version of the thread I'm running:
static int iRefreshTransactions = 30000;
static boolean bRefreshingTransactions = false;
static Calendar cLastRefreshTransactions = null;
final Runnable mRefreshTransactions = new Runnable() {
public void run() {
mHandler.removeCallbacks(this);
Thread T = new tRefreshTransactions();
T.start();
}
};
private class tRefreshTransactions extends Thread {
#Override
public void run() {
bRefreshingTransactions = true;
RetrieveTransactions();
bRefreshingTransactions = false;
handler.sendEmptyMessage(0);
}
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
cLastRefreshTransactions = Calendar.getInstance();
ShowToast("cLastRefreshTransactions(): " + cLastRefreshTransactions.getTime().toLocaleString());
mHandler.postDelayed(mRefreshTransactions, iRefreshTransactions);
}
};
private Handler failhandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// handle the failure somehow
}
};
}
Here's a pared-down version of the RetrieveTransactions() code:
// Retrieve the user's latest transactions from the website.
public boolean RetrieveTransactions() {
String result;
FailureReason = "";
iTransactions = 0;
// Retrieve the Page.
result = GetPage(Url);
// Strip the transactions from the page and convert them to a JSONArray.
try {
String sTransactions = textExtract(result, "var dataTable1Data=", ";\n", 0);
jTransactions = new JSONArray(sTransactions);
iTransactions = jTransactions.length();
return true;
} catch (JSONException e1) {
// Generally if it fails during this, there was no JSONArray to parse (hence no transactions).
FailureReason = "No Transactions Found";
return false;
}
}
And finally here's the pared-down code that displays the transactions in a listview, which is called at activity launch and every 5 seconds or so thereafter:
public void ShowTransactions() {
try {
if (!bRefreshingTransactions) {
if (iTransactions==0) {
return;
}
if (iTransactions==0) return;
List<String> listContents = new ArrayList<String>(iTransactions);
for (int i = 0; i < iTransactions; i++) {
listContents.add(jTransactions.getString(iTransactions - i - 1));
}
lvRecentTransactions.setAdapter(new ArrayAdapterTransactions(MyContext, listContents));
}
} catch (Exception e) {
// Do error stuff here
}
}
Thank you in advance. :)
It seems to be mutual exclusion problem. Make jTransaction synchronized or put the jTransaction variable in synchonized block.
synchronized(jTransactions ){
String sTransactions = textExtract(result, "var dataTable1Data=", ";\n", 0);
jTransactions = new JSONArray(sTransactions);
iTransactions = jTransactions.length();
}
I didn't test the code but I hope synchronization will help you.

Categories