Changing default limit in Vaadin 8 lazy loading with grid - java

I have implemented lazy loading in Vaadin 8 with grid implementation.
My backend runs on AWS Lambda which has a limit of 6 MB in response object.
The lazy loading implementation gives default limit(40) to server which makes my program crash giving error as "body too large".
I want to make changes in default limit of lazy loading in Vaadin.
Below is my code snippet:
grid.setDataProvider((sortorder, offset, limit) -> {
try {
return billingClient.getInvoiceListByCriteria(criteria, (long) offset, (long) limit).stream();
} catch (Exception e) {
logger.error("Exception while getInvoiceListByCriteria", e);
return null;
}
}, () -> {
try {
totalInvoices = billingClient.getCountInvoiceListByCriteria(criteria).longValue();
Integer count = totalInvoices.intValue();
if (count == 0)
Notification.show("No Invoices found.", Notification.Type.HUMANIZED_MESSAGE);
return count;
} catch (Exception e) {
logger.error("Error occured while getting count calling getCountInvoiceListByCriteria", e);
Notification.show("Error while getting count", Notification.Type.ERROR_MESSAGE);
return null;
}
});

Thats strange that 40 rows are larger than 6MB.
Never tried it but you can use grid.getDataCommunicator().setMinPushSize(size) to set the minimum number of items. It's initialized with 40 so I guess you can lower this to prevent your response from getting to large. But the "min" in the name suggests that also other factors may influence it, so you need to test it thoroughly.

The problem is resolved by manually changing the value of limit.
grid.setDataProvider((sortorder, offset, limit) -> {
try {
limit=20;
return billingClient.getInvoiceListByCriteria(criteria, (long) offset, (long) limit).stream();
} catch (Exception e) {
logger.error("Exception while getInvoiceListByCriteria", e);
return null;
}
}, () -> {
try {
totalInvoices = billingClient.getCountInvoiceListByCriteria(criteria).longValue();
Integer count = totalInvoices.intValue();
if (count == 0)
Notification.show("No Invoices found.", Notification.Type.HUMANIZED_MESSAGE);
return count;
} catch (Exception e) {
logger.error("Error occured while getting count calling getCountInvoiceListByCriteria", e);
Notification.show("Error while getting count", Notification.Type.ERROR_MESSAGE);
return null;
}
});
offset is adjusted according to limit I have set.

Related

Continue the program execution in multiple try-catch statements scenario after catching exception

I have the following code running in my project:
HashMap<String, DeviceData> deviceMap = getAllDevices();
int status = 0;
DeviceHandle devHandle = null;
for (LicenseData licenseData:listLicenses) {
Map<String, String> licenseMap = licenseData.getLicenseKeyValues();
if ((licenseMap != null && !licenseMap.isEmpty())) {
String keyDecrypt = licenseMap.get("key");
Date expiryDate = new Date(Long.parseLong(licenseMap.get("expiryDate")));
boolean allowForeign = Boolean.parseBoolean(licenseMap.get("allowForeign"));
String ipDecrypt = licenseMap.get("ipAddress");
if (expiryDate.compareTo(new Date()) > 0 || keyDecrypt.equals(licenseData.getKey().getCurrentValueAsString()))
{
try {
DeviceData device = deviceMap.get(ipDecrypt);
devHandle = (DeviceHandle)device.getHandle();
if(device != null && devHandle != null) {
deviceMap.remove(ipDecrypt, device);
System.out.println("After deletion device map.");
System.out.println(deviceMap);
createUser(devHandle);
try {
if (allowForeign) {
Process pr = Runtime.getRuntime().exec(SomeOperation);
status = pr.waitFor();
if (status == 0)
//Debug Statement
else
//Error Debug Statemnt
deleteUser(devHandle);
}
else {
Process pr = Runtime.getRuntime().exec(SomeOperation);
status = pr.waitFor();
if (status == 0)
//Debug Statement
else
//Error Debug Statement
deleteUser(devHandle);
}
} catch(Exception e) {
//Exception statement
deleteUser(devHandle);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Explanation: I have a list of licenses for my application in listLicenses. All the devices present in the server are in deviceMap. For each license, I am decrypting it and getting the values. If license for a device is present, I get a handle on that device and doing some operations.
The issue is:
If I am not able to get a handle on device(getHandle()), or if I am not able to create a user after getting the device handle(createUser()), an exception is thrown. These methods are very hierarchical, i.e I am calling them from here, they are in another class throwing own exceptions and for their operation, they call other methods.
If there are three devices in the map, and three licenses, and if for the first one I am not able to get a handle or create a user, device is removed from deviceMap but no further execution happens i.e. for the next two devices.
If exception occurs for on device, I want to continue the exception for other two devices. I tried using return but couldn't get it to work.
Please help.Also, please forgive for the syntax and if any mismatch is there in the code.
Make use of first try's catch block.
This is how I handled when I faced same kind of situation.
catch (Exception exp) {
if (exp instanceof NullPointerException) {
log.info"Invalid/ Inactive ");
} else if (exp instanceof NonUniqueResultException) {
log.info("Multiple records existed");
} else {
exp.printStackTrace();
errorMsgs.append("Unexpected Error Occured. Please contact Admin.");
}
}

Solr Trigger Optimize And Check Progress From Java Code

From this topic there are two ways to trigger solr optimize from Java code. Either sending an http request, or using solrj api.
But how to check the progress of it?
Say, an api which returns the progress of optimize in percentage
or strings like RUNNING/COMPLETED/FAILED.
Is there such an api?
Yes, optimize() in solrj api is a sync method. Here is what I used to monitor the optimization progress.
CloudSolrClient client = null;
try {
client = new CloudSolrClient(zkClientUrl);
client.setDefaultCollection(collectionName);
m_logger.info("Explicit optimize of collection " + collectionName);
long optimizeStart = System.currentTimeMillis();
UpdateResponse optimizeResponse = client.optimize();
for (Object object : optimizeResponse.getResponse()) {
m_logger.info("Solr optimizeResponse" + object.toString());
}
if (optimizeResponse != null) {
m_logger.info(String.format(
" Elapsed Time(in ms) - %d, QTime (in ms) - %d",
optimizeResponse.getElapsedTime(),
optimizeResponse.getQTime()));
}
m_logger.info(String.format(
"Time spent on Optimizing a collection %s :"
+ (System.currentTimeMillis() - optimizeStart)
/ 1000 + " seconds", collectionName));
} catch (Exception e) {
m_logger.error("Failed during explicit optimize on collection "
+ collectionName, e);
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
throw new RuntimeException(
"Failed to close CloudSolrClient connection.", e);
}
client = null;
}
}

executor.invokeAll() lambda body does not return

The idea is for some kind of compiler, and I'm trying to implement a fork statement that starts another thread.
The code:
List < Callable < CustomClass >> callList = lista.stream().map(p -> (Callable < CustomClass > )() -> p.oneStep()).collect(Collectors.toList()); //here I just prepared the list of callables
List < CustomClass > newPrgs;
try {
newPrgs = executor.invokeAll(callList).stream().map(future -> {
try {
return future.get();
} catch (Exception e) {
e.printStackTrace();
}
}
/here it indicates the error/.filter(p -> p != null).collect(Collectors.toList());
} catch (InterruptedException e) {
throw new CustomException(e.getMessage());
}
The error is: lambda body is neither value nor void compatible. I tried all sort of changes and tricks, and no result. Some help please?
The problem is in the definition of your lambda...
{
try{
return future.get();
}
catch (Exception e){
e.printStackTrace();
}
}
Now, this is fine for the happy path, which just returns the response from the future, but in the event of an exception this lambda will not return a value. You need to return something from the exception case, or throw a RuntimeException. Which to do depends on your use case - an exception will stop the entire stream from processing, but a null or default value could risk polluting your stream.
Also, it's generally best not to catch Exception - keep the catch down to the minimal set necessary / that you can handle.
The exception-throwing form would look like...
{
try{
return future.get();
}
catch (InterruptedException | ExecutionException e){
e.printStackTrace();
throw new RuntimeException(e)
}
}
Take a look at your lambda's body:
try {
return future.get(); // This branch returns a value
} catch (Exception e) {
e.printStackTrace(); // No return statement here
}
// No return statement here either
So your lambda can neither be translated into a void method, not into a method with a return value.
You should have a return value either at the catch or at the end of the lambda body.

How to throw an exception if parsing with Long.parseLong() fails?

I am trying to write some kind of a stack calculator.
Here is a part of my code where I am handling a push command. I want to push integers only, so I have to get rid of any invalid strings like foobar (which cannot be parsed into integer) or 999999999999 (which exceeds the integer range).
strings in my code is a table of strings containing commands like POP or PUSH, numbers, and random clutter already split by white characters.
Main problem:
I've got difficulties with throwing an exception for long parseNumber = Long.parseLong(strings[i]); - I don't know how to handle the case, when strings[i] cannot be parsed into a long and subsequently into an integer.
while (i < strings.length) {
try {
if (strings[i].equals("PUSH")) {
// PUSH
i++;
if (strings[i].length() > 10)
throw new OverflowException(strings[i]);
// How to throw an exception when it is not possible to parse
// the string?
long parseNumber = Long.parseLong(strings[i]);
if (parseNumber > Integer.MAX_VALUE)
throw new OverflowException(strings[i]);
if (parseNumber < Integer.MIN_VALUE)
throw new UnderflowException(strings[i]);
number = (int)parseNumber;
stack.push(number);
}
// Some options like POP, ADD, etc. are omitted here
// because they are of little importance.
}
catch (InvalidInputException e)
System.out.println(e.getMessage());
catch (OverflowException e)
System.out.println(e.getMessage());
catch (UnderflowException e)
System.out.println(e.getMessage());
finally {
i++;
continue;
}
}
Long.parseLong(String str) throws a NumberFormatException if the string cannot be parsed by any reason. You can catch the same by adding a catch block for your try, as below:
catch ( NumberFormatException e) {
System.out.println(e.getMessage());
}
No need to worry. Long.parseLong() throws a NumberFormatException if it got other than a Number.
After reading your comments and answers I was able to come up with such a solution (this code is embedded inside the outside try-catch.)
if (strings[i].equals("PUSH")) {
// PUSH
i++;
if (strings[i].length() > 10) {
throw new OverflowException(strings[i]);
}
try{
parseNumber = Long.parseLong(strings[i]);
if (parseNumber > Integer.MAX_VALUE) {
throw new OverflowException(strings[i]);
}
if (parseNumber < Integer.MIN_VALUE) {
throw new UnderflowException(strings[i]);
}
number = (int)parseNumber;
stack.push(number);
}
catch (NumberFormatException n){
throw new InvalidInputException(strings[i]);
}
}

java's executeUpdate is not working properly

I have the following java code:
if (ps.executeUpdate() != 1)
{
// Error - did not insert one row
String err = "insert unable to insert LocalUsage data: " + usg.toString();
Logger.log(err, _MODULE_CLASS, Logger.DEBUG);
throw new DaoException(err);
}
The problem if the query had a foreign key exception, then it will be thrown but it will never get to inside the if. what should I do so that it will get inside the if and output the log I have?
The problem is that this if condition is inside a try catch block, and it is going to the catch and never enters to the if condition.
executeUpdate() might throw an SQLException, as is described in its API documentation. You might want to catch that exception.
int count;
try {
count = ps.executeUpdate();
} catch (SQLException e) {
throw new DaoException("Exception while executing update: " + e.getMessage());
}
if (count != 1) {
// ...
}
As the docs states executeUpdate() may throw an exception so your code flow will fail and you will not be able to do any processing afterwards incase your exception handling is not proper.
Which I think is happening in your code right now.
While doing database call I would suggest you do it like this:
int operationStatus;
try {
operationStatus = ps.executeUpdate();
} catch(SQLException exp) {
final String message = "SQL Exception while calling executeUpdate()";
logger.error(message, exp);
throw new DAOException(message, logger);
} catch(Exception exp) {
final String message = "Exception while calling executeUpdate()";
logger.error(message, exp);
throw new DAOException(message, logger);
} finally {
//you may wish to clean up resources if they are not going to be used after this point.
}
if(operationStatus < 0) {
//Next steps
}

Categories

Resources