JavaCC line number in exception - javacc

i use JavaCC for parsing my script...
I have something like this in my *.jj
private Type parseType() throws MyScriptException:
{
Token token;
}
{ ( token = <INT>
| token = <FLOAT>
| token = <BOOL>
| token = <STRING>
)
{ return types.get(token.image); }
}
in types.get I throw an exception from type MyScriptException when anything goes wrong.
But I need in the output from which line the error was caused.
Can I integrate the line from error in MyScriptException?

The Token class has attributes that give the location of the token:
/** The line number of the first character of this Token. */
public int beginLine;
/** The column number of the first character of this Token. */
public int beginColumn;
/** The line number of the last character of this Token. */
public int endLine;
/** The column number of the last character of this Token. */
public int endColumn;

Related

Spring Kafka DefaultErrorHandler infinite loop

Trying to create a non retry-able listener, on deserializataion error, it should just print the suspect message as string and move on.
However, when explicitly setting the DefaultErrorHandler (in an effort to see msg/payload body), it goes into a retry loop. Without setting it, it just prints the exception msg (expected string but got null) and moves on.
I've tried setting Backoff with 0 retries with no luck. Also I'm still unable to see the contents of the suspect message.
#Bean
public ConcurrentKafkaListenerContainerFactory<String, GenericRecord> kafkaListenerCAFMessageContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, GenericRecord> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(getCafKafkaConfig());
factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL);
factory.setConcurrency(consumerConcurrency);
DefaultErrorHandler defaultErrorHandler = new DefaultErrorHandler((record, exception) -> {
// trying to print the payload that doesn't serialize
LOGGER.error(exception.getMessage() + record.value().toString()); // but record.value() is always null
});
#org.springframework.kafka.annotation.KafkaListener(topics = "gcrs_process_events", containerFactory = "kafkaListenerCAFMessageContainerFactory")
public void listenCafMsgs(ConsumerRecord<String, GenericRecord> record, Acknowledgment ack) {...}
The value has to be null so that the deserializer is type safe - for example, if you are using the JsonDeserializer to convert byte[] to a Foo - it is not type safe if it returns a record with a byte[] payload.
See the cause of the ListenerExecutionFailedException - it is a DeserializationException which has the data field.
/**
* Get the data that failed deserialization (value or key).
* #return the data.
*/
public byte[] getData() {
return this.data; // NOSONAR array reference
}

Do I have to post objects seperately with Angular 7 and Asp.net?

I am trying to post objects to my server but the received objects have the value null.
Backend Code:
// Signature
public IActionResult Save(string num, string pat, string token, [FromBody]DataCl data, [FromBody]List<items> listItems)
// EDIT: Added class
public class Object
{
public List<items> listItems { get; set; }
public DataCl data { get; set; }
}
// So new signature
public IActionResult Save(string num, string pat, string token, [FromBody]Test test)
// The value is still null
Frontend Code:
post(num, data, list)
return this.http.post<any>(url,{data, list}, httpOptions).subscribe()
So the parameter num, pat and token are receiving the correct data but the data representing the body are not reciving any data - they are null.
With only one object it is working fine - the correct object was received but with two it does not work anymore but why? Is it something in the frontend code? Or backend?
Check the following article here
Don't apply [FromBody] to more than one parameter per action method.
The ASP.NET Core runtime delegates the responsibility of reading the
request stream to the input formatter. Once the request stream is
read, it's no longer available to be read again for binding other
[FromBody] parameters.
You cannot have two FromBody attributes. The from body is only read once.
{data, list} is one object anyway in javascript. There is no way to Post multiple objects in body, unless they are embedded.
{
object1: {}
object2: {}
}
And in you backend code:
class WrapperObjectResponse {
public Object1 = ...
public Object2 = ...
}
In your new signature, try this:
[Route("save/{num}/{pat}/{token}")]
public IActionResult Save(string num, string pat, string token, [FromBody]Test test)
And call like this:
return this.http.post<any>(url + '/' + num + '/' + pat + '/' + token + '/',{data: {}, list = []}, httpOptions).subscribe()

NotRegistered Error Returned Without RegistrationID

I'm testing out the responses FCM is sending me and I've encountered a problem. FCM will return an error for devices it couldn't send a notification to - but it doesn't say what the registration ID is for the failed push.
public async static void SendPushNotification(string title, string strMessage, string clickLocation, List<string> registrationIDs) {
ResponseContent resp;
using (var sender = new Sender(CloudConfigurationManager.GetSetting("FCMKey")))
{
var json = "{\"data\":{\"title\":\"json message\",\"body\":\"works like a charm!\"},\"registration_ids\":" + JsonConvert.SerializeObject(registrationIDs) + "}";
resp = await sender.SendAsync(json);
}
HandleFCMResponse(resp);
}
private static void HandleFCMResponse(ResponseContent response) {
if (response.MessageResponse.Failure > 0)
{
foreach (Result r in response.MessageResponse.Results)
{
Console.WriteLine(r.RegistrationId);
}
}
Console.WriteLine("resp");
}
Empty registration id:
If you print the result as JSONString, you would see that the result has an array for the errors/responses. The array corresponds to the order of registration tokens specified in your registration_ids parameter.
In your screenshot, it shows 2 results, which is presuming also the count of registration tokens in registration_ids. Both are returning the NotRegistered error. Which means token[0] and token[1] in your list are both invalid tokens.
Possibly similar post: firebase - How to know which registration_id is bad/expired/deleted

How to use IUserIdProvider

My code:
public string GetUserId(IRequest request) {
var token = request.QueryString.Get("token");
// what is it? request.User.Identity.Name;
if (string.IsNullOrWhiteSpace(token)) {
return token;
}
else {
return JsonConvert.SerializeObject(new UserAbility().GetUserByToken(token));
}
}
I need to map the connection with the user using a different identifier.
So i want to get the custom token from the QueryString in this method, but GetUserId doesn't trigger in every reqeust.
And i always get the request.User.Identity.Name is string empty?
This article explains what you need to do.
http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections#IUserIdProvider

How to detect a file-upload examining the http-message?

I want to detect if a Http-Request is a file-upload or not. I know, there are a view things that may indicate a file-upload:
request method: If its POST, there's usually a message-body. But I know, it's also possible to send content withing a GET-request. Is it possible to upload files with a GET-request aswell?
content-type: I guess, the content-type field is usually set, file-upload-message. But whats the content-type of a file-upload?
content-length: The content-length field should be set for a file-upload.
There are a view Questions left:
How can I distinguish a file-upload from a normal html-form post? Does the browser use chunked-encoding for file-uploads? (As far as I know, that would be senseless, but I dont know a lot)
Usually it can be detected by checking whether the request is multipart .
The following example code is c&p from Apache Commons FileUpload library
/**
* Utility method that determines whether the request contains multipart
* content.
*
* #param request The servlet request to be evaluated. Must be non-null.
*
* #return <code>true</code> if the request is multipart;
* <code>false</code> otherwise.
*/
public static final boolean isMultipartContent(
HttpServletRequest request) {
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
if (contentType == null) {
return false;
}
if (contentType.toLowerCase().startsWith(MULTIPART)) {
return true;
}
return false;
}
where MULTIPART is
/**
* Part of HTTP content type header.
*/
public static final String MULTIPART = "multipart/";
Checking for a multipart form submission just gets you through the front door. The problem is, you can have a multipart form submission that does not actually contain a file upload. If you want to know if you actually have an uploaded file, you need to search through the form parts. Like this:
public static int getUploadCount(HttpServletRequest request) throws Exception {
int fileCt = 0;
String[] tokens;
String contentDisp;
String fileName;
// Search through the parts for uploaded files
try{
for (Part part : request.getParts()) {
fileName = "";
contentDisp = part.getHeader("content-disposition");
// System.out.println("content-disposition header= "+contentDisp);
tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
fileName = token.substring(
token.indexOf("=") + 2,
token.length() - 1
);
}
}
if (!fileName.equals("")) {
fileCt++;
}
}
} catch (ServletException ex) {
throw new Exception(ex);
}
return fileCt;
}

Resources