Error inserting DateTime values on database - java

I searched for this online and some posts even here on StackOverflow talk about this but never resolve to my problem.
I am having a problem inserting DateTime into the database. The first problem is that I only know how to make StringRequests from java, so I convert date to String (output example: "2000-04-23 10:25:06").
This is my java code:
StringRequest stringRequest = new StringRequest(Request.Method.GET, testInserirPontoURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {}
}) {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
String codColab = getIntent().getStringExtra("codigo colaborador");
LocalDate ldHoraEntrada = LocalDate.of(ponto.getEntrada().get(Calendar.YEAR), ponto.getEntrada().get(Calendar.MONTH) + 1, ponto.getEntrada().get(Calendar.DAY_OF_MONTH));
String horaEntrada = ldHoraEntrada + " " + sdfHora2.format(ponto.getEntrada().getTime());
LocalDate ldSaidaAlmoco = LocalDate.of(ponto.getSaidaAlmoco().get(Calendar.YEAR), ponto.getSaidaAlmoco().get(Calendar.MONTH) + 1, ponto.getSaidaAlmoco().get(Calendar.DAY_OF_MONTH));
String saidaAlmoco = ldSaidaAlmoco + " " + sdfHora2.format(ponto.getSaidaAlmoco().getTime());
LocalDate ldEntradaTarde = LocalDate.of(ponto.getEntradaTarde().get(Calendar.YEAR), ponto.getEntradaTarde().get(Calendar.MONTH) + 1, ponto.getEntradaTarde().get(Calendar.DAY_OF_MONTH));
String entradaTarde = ldEntradaTarde + " " + sdfHora2.format(ponto.getEntradaTarde().getTime());
LocalDate ldHoraSaida = LocalDate.of(ponto.getSaida().get(Calendar.YEAR), ponto.getSaida().get(Calendar.MONTH) + 1, ponto.getSaida().get(Calendar.DAY_OF_MONTH));
String horaSaida = ldHoraSaida + " " + sdfHora2.format(ponto.getSaida().getTime());
Map<String, String> map = new HashMap<String, String>();
map.put("horaEntrada", horaEntrada);
map.put("saidaAlmoco", saidaAlmoco);
map.put("entradaTarde", entradaTarde);
map.put("horaSaida", horaSaida);
map.put("cod_colab", codColab);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(PontoActivity.this);
requestQueue.add(stringRequest);
note: The codColab is a String in here but an int in the database, but it works just fine because I already use it for login.
This is my php code:
if($_SERVER['REQUEST_METHOD']=='GET'){
$horaEntrada = $_GET['horaEntrada'];
$saidaAlmoco = $_GET['saidaAlmoco'];
$entradaTarde = $_GET['entradaTarde'];
$horaSaida = $_GET['horaSaida'];
$cod_colab = $_GET['cod_colab'];
$sql= "INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES ('".$horaEntrada."', '".$saidaAlmoco."', '".$entradaTarde."', '".$horaSaida."', '".$cod_colab."')";
//$sql= "INSERT INTO `ponto` (`id`, `hora_entrada`, `saida_almoco`, `entrada_tarde`, `hora_saida`, `cod_colab`) VALUES (NULL, '2019-05-15 10:25:41', '2019-05-09 14:25:37', '2019-05-16 11:20:13', '2019-05-09 13:25:30', '1')";
//$sql= "INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES ('$horaEntrada', '$saidaAlmoco', '$entradaTarde', '$horaSaida', '$cod_colab')";
if (mysqli_query($conn, $sql)){
echo "registado";
} else {
echo "erro a registar";
}
Note: the comment lines are the ones I tried. the 1st comment line works but I want the values of the variables

Since $horaSaida can be NULL the output will be something like this:
INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES ('',...)
and '' isn't a right datatime value
You could this to get the right SQL:
$sql= "INSERT INTO ponto (hora_entrada,saida_almoco,entrada_tarde,hora_saida,cod_colab) VALUES (". (null === $horaEntrada ? "NULL" : "'$horaEntrada'") . ", '".$saidaAlmoco."', '".$entradaTarde."', '".$horaSaida."', '".$cod_colab."')";

Related

How to get automatically generated Firebase push ID from Firebase Realtime Database?

My app sends every message with a unique id (using push() method) so how can I get this id?
my code to send message :
String messageSenderRef = "Messages/" + messageSenderID + "/" + messageReceiverID;
String messageReceiverRef = "Messages/" + messageReceiverID + "/" + messageSenderID;
DatabaseReference userMessagesKeyRef = reference.child("Messages")
.child(messageSenderID).child(messageReceiverID).push();
String messagePushID = userMessagesKeyRef.getKey();
Map messageTextBody = new HashMap();
messageTextBody.put("message",messageText);
messageTextBody.put("type","text");
messageTextBody.put("to",messageReceiverID);
messageTextBody.put("from",messageSenderID);
messageTextBody.put("time",time);
messageTextBody.put("date",date);
messageTextBody.put("isSeen",false);
messageTextBody.put("messageID",messagePushID);
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(messageSenderRef + "/" + messagePushID,messageTextBody);
messageBodyDetails.put(messageReceiverRef + "/" + messagePushID,messageTextBody);
My Firebase database node:
Firebase Node:
If you want to read the value of messageID field, then you should create a reference that points to the cG6v...PXi1 node and use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = db.child("Messages");
DatabaseReference messageReceiverIdRef = messagesRef.child(messageSenderID).child(messageReceiverID);
messageReceiverIdRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String messageId = ds.child("messageID").getValue(String.class);
Log.d("TAG", messageId);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
-ND-fz....l2krv
...

java.lang.IllegalArgumentException: 'value' is not a valid managed object with realm

I'm using realm to storing data after reading it from the server but when I try to store it in realm I got "java.lang.IllegalArgumentException: 'value' is not a valid managed object"
here is my code of the method to storing data in realm
public void addOrdersToLocalDB(Order order,List<Product> products) {
realmAsyncTask = myRealm.executeTransactionAsync(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
Order localOrder = realm.createObject(Order.class, order.getId());
localOrder.setName(order.getName());
localOrder.setTimestamp(order.getTimestamp());
localOrder.setDate(order.getDate());
localOrder.setCost(order.getCost());
localOrder.setProductNums(order.getProductNums());
localOrder.setTime(order.getTime());
Log.d("orders_data", "realm order : " + order.getName());
RealmList<Product> localProducts = new RealmList<>();
for (Product product : products){
Log.d("orders_data", "realm product : " + product.getName());
Product localProduct = realm.createObject(Product.class, product.getId());
localProduct.setName(product.getName());
localProduct.setBarCode(product.getBarCode());
localProduct.setCurrentQuantity(product.getCurrentQuantity());
localProduct.setStatus(product.getStatus());
localProduct.setOldUnitPrice(product.getOldUnitPrice());
localProduct.setImage(product.getImage());
localProduct.setNeededQuantity(product.getNeededQuantity());
localProduct.setTotalPrice(product.getTotalPrice());
localProduct.setDescription(product.getDescription());
localProduct.setUnitPrice(product.getUnitPrice());
localProduct.setTimeStamp(product.getTimeStamp());
localProducts.add(product);
}
if (localProducts.size() == products.size()){
Log.d("orders_data", "realm products size : " + String.valueOf(localProducts.size()));
localOrder.setProducts(localProducts);
}
}
}, new Realm.Transaction.OnSuccess() {
#Override
public void onSuccess() {
HelperMethods.displayToastMsg("data added successfully to realm", HomeActivity.this);
curvesLoader.setVisibility(View.GONE);
//setupRecyclerView();
}
}, new Realm.Transaction.OnError() {
#Override
public void onError(Throwable error) {
curvesLoader.setVisibility(View.GONE);
HelperMethods.displayToastMsg("data not added to realm, there was a problem : " + error, HomeActivity.this);
Log.d("myrealm", error.toString());
}
});
}
I searched about that error and checked this question here and still got the error hoping if any one can help?
also when I use other method with static data like the next code it works fine
Order order = realm.createObject(Order.class, "1");
order.setName("طلب 1");
order.setTimestamp("٢٠١٩.٠١.١٦.١١.٢٤.١٦");
order.setDate("٢٠١٩.٠١.١٦");
order.setCost("1050");
order.setProductNums("2");
order.setTime("١١.٣٧.٢٦");
RealmList<Product> products = new RealmList<>();
Double unitPrice = 10.0;
int neededQuantity = 5;
int currentQuantity = 0;
Product product = realm.createObject(Product.class, "1");
product.setName("مناديل فاين");
product.setBarCode("6251001214468");
product.setCurrentQuantity("0");
product.setStatus(1);
product.setOldUnitPrice(String.valueOf(unitPrice));
product.setImage("https://www.albawaba.com/sites/default/files/im/pr_new/FINE_NEW_PACK.jpg");
product.setNeededQuantity(String.valueOf(neededQuantity - currentQuantity));
product.setTotalPrice(String.valueOf(unitPrice * neededQuantity));
product.setDescription("الوزن : 100 منديل / العدد : 36 علبة");
product.setUnitPrice(String.valueOf(unitPrice));
product.setTimeStamp("٢٠١٩.٠١.١٦.١١.٣٧.٢٦");
products.add(product);
unitPrice = 7.5;
neededQuantity = 10;
currentQuantity = 0;
Product product2 = realm.createObject(Product.class, "2");
product2.setName("بيبسى 1 لتر");
product2.setBarCode("6223001360766");
product2.setStatus(1);
product2.setOldUnitPrice(String.valueOf(unitPrice));
product2.setCurrentQuantity("0");
product2.setImage("https://grocety.com/media/catalog/product/cache/2/small_image/228x/9df78eab33525d08d6e5fb8d27136e95/1/2/120-370x310.jpg");
product2.setNeededQuantity(String.valueOf(neededQuantity - currentQuantity));
product2.setTotalPrice(String.valueOf(unitPrice * neededQuantity));
product2.setUnitPrice(String.valueOf(unitPrice));
product2.setDescription("الحجم :1 لتر / العدد : 30");
product2.setCurrentQuantity(String.valueOf(currentQuantity));
product2.setTimeStamp("٢٠١٩.٠١.١٦.١١.٢٤.١٦");
products.add(product2);
order.setProducts(products);
Replace localProducts.add(product) with localProducts.add(localProduct) , you initialized localProduct but forgot to add him to list, and instead adding product that not managed by Realm.

Can't get results from flink SQL query

I'm facing a problem in which I don't get results from my query in Flink-SQL.
I have some informations stored in two Kafka Topics, I want to store them in two tables and perform a join between them in a streaming way.
These are my flink instructions :
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
StreamTableEnvironment tableEnv = TableEnvironment.getTableEnvironment(env);
// configure Kafka consumer
Properties props = new Properties();
props.setProperty("bootstrap.servers", "localhost:9092"); // Broker default host:port
props.setProperty("group.id", "flink-consumer"); // Consumer group ID
FlinkKafkaConsumer011<Blocks> flinkBlocksConsumer = new FlinkKafkaConsumer011<>(args[0], new BlocksSchema(), props);
flinkBlocksConsumer.setStartFromEarliest();
FlinkKafkaConsumer011<Transactions> flinkTransactionsConsumer = new FlinkKafkaConsumer011<>(args[1], new TransactionsSchema(), props);
flinkTransactionsConsumer.setStartFromEarliest();
DataStream<Blocks> blocks = env.addSource(flinkBlocksConsumer);
DataStream<Transactions> transactions = env.addSource(flinkTransactionsConsumer);
tableEnv.registerDataStream("blocksTable", blocks);
tableEnv.registerDataStream("transactionsTable", transactions);
Here is my SQL query :
Table sqlResult
= tableEnv.sqlQuery(
"SELECT block_timestamp,count(tx_hash) " +
"FROM blocksTable " +
"JOIN transactionsTable " +
"ON blocksTable.block_hash=transactionsTable.tx_hash " +
"GROUP BY blocksTable.block_timestamp");
DataStream<Test> resultStream = tableEnv
.toRetractStream(sqlResult,Row.class)
.map(t -> {
Row r = t.f1;
String field2 = r.getField(0).toString();
long count = Long.valueOf(r.getField(1).toString());
return new Test(field2,count);
})
.returns(Test.class);
Then, I print the results :
resultStream.print();
But I don't get any answers, my program is stuck...
For the schema used for serialization and deserialization, here is my test class which stores the result of my query (two fields a string and a long for respectively the block_timestamp and the count) :
public class TestSchema implements DeserializationSchema<Test>, SerializationSchema<Test> {
#Override
public Test deserialize(byte[] message) throws IOException {
return Test.fromString(new String(message));
}
#Override
public boolean isEndOfStream(Test nextElement) {
return false;
}
#Override
public byte[] serialize(Test element) {
return element.toString().getBytes();
}
#Override
public TypeInformation<Test> getProducedType() {
return TypeInformation.of(Test.class);
}
}
This is the same principle for BlockSchema and TransactionsSchema classes.
Do you know why I can't get the result of my query ? Should I test with BatchExecutionEnvironment ?

Parse save ParseGeoPoint by objectId fails with "com.parse.ParseRequest$ParseRequestException:"

Following instructions here to save data to an object by objectId thru android app and getting errmsg com.parse.ParseRequest$ParseRequestException: (without anything following semicolon). I have confirmed objectId is as shown in parse dashboard. Can someone please help me figure out what I'm doing incorrectly? Thanks
final String parseRequest = "Request";
final String parseRequestDriverLocation = "driverLocation";
private void saveDriverLocation(String objectId, Location driverLocation) {
Log.i("saveDriverLocation", "objectId=" + objectId + ", driverLocation=" + driverLocation.toString());
ParseGeoPoint locationDriverParse = new ParseGeoPoint(driverLocation.getLatitude(), driverLocation.getLongitude());
ParseObject acceptedRequest = ParseObject.createWithoutData(parseRequest, objectId);
Log.i("saveDriverLocation", "acceptedRequest=" + acceptedRequest.toString() + "\nlocationDriverParse=" + locationDriverParse.toString());
acceptedRequest.put(parseRequestDriverLocation, locationDriverParse);
acceptedRequest.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Log.i("saveDriverLocation", "driver location saved successfully");
} else {
Log.i("saveDriverLocation", "saving driver location failed... " + e.toString());
}
}
});
}
The logcat:
I/saveDriverLocation: objectId=Ddm73yXhPC, driverLocation=Location[gps 41.677770,-80.385998 acc=20 et=+1d7h59m59s883ms alt=18.0 {Bundle[mParcelledData.dataSize=40]}]
I/saveDriverLocation: acceptedRequest=com.parse.ParseObject#ddeb183
locationDriverParse=ParseGeoPoint[41.677770,-80.385998]
I/saveDriverLocation: saving driver location failed... com.parse.ParseRequest$ParseRequestException:
Apparently a Parse class can only have one ParseGeoPoint column! Here is reference.

Elasticsearch index a document

I'm having serious issues trying to find the correct syntax to push a document into an elasticsearch index by type.
My code im using to do this is :
String url = "https://my_url/my_index_name";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
String site = jsonResponse.getString("site"),
network = jsonResponse.getString("network");
Log.d("Site: ", site + "\nNetwork: "+network);
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON EXCEPTION", e.toString());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}
)
{
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("type", "type_name");;
params.put("field1", field1_value);
params.put("field2", field2_value);
params.put("field3", field3_value);
params.put("field4", field4_value);
params.put("field5", field5_value);
return params;
}
};
Volley.newRequestQueue(this).add(postRequest);
It's hitting the server, as I'm getting 400 requests, but I just cant get it to go in using this.
12-14 16:19:04.533 12642-13089/? E/Volley﹕ [41831]
BasicNetwork.performRequest: Unexpected response code 400 for URL
Can some enlighten me as to what the correct syntax is, using java code, or tell me what I'm doing wrong?
I assumed the correct syntax was:
http:// url | index_name | type | body ?
EDIT: I've searched SO, elastic java api's, google groups and all over the internet for 3 days now, with no luck! Anything at all is greatly appreciated !
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.e("VOLLEY ERROR", "" + error.toString());
}
}
Results in : VOLLEY ERROR﹕ com.android.volley.ServerError
Any ideas?
Ok, so I managed to fix it.
There was two issues:
The first issue was with the URL which was:
String url = "https://my_url/my_index_name";
It should have been:
String url = "https://my_url/my_index_name/type%20-d";
The second issue was with the actual arguments:
params.put("type", "type_name");;
params.put("field1", field1_value);
params.put("field2", field2_value);
params.put("field3", field3_value);
params.put("field4", field4_value);
params.put("field5", field5_value);
return params;
I swapped this out for :
String urlParameters =
"{" +
" \"field\": \" + field_value \"," +
" \"field\": \" + field_value \"," +
" \"field\": \" + field_value \"," +
" \"field\": \" + field_value \"," +
" \"field\": \" + field_value \"" +
"}";
And post by:
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
Everything is working as I want now, thanks for the help.

Categories