I am trying to delete an object from an array with Angularjs Resource:
CommandeDetail.delete({id:commandeDetail.id});
My factory :
.factory('CommandeDetail', function ($resource) {
return $resource('api/commandeDetail/:id', {}, {
'query': { method: 'GET', isArray: true},
'get': {
method: 'GET'
}
});
})
My object commandeDetail is (debug on Chrome before delete is called) :
commandeDetail: Resource
$$hashKey: "object:1136"
calibre: "douze"
categorie: "II"
certificatFournisseur: "AGROCERT"
commande: null
commandeId: 10
commentaire: null
dispJ4: 0
emballage: "COLIS 10 KG NET"
id: 35
marque: "ECOCERT"
max: 10
nbPalettes: 0
produit: "ABRICOT"
puht: 0
quantite: 10
tare: 0
valorisation: "Net"
The delete is well done on server side but I am getting this error on frontSide :
angular.js:11598 RangeError: Maximum call stack size exceeded
at join (native)
at Object.stringify (native)
at toJson (http://localhost:8080/bower_components/angular/angular.js:1048:15)
at defaults.defaults.transformRequest (http://localhost:8080/bower_components/angular/angular.js:8707:74)
at http://localhost:8080/bower_components/angular/angular.js:8655:12
at forEach (http://localhost:8080/bower_components/angular/angular.js:323:20)
at transformData (http://localhost:8080/bower_components/angular/angular.js:8654:3)
at $get.serverRequest (http://localhost:8080/bower_components/angular/angular.js:9319:23)
at processQueue (http://localhost:8080/bower_components/angular/angular.js:13175:27)
at http://localhost:8080/bower_components/angular/angular.js:13191:27
I don't know where that can come from. My object is quite simple.
If anybody can help me on this...
Thanks
Related
I'm having a WebSocket endpoint exposed by the Play Framework like this:
def socket: WebSocket = WebSocket.acceptOrResult[JsValue, JsValue] { request =>
Future.successful(
if (acceptedSubProtocol(request.headers, appConfig.ocppServerCfg.supportedProtocols)) { // TODO: Get the Protocol via AppConfig
Right(ActorFlow.actorRef { actorRef =>
Props(new ProvisioningActor(actorRef))
})
} else {
logger.warn(s"Supported Protocol is not one of ${appConfig.ocppServerCfg.supportedProtocols.mkString(",")} " +
"in the Sec-WebSocket-Protocol header")
Left(Forbidden)
}
)
}
The following implicit conversion for the incoming Json which looks like this:
implicit val ocppCallRequestReads2: Reads[OCPPCallRequest] = Reads { jsValue =>
val messageTypeIdE = (jsValue \ 0).toEither
val messageIdE = (jsValue \ 1).toEither
val actionNameE = (jsValue \ 2).toEither
val payloadE = (jsValue \ 3).toEither
val yielded = for {
messageTypeId <- messageTypeIdE
messageId <- messageIdE
actionName <- actionNameE
payload <- payloadE
} yield {
OCPPCallRequest( // Here I know all 4 exists, so safe to call head
messageTypeId.head.as[Int],
messageId.head.as[String],
actionName.head.as[String],
payload
)
}
yielded match {
case Right(ocppCallRequest) => JsSuccess(ocppCallRequest)
case Left(errors) =>
println("****************+ ERRORS")
errors.messages.foreach(println)
println("****************+ ERRORS")
JsError(errors)
}
}
And the actual JSON:
[
"19223201",
"BootNotification",
{
"reason": "PowerUp",
"chargingStation": {
"serialNumber" : "12345",
"model" : "",
"vendorName" : "",
"firmwareVersion" : "",
"modem": {
"iccid": "",
"imsi": ""
}
}
}
]
What I'm trying to do is to validate the incoming JSON and propogate any errors to the client. When I tried to run my example., I'm not able to pass the error back as a JSON response, but the WebSocket endpoint closes with an internal server error as seen below:
[info] a.a.CoordinatedShutdown - Running CoordinatedShutdown with reason [ApplicationStoppedReason]
[info] a.e.s.Slf4jLogger - Slf4jLogger started
[info] play.api.Play - Application started (Dev) (no global state)
****************+ ERRORS
Array index out of bounds in ["19223201","BootNotification",{"reason":"PowerUp","chargingStation":{"serialNumber":"12345","model":"","vendorName":"","firmwareVersion":"","modem":{"iccid":"","imsi":""}}}]
****************+ ERRORS
[error] p.c.s.c.WebSocketFlowHandler - WebSocket flow threw exception
java.lang.ClassCastException: scala.Tuple2 cannot be cast to play.api.libs.json.JsValue
at akka.stream.impl.fusing.Map$$anon$1.onPush(Ops.scala:52)
at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:542)
at akka.stream.impl.fusing.GraphInterpreter.processEvent(GraphInterpreter.scala:496)
at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:390)
at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:650)
at akka.stream.impl.fusing.ActorGraphInterpreter$SimpleBoundaryEvent.execute(ActorGraphInterpreter.scala:61)
at akka.stream.impl.fusing.ActorGraphInterpreter$SimpleBoundaryEvent.execute$(ActorGraphInterpreter.scala:57)
at akka.stream.impl.fusing.ActorGraphInterpreter$BatchingActorInputBoundary$OnNext.execute(ActorGraphInterpreter.scala:104)
at akka.stream.impl.fusing.GraphInterpreterShell.processEvent(ActorGraphInterpreter.scala:625)
at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$processEvent(ActorGraphInterpreter.scala:800)
Any clues as to how I can control the WebSocket endpoint not to crash into an exception? What happens is that the connection gets closed and I do not want that.
I don't know how to use CustomSerializer to convert JSON to Scala data
I don't need to serialize the parts, but deserialization is difficult
Can someone help me? Thank you very much
{
"parameters": {
"field_owner": true,
"sample_field": "gender",
"sample_strategy": "by_ratio",
"sample_config": [["male", 1500.0], ["female", 1500.0]],
"with_replacement": true,
"random_seed": 114514,
"least_sample_num": 100
},
"input_artifacts": {"dataset": {"object_id": "upload/ml_classifier_predict_result"}},
"output_artifacts": {"predict_result": {"object_id": "ingest_output.csv"}}
}
class TupleSerializer extends CustomSerializer[(String,Double)](tuple_formats => (
{
case JArray(List(JString(x), JDouble(y))) =>
(x,y)
},{
case x:Tuple2[String,Double] => null
}
))
implicit val formats: Formats = DefaultFormats + new TupleSerializer
val fileBuffer = Source.fromFile(path)
val jsonString = fileBuffer.mkString
parse(jsonString).extract[StratifiedSampleArgument]
}
error message:
o usable value for parameters
No usable value for sample_config
Expected object with 1 element but got JArray(List(JString(male), JDouble(1500.0)))
at com.alipay.morse.sgxengine.driver.StratifiedSampleDriverTest.main(StratifiedSampleDriverTest.scala:15)
Caused by: org.json4s.package$MappingException:
No usable value for sample_config
Expected object with 1 element but got JArray(List(JString(male), JDouble(1500.0)))
at com.alipay.morse.sgxengine.driver.StratifiedSampleDriverTest.main(StratifiedSampleDriverTest.scala:15)
Caused by: org.json4s.package$MappingException: Expected object with 1 element but got JArray(List(JString(male), JDouble(1500.0)))
at com.alipay.morse.sgxengine.driver.StratifiedSampleDriverTest.main(StratifiedSampleDriverTest.scala:15)
[INFO]
[INFO] Results:
[INFO]
[ERROR] Errors:
[ERROR] StratifiedSampleDriverTest.main:15 » Mapping No usable value for parameters
No...
[INFO]
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0
I have multiline log that consists correct json part (one or more lines), and after it - stack trace.
Is it possile to parse first part of the log as json, and for stack-trace make new label ("stackTrace" for example) and put there all the lines after first part?
Unfortunately, logs can contain a different number of fields in json format, and therefore it is unlikely to parse them using regex.
{ "timestamp" : "2022-03-28 14:33:00,000", "logger" : "appLog", "level" : "ERROR", "thread" : "ktor-8080", "url" : "/path","method" : "POST","httpStatusCode" : 400,"callId" : "f7a22bfb1466","errorMessage" : "Unexpected JSON token at offset 184: Encountered an unknown key 'a'. Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys. JSON input: { \"entityId\" : \"TGT-8c8d950036bf\", \"processCode\" : \"test\", \"tokenType\" : \"SSO_CCOM\", \"ttlMills\" : 600000, \"a\" : \"a\" }" }
com.example.info.core.WebApplicationException: Unexpected JSON token at offset 184: Encountered an unknown key 'a'.
Use 'ignoreUnknownKeys = true' in 'Json {}' builder to ignore unknown keys.
JSON input: {
"entityId" : "TGT-8c8d950036bf",
"processCode" : "test",
"tokenType" : "SSO_CCOM",
"ttlMills" : 600000,
"a" : "a"
}
at com.example.info.signtoken.SignTokenApi$signTokenModule$2$1$1.invokeSuspend(SignTokenApi.kt:94)
at com.example.info.signtoken.SignTokenApi$signTokenModule$2$1$1.invoke(SignTokenApi.kt)
at com.example.info.signtoken.SignTokenApi$signTokenModule$2$1$1.invoke(SignTokenApi.kt)
at io.ktor.util.pipeline.SuspendFunctionGun.loop(SuspendFunctionGun.kt:248)
at io.ktor.util.pipeline.SuspendFunctionGun.proceed(SuspendFunctionGun.kt:116)
at io.ktor.util.pipeline.SuspendFunctionGun.execute(SuspendFunctionGun.kt:136)
at io.ktor.util.pipeline.Pipeline.execute(Pipeline.kt:78)
at io.ktor.routing.Routing.executeResult(Routing.kt:155)
at io.ktor.routing.Routing.interceptor(Routing.kt:39)
at io.ktor.routing.Routing$Feature$install$1.invokeSuspend(Routing.kt:107)
at io.ktor.routing.Routing$Feature$install$1.invoke(Routing.kt)
at io.ktor.routing.Routing$Feature$install$1.invoke(Routing.kt)
UPD.
I've made promtail pipeline like so
scrape_configs:
- job_name: Test_AppLog
static_configs:
- targets:
- ${HOSTNAME}
labels:
job: INFO-Test_AppLog
host: ${HOSTNAME}
__path__: /home/adm_web/app.log
pipeline_stages:
- multiline:
firstline: ^\{\s?\"timestamp\"
max_lines: 128
max_wait_time: 1s
- match:
selector: '{job="INFO-Test_AppLog"}'
stages:
- regex:
expression: '(?P<log>^\{ ?\"timestamp\".*\}[\s])(?s)(?P<stacktrace>.*)'
- labels:
log:
stacktrace:
- json:
expressions:
logger: logger
url: url
method: method
statusCode: httpStatusCode
sla: sla
source: log
But in fact, json config block does not work, the result in Grafana is only two fields - log and stacktrace.
Any help would be appreciated
if the style is constantly like this maybe the easiest way is to analyze whole log string find index of last symbol "}" - then split the string using its index+1 and result should be in the first part of output array
i have a json result:
0: { m_event_type_id: 0, m_event_log_description: "SYSTEM_LOG_44: RPM Reduction Due to High Wind Turbulence OFF", …}
1: { m_event_type_id: 0, m_event_log_description: "SYSTEM_LOG_44: RPM Reduction Due to High Wind Turbulence ON", …}
2: { m_event_type_id: 0, m_event_log_description: "Grease Pump Stopped 30 cycles executed", …}
3: { m_event_type_id: 0, m_event_log_description: "Grease Pump Started", …}
4: { m_event_type_id: 0, m_event_log_description: "SYSTEM_LOG_40: Battery Test Request Signal ON", …}
my result is stored in a variable call rslt,now i want to access
rslt.m_event_log_description
but it gives me error because cant access the property like this,any way to achive it?i dont want to write rslt[0].m_event_log_description because it just gives me the first one
You could use the Array#map function to extract a property from an object array as an array.
Try the following
someService.getData().subscribe(
response => {
this.rslt = response;
this.logDescriptions = response.map(item => item['m_event_log_description']);
},
error => {
// handle error
}
);
Now you could use the logDescriptions property in the template
<div *ngFor="description of logDescriptions">
{{ description }}
</div>
Here below is my code to find a document by ObjectID:
def find(selector: JsValue, projection: Option[JsValue], sort: Option[JsValue],
page: Int, perPage: Int): Future[Seq[JsValue]] = {
var query = collection.genericQueryBuilder.query(selector).options(
QueryOpts(skipN = page * perPage)
)
projection.map(value => query = query.projection(value))
sort.map(value => query = query.sort(value.as[JsObject]))
// this is the line where the call crashes
query.cursor[JsValue].collect[Vector](perPage).transform(
success => success,
failure => failure match {
case e: LastError => DaoException(e.message, Some(DATABASE_ERROR))
}
)
}
Now let's suppose we invoke this method with an invalid ObjectID:
// ObjectId 53125e9c2004006d04b605abK is invalid (ends with a K)
find(Json.obj("_id" -> Json.obj("$oid" -> "53125e9c2004006d04b605abK")), None, None, 0, 25)
The call above causes the following exception when executing query.cursor[JsValue].collect[Vector](perPage) in the find method:
Caused by: java.util.NoSuchElementException: JsError.get
at play.api.libs.json.JsError.get(JsResult.scala:11) ~[play-json_2.10.jar:2.2.1]
at play.api.libs.json.JsError.get(JsResult.scala:10) ~[play-json_2.10.jar:2.2.1]
at play.modules.reactivemongo.json.collection.JSONGenericHandlers$StructureBufferWriter$.write(jsoncollection.scala:44) ~[play2-reactivemongo_2.10-0.10.2.jar:0.10.2]
at play.modules.reactivemongo.json.collection.JSONGenericHandlers$StructureBufferWriter$.write(jsoncollection.scala:42) ~[play2-reactivemongo_2.10-0.10.2.jar:0.10.2]
at reactivemongo.api.collections.GenericQueryBuilder$class.reactivemongo$api$collections$GenericQueryBuilder$$write(genericcollection.scala:323) ~[reactivemongo_2.10-0.10.0.jar:0.10.0]
at reactivemongo.api.collections.GenericQueryBuilder$class.cursor(genericcollection.scala:342) ~[reactivemongo_2.10-0.10.0.jar:0.10.0]
at play.modules.reactivemongo.json.collection.JSONQueryBuilder.cursor(jsoncollection.scala:110) ~[play2-reactivemongo_2.10-0.10.2.jar:0.10.2]
at reactivemongo.api.collections.GenericQueryBuilder$class.cursor(genericcollection.scala:331) ~[reactivemongo_2.10-0.10.0.jar:0.10.0]
at play.modules.reactivemongo.json.collection.JSONQueryBuilder.cursor(jsoncollection.scala:110) ~[play2-reactivemongo_2.10-0.10.2.jar:0.10.2]
at services.common.mongo.MongoDaoComponent$MongoDao$$anon$1.find(MongoDaoComponent.scala:249) ~[classes/:na]
... 25 common frames omitted
Any idea? Thanks.