Validators for combobox in Vaadin - java

In text fields I can check how many characters entered by the user, for example:
Field field;
field.addValidator(
new StringLengthValidator(
"WARNING MESSAGE HERE", 6, 20, false));
If the number is not within the range, then warning message is throw. For numeric fields I can check the type:
field.addValidator(new Validator() {
public boolean isValid(Object value) {
try {
float f = Float.parseFloat((String) value);
return true;
} catch (Exception e) {
field.getWindow().showNotification("WARNING MESSAGE HERE");
field.setValue(0);
return false;
}
}
public void validate(Object value)
throws InvalidValueException {
}
});
For the combobox I specify the following:
final ComboBox combobox = new ComboBox("...");
if("someProperty".equals(propertyId)) {
field = combobox;
}
field.setRequired(true);
field.setRequiredError("WARNING MESSAGE HERE");
If I leave it blank, then no warning displayed and form sent to the server. What validator needed for ComboBox?
I would be very grateful for the information. Thanks to all.

What you are looking for is the immediate callback to the server after the user changes anything.
// Fire value changes immediately when the field loses focus
combobox.setImmediate(true);
For that users don't have to wait to get a validation until they commit or do anything else what needs to interact with the server.

I suppose you should explicitly call validate() method:
/**
* Checks the validity of the Validatable by validating the field with all
* attached validators except when the field is empty. An empty field is
* invalid if it is required and valid otherwise.
*
* The "required" validation is a built-in validation feature. If the field
* is required, but empty, validation will throw an EmptyValueException with
* the error message set with setRequiredError().
*
* #see com.vaadin.data.Validatable#validate()
*/
public void validate() throws Validator.InvalidValueException {
if (isEmpty()) {
if (isRequired()) {
throw new Validator.EmptyValueException(requiredError);
} else {
return;
}
}
// If there is no validator, there can not be any errors
if (validators == null) {
return;
}
...
By default Form performs validation:
/**
* Checks the validity of the validatable.
*
* #see com.vaadin.data.Validatable#validate()
*/
#Override
public void validate() throws InvalidValueException {
super.validate();
for (final Iterator<Object> i = propertyIds.iterator(); i.hasNext();) {
(fields.get(i.next())).validate();
}
}

Related

vaadin cross form validation fails as bean not bound

<vaadin.version>22.0.7</vaadin.version>
I have built a vaadin edit form with an attached Save button.
When the user clicks 'Save' I want to validate the form and then save the validated data to the bean.
This works as expected.
The problem comes when I went to add in cross field validation. In this case I want to validate that a start/end date pair are in the correct order.
The problem is that when I add the form validator, vaadin starts throwing exceptions when I call validate.
#Override
public void bindFields(CrudFieldBinder<DiscountCode> binder)
{
binder.forField(this.discountCode).asRequired("Please enter the unique Discount Code.").bind(
DiscountCode::getDiscountCode,
DiscountCode::setDiscountCode);
binder.forField(this.startDate).asRequired("Please enter a Start Date.").bind(DiscountCode::getStartDate,
DiscountCode::setStartDate);
binder.forField(this.endDate).asRequired("Please enter an End Date.")
.bind(DiscountCode::getEndDate,
DiscountCode::setEndDate);
binder.withValidator(new DateRangeValidator());
}
I've tried a few variations all with the same result. Here is the latest iteration:
protected void saveEdits(E currentEntity) {
try
{
binder.writeBean(currentEntity);
}
catch (ValidationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
// this line throws the below error
BinderValidationStatus<E> status = binder.validate();
}
The call to writeBean runs without error but the call to binder.validate() fails with:
java.lang.IllegalStateException: Cannot validate binder: bean level validators have been configured but no bean is currently set
at com.vaadin.flow.data.binder.Binder.validate(Binder.java:2479) ~[flow-data-9.0.8.jar:9.0.8]
at com.vaadin.flow.data.binder.Binder.validate(Binder.java:2463) ~[flow-data-9.0.8.jar:9.0.8]
... EditorFormLayout.saveEdits(EditorFormLayout.java:92) ~[classes/:?]
This seems to suggest that form level validation only works if you make a call to setBean, however my understanding is the call to setBean will result in the form autosaving rather than waiting for the user to click the save button.
I don't believe there is a supported method for doing this.
I've raised a feature request here:
https://github.com/vaadin/platform/issues/2868
Here is my hack that relies on overloading the binder and making the validation method think a bean is bound.
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.data.binder.BinderValidationStatus;
public class MyBinder<E> extends Binder<E>
{
public MyBinder()
{
}
/**
* Apparently when doing cross field validation by calling
* binder.withValidator there is no way to the list of errors back
* due to the following issue.
* https://github.com/vaadin/platform/issues/2868
*
* Which essentially says that unless you are using setBean you can't
* do cross form validation.
*
* This code caches the bean sent to the binder when readBean is called
* and then uses that bean to fake a bound bean during validation.
*
*/
private boolean validating = false;
private E bean;
#Override
public void readBean(E bean)
{
this.bean = bean;
super.readBean(bean);
}
#Override
public void setBean(E bean)
{
throw new RuntimeException("The MyBinder only works with read/writeBean");
}
#Override
public E getBean()
{
if (validating)
{
return bean;
}
/// this call should always return null as setBean hasn't been
// called but we do this try to reduce the likelihood of this overload
// causing problems if someone accicentially uses this class
// when using setBean.
return super.getBean();
}
#Override
public BinderValidationStatus<E> validate()
{
try
{
// force getBean to return a bean during validation.
validating = true;
return super.validate();
}
finally
{
validating = false;
}
}
}```

Generic Methods for Rendering TableColumns in JavaFX

So my application uses a number of TableViews within different FXMLViewControllers to present a number of different JPA Entities. The example below is for JobSupplierParts.
/**
* renderDoubleColumn takes a TableColumn setting its value and type before setting up edit event handling.
* #param column the tableColumn to be set up.
* #param field the name of the field to be mapped to.
* #param methodName the set method name of the field.
*/
protected void renderDoubleColumn(TableColumn<JobSupplierPart, Double> column, String field, String methodName) {
String className = "BiasDB.JobSupplierPart";
column.setCellValueFactory(new PropertyValueFactory<>(field));
column.setCellFactory(TextFieldTableCell.<JobSupplierPart, Double>forTableColumn(new DoubleStringConverter()));
column.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<JobSupplierPart, Double>>() {
#Override
public void handle(TableColumn.CellEditEvent<JobSupplierPart, Double> t) {
JobSupplierPart supplierPart = t.getTableView().getItems().get(t.getTablePosition().getRow());
try {
Class<?> c = Class.forName(className);
Method method = c.getDeclaredMethod(methodName, Double.class);
method.invoke(supplierPart, t.getNewValue());
supplierPart.setTotal(updateItem(supplierPart));
} catch (ClassNotFoundException|NoSuchMethodException|IllegalAccessException|InvocationTargetException ex) {
logger.error("renderDoubleColumn",ex);
} //End try to get method from String.
try {
jobSupplierPartController.edit(supplierPart);
} catch (Exception ex) {
logger.error("renderDoubleColumn",ex);
}
t.getTableView().refresh();
}
} //END Event Handler
); //END SetOnEditCommit.
}
//END renderDoubleColumn
I can call this with:
renderDoubleColumn(discountColumn, "discount", "setDiscount");
BUT - I have to create new methods for each JPA Entity. Is it possible to replace the references to JobSupplierPart such that it becomes a generic method much like I have achieved with the methods? I have tried and alternatives such as T or K but they all returned errrors. The controller can just be passed as a parameter. Or is this a really bad practice/poor performance thing to do?
So I don't know if the Java aficionados will agree with this solution but in response to an answer posted and then deleted shortly after I was able to make the code cleaner. I also moved the set/edit section into a method so now I have:
/**
* renderBigDecimalColumn takes a TableColumn setting its value and type before setting up edit event handling.
* #param column the tableColumn to be set up.
* #param field the name of the field to be mapped to.
*/
private void renderBigDecimalColumn(TableColumn<AccountAsset, BigDecimal> column, String field) {
//Set an observable value for the column
column.setCellValueFactory(new PropertyValueFactory<>(field));
//Set how we want the cell to be rendered
// This line varies for the different cell types e.g. Strings, Bools etc.
column.setCellFactory(TextFieldTableCell.<AccountAsset, BigDecimal>forTableColumn(new BigDecimalStringConverter()));
//Set how we want the cell to be edited including the row update.
column.setOnEditCommit(t -> {
handleEditCommit(t, field);
}); //END SetOnEditCommit.
} //END renderBigDecimalColumn
And my handleEditCommit method looks like:
/** handleEditCommit deals with updating and saving the new data from the table view.
*
* #param t
* #param field
*/
private void handleEditCommit(javafx.scene.control.TableColumn.CellEditEvent<AccountAsset,?> t, String field) {
AccountAsset rowData = t.getTableView().getItems().get(t.getTablePosition().getRow());
//Set the new value.
try {
BeanUtils.setProperty(rowData, field, t.getNewValue());
} catch (IllegalAccessException | InvocationTargetException ex) {
logger.error("handleEditCommit / Setter", ex);
}
//Save the new rowData back to the database.
try {
tableDataController.edit(rowData);
} catch (Exception ex) {
logger.error("handleEditCommit / Edit", ex);
}
}

Spring-boot No thread-bound request found when throw exception on JMS queue listener

I am trying to consume an AWS queue using Spring boot with JMS, and I am having a problem throwing exceptions in my consumer method.
Every time I try to throw a custom exception in my consumer method, to log into an Aspect, the following message is returned:
errorCause=java.lang.IllegalStateException: No thread-bound request
found: Are you referring to request attributes outside of an actual
web request, or processing a request outside of the originally
receiving thread? If you are actually operating within a web request
and still receive this message, your code is probably running outside
of DispatcherServlet/DispatcherPortlet: In this case, use
RequestContextListener or RequestContextFilter to expose the current
request., errorMessage=Error listener queue,
date=2018-06-29T17:45:26.290, type=InvoiceRefuseConsumer]
I have already created a RequestContextListener bean but I did not succeed.
Could someone tell me what might be causing this error?
Here is my code:
Module 1 - Queue consumer
#Service
public class InvoiceRefuseConsumer extends AbstractQueue implements IQueueConsumer{
#Autowired
private InvoiceRefuseService invoiceRefuseService;
#JmsListener(destination = "${amazon.sqs.queue-to-be-consumed}")
#Override
public void listener(#Payload String message) throws ApplicationException {
try {
//Convert the payload received by the queue to the InvoiceFuseParam object
InvoiceRefuseParam param = convertToPojo(message, InvoiceRefuseParam.class);
// Set the type and reason of the refused invoice
param.setType(InvoiceRefuseType.INVOICE_TREATMENT.getId());
if(param.getReasonCode().equals(InvoiceRefuseTypeOperationType.TYPE_OPERATION_INSERT.getDesc())) {
// Persist data information
invoiceRefuseService.save(param);
} else if(param.getReasonCode().equals(InvoiceRefuseTypeOperationType.TYPE_OPERATION_DELETE.getDesc())) {
// Remove refused invoice
invoiceRefuseService.delete(param.getKeyAccess(), param.getType());
}
} catch(Exception e) {
throw new ApplicationException("Error listener queue", e);
}
}
}
Module 2 - Service operations
#Service
public class InvoiceRefuseService {
/**
* automatically initiates the InvoiceRefuseCrud
*/
#Autowired
private InvoiceRefuseCrud invoiceRefuseCrud;
/**
* automatically initiates the SupplierCrud
*/
#Autowired
private SupplierCrud supplierCrud;
/**
* automatically initiates the SequenceDao
*/
#Autowired
private SequenceDao sequenceDao;
/**
* automatically initiates the InvoiceRefuseDao
*/
#Autowired
private InvoiceRefuseDao invoiceRefuseDao;
/**
* automatically initiates the OrderConsumerService
*/
#Autowired
private OrderConsumerService orderConsumerService;
/**
* automatically initiates the InvoiceOrderService
*/
#Autowired
private InvoiceOrderService invoiceOrderService;
/**
* automatically initiates the BranchWarehouseTypeDao
*/
#Autowired
private BranchWarehouseTypeDao branchWarehouseTypeDao;
/**
* Method created to delete a invoice refuse
* #param key
* #param type
* #throws ApplicationException
*/
#Transactional
public void delete(String key, int type) throws ApplicationException {
try {
// Search for the refused invoices
List<InvoiceRefuseModel> lsInvoiceRefuseModel = invoiceRefuseCrud.findBykeyAccessAndType(key, type);
if(ApplicationUtils.isEmpty(lsInvoiceRefuseModel)){
throw new FieldValidationException(getKey("key.notfound"));
}
// Remove refused invoice and cascate with the the scheduling order
invoiceRefuseCrud.deleteAll(lsInvoiceRefuseModel);
} catch (Exception e) {
throw new ApplicationException(getKey("api.delete.error"), e);
}
}
/**
* Method created to save a new invoice refuse
* #param param
* #throws ApplicationException
*/
#OneTransaction
public void save(InvoiceRefuseParam param) throws ApplicationException {
try {
for (String orderNumber : param.getOrderNumbers()) {
// Verify if the invoice refused key already exists
Optional.ofNullable(invoiceRefuseCrud.findBykeyAccessAndType(param.getKeyAccess(), param.getType()))
.filter(invoiceRefuses -> invoiceRefuses.isEmpty())
.orElseThrow(() -> new ApplicationException(getKey("invoice.alread.exists")));
// Convert to model
InvoiceRefuseModel model = convertToSaveModel(param, orderNumber);
// Save data on database
InvoiceRefuseModel result = invoiceRefuseCrud.save(model);
// Associate new refused invoice with the scheduled order
associateInvoiceRefusedToSchedulingOrder(result);
}
} catch (Exception e) {
throw new ApplicationException(getKey("api.save.error"), e);
}
}
/**
* Method creates to associate a refused invoice to the scheduling order
* #param invoiceRefuseModel
* #throws ApplicationException
*/
public void associateInvoiceRefusedToSchedulingOrder(InvoiceRefuseModel invoiceRefuseModel) throws ApplicationException{
// Search for the scheduled order
List<InvoiceOrderModel> lsInvoiceOrderModel = invoiceOrderService.findByNuOrder(invoiceRefuseModel.getNuOrder());
for (InvoiceOrderModel orderModel : lsInvoiceOrderModel) {
// Verify if its a SAP order
boolean isOrderSap = Optional
.ofNullable(branchWarehouseTypeDao.findByIdBranch(orderModel.getNuReceiverPlant()))
.filter(branch -> branch.getNaLoadPoint() != null)
.isPresent();
if (isOrderSap) {
// Update the order status
invoiceOrderService.updateStatus(orderModel);
}
}
}
/**
* Method created to convert from param to model
* #param param
* #param orderNumber
* #return InvoiceRefuseModel
* #throws ApplicationException
*/
private InvoiceRefuseModel convertToSaveModel(InvoiceRefuseParam param, String orderNumber) throws ApplicationException{
OrderParam orderParam = new OrderParam();
orderParam.getLsOrdeNumber().add(orderNumber);
// Search for SAP orders
OrderDataPojo orderSap = Optional.ofNullable(orderConsumerService.findAll(orderParam))
.filter(ordersSap -> ordersSap.getOrders().size() > 0)
.orElseThrow(() -> new ApplicationException(getKey("ordersap.notfound")));
// Convert to model
InvoiceRefuseModel model = new InvoiceRefuseModel();
model.setNuOrder(orderNumber);
model.setCdCompany(BranchMatrixType.MATRIX.getCdCompany());
model.setDsMessage(param.getReasonDescription());
model.setDtIssue(param.getIssueDate());
model.setKeyAccess(param.getKeyAccess());
model.setNuGuid(param.getGuid());
model.setNuInvoice(param.getInvoiceNumber() + param.getInvoiceSerialNumber());
model.setTsCreation(new Date());
model.setNuInvoiceSerial(param.getInvoiceSerialNumber());
model.setNuIssuerPlant(orderSap.getOrders().stream().map(o -> o.getHeader().getIssuerPlant()).findFirst().get());
model.setNuReceiverPlant(orderSap.getOrders().stream().map(o -> o.getHeader().getReceiverPlant()).findFirst().get());
model.setType(param.getType());
model.setCdInvoiceRefuseMessage(param.getReasonCode());
// Passing these fields is required for refused invoices, but they are not received for notes in treatment
if(param.getType().equals(InvoiceRefuseType.INVOICE_REFUSED.getId())) {
model.setIsEnableReturn(BooleanType.getByBool(param.getIsEnableReturn()).getId());
model.setDtRefuse(param.getRefuseDate());
}
// Search for the issuing supplier
SupplierModel supplierModelIssuer = findSupplier(param.getDocumentIdIssuer());
model.setCdSupplierIssuer(supplierModelIssuer.getCdSupplier());
// Search for the receiver supplier
SupplierModel supplierModelReceiver = findSupplier(param.getDocumentIdIssuer());
model.setCdSupplierReceiver(supplierModelReceiver.getCdSupplier());
// Set the primary key
InvoiceRefuseModelId id = new InvoiceRefuseModelId();
id.setCdInvoiceRefuse(sequenceDao.nextIntValue(SequenceName.SQ_INVOICE_REFUSE));
model.setId(id);
return model;
}
/**
* Method created to search for a supplier
* #param documentId
* #return SupplierModel
* #throws ApplicationException
*/
private SupplierModel findSupplier(String documentId) throws ApplicationException{
// Search for the supplier
SupplierModel model = supplierCrud.findTop1ByNuDocumentIdAndCdCompany(documentId, BranchMatrixType.MATRIX.getCdCompany());
if(model == null){
throw new ApplicationException(getKey("supplier.notfound"));
}
return model;
}
/**
* Method created to find a refused invoice and return the result by page
* #param param
* #param pageable
* #return Page<InvoiceRefuseModel>
* #throws ApplicationException
*/
public Page<InvoiceRefuseModel> findRefuseInvoice(InvoiceRefuseFilterParam param, Pageable pageable) throws ApplicationException {
return invoiceRefuseDao.findRefuseInvoice(param, pageable);
}
/**
* Method created to find a refused invoice and return the result by list
* #param param
* #return List<InvoiceRefuseModel>
* #throws ApplicationException
*/
public List<InvoiceRefuseModel> findRefuseInvoice(InvoiceRefuseFilterParam param) throws ApplicationException {
return invoiceRefuseDao.findRefuseInvoice(param);
}
/**
* Method created to find a refused invoice by order number and return the result by list
* #param nuOrder
* #return List<InvoiceRefuseModel>
*/
public List<InvoiceRefuseModel> findByNuOrder(String nuOrder){
return invoiceRefuseDao.findByNuOrder(nuOrder);
}
}

Assess if HttpServletRequest is a valid method call

I think it would be useful to validate if an http request will be valid when using the details in the request to invoke a method.
I do not know of any apache library that has a method that I can use to do this but if there is one please let me know as it will make things a lot easier.
This is the code I have so far but it is really bad and also incomplete. I have left comments inside the code with which parts need to be completed but if something can be improved, please show me how.
package com.example.controller;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println("has correct parameters: " + hasCorrectParameters(request));
request.getRequestDispatcher("index.jsp").forward(request, response);
} catch (Exception ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
}
/*
* This method will check if an HttpServletRequest has the correct parameters required to invoke a method
* ------------------------------------------------
* Potential problems and how they get resolved
* ------------------------------------------------
* 1. Too many parameters for any of the methods in the specified class
* SOLUTION: throw new ExcessiveParametersException().
* 2. Too few parameters for any of the methods in the specified class
* SOLUTION: throw new InsufficientParametersException().
* 3. Inappropriate method being called based on details provided
* SOLUTION: throw new IncorrectDetailsException().
* 4. No way of determining what will be returned and what's expected to be returned
* SOLUTION: ??
* 5. No way of determining which of the parameters in the request should be associated with which of the parameters in the method signature
* SOLUTION: ??
* 6. Parameters of the wrong type being passed to the method
* SOLUTION: Try and use instanceof to determine what the type of the parameter is. If it's not correct then throw new IncorrectDetailsException().
*/
public Boolean hasCorrectParameters(HttpServletRequest request) throws Exception {
//Class information
int methodWithMostParamsInSignature = 2;
int methodWithLeastParamsInSignature = 0;
//Request information
int paramsInRequest = 0;
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String param = (String) parameterNames.nextElement();
System.out.println(param);
paramsInRequest++;
}
/*
* 1. Too many parameters for any of the methods in the specified class
* SOLUTION: throw new ExcessiveParametersException().
*/
if (paramsInRequest > methodWithMostParamsInSignature) {
throw new Exception("Excessive Parameters");
}
/*
* 2. Too few parameters for any of the methods in the specified class
* SOLUTION: throw new InsufficientParametersException().
*/
if (paramsInRequest < methodWithLeastParamsInSignature) {
throw new Exception("Insufficient Parameters");
}
/*
* 3. Inappropriate method being called based on details provided
* SOLUTION: throw new IncorrectDetailsException().
*/
if (request.getParameter("method") != null) {
if (request.getParameter("method").equalsIgnoreCase("isWalking")) {
if (paramsInRequest == 1) {
isWalking(Integer.parseInt(request.getParameter("speed")));
}
if (paramsInRequest == 2) {
if (request.getParameter("lastLocation") != null) {
isWalking(Integer.parseInt(request.getParameter("speed")), request.getParameter("lastLocation"));
}
}
}
}
/*
* 4. No way of determining what will be returned and what's expected to be returned
* SOLUTION: Not sure how to resolve
*/
/*
* 5. No way of determining which of the parameters in the request should be associated with which of the parameters in the method signature
* SOLUTION: Not sure how to resolve
*/
/*
* 6. Parameters of the wrong type being passed to the method
* SOLUTION: Try and use instanceof to determine what the type of the parameter is. If it's not correct then throw new IncorrectDetailsException().
*/
//Parameters are always a String so I'm not sure how to check if it's a valid variable for the method signature
return true;
}
public Boolean isWalking(Integer speed) {
return speed == 2;
}
public Boolean isRunning(Integer speed) {
return speed == 5;
}
public String isWalking(Integer speed, String lastLocation) {
if ((speed == 2) && (lastLocation.equalsIgnoreCase("nearby"))) {
return "Yup, you're walking";
}
return "";
}
}
You should use reflection to call the methods that you want to call. This will give a runtime exception when the wrong amount of parameters is provided.
Definition:
java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) {
// ...
} catch (NoSuchMethodException e) {
// ...
}
Then to invoke:
try {
method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
Api of Method: http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html

How do I recompile with -Xlint? Jgrasp

My program appears to work to my liking. However, when I compile it I get this message:
Note: Program.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
What can I do to identify the unsafe operations with -Xlint, or what in program is causing this message? I'm thinking it has something to do with my Node class..?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
* An application that reads from a file, enters/deletes in queue and writes output to the file
*/
public class Program {
/**
* Driver code to test class
*
* #param arguments
* Commandline arguments. 1st argument is input file and 2nd argument is output file
* #throws IOException
*/
public static void main(String[] arguments) throws IOException {
//Queue Object
MyQueue<String> queue= (new MyQueue<String>());
String name;
//reading file
read(queue,arguments[0]);
String[] array = { "Offer Person", "Poll Person", "Peek person","Display Queue", "Exit Program"};
int choice = 0;
// display loop
while (choice != array.length-1) {
choice = JOptionPane.showOptionDialog(null, // put in center of screen
"Press a Button", // message to user
"Queue(Line) of People", // title of window
JOptionPane.YES_NO_CANCEL_OPTION, // type of option
JOptionPane.QUESTION_MESSAGE, // type of message
null, // icon
array, // array of strings
array[array.length - 1]); // default choice (last one)
if(choice==0)
{
//inserting the new name in queue
name=JOptionPane.showInputDialog(null,"Enter Person's name","Input");
queue.offer(name);
}
else if(choice==1){
//Display and remove the name which is at front of line
JOptionPane.showMessageDialog(null, queue.poll() + " is next in line");
}
else if(choice==2){
//Display name which is at front of line
JOptionPane.showMessageDialog(null, queue.peek() + " is front of the line");
}
else if(choice==3){
//Dispay all the list
JOptionPane.showMessageDialog(null, queue.toString());
}
//JOptionPane.showMessageDialog(null, "Your pressed button #" + choice);
}
//calling writing function
write(queue, arguments[1]);
}// end of main()
/**
* Reads a file
* #param queue
* #param file_name name of file
*/
public static void read(QueueInterface<String> queue, String file_name) throws IOException{
try
{
String name;
//creating a buffer reader to read
BufferedReader br= new BufferedReader(new FileReader(file_name));
while((name=br.readLine()) != null){
//putting in the queue
queue.offer(name);
}
//closing buffer reader
br.close();
}
catch(Exception ex)
{
System.err.println(ex.getMessage());
}
}
/**
* Writes the contents of LinkedQueue to the output file at the ned of program
* #param queue QueueInterface methods
* #param file_name name of file
*/
public static void write(QueueInterface<String> queue, String file_name) throws IOException{
try
{
String name;
//creating a buffer writer to write
BufferedWriter bw= new BufferedWriter(new FileWriter(file_name));
while((name=queue.poll()) != null){
//writin in file
bw.write(name);
bw.newLine();
}
//closing buffer
bw.close();
}
catch(Exception ex)
{
System.err.println(ex.getMessage());
}
}
}// end of class
/**
* Interface to be implemented by LinkedQueue
*/
interface QueueInterface<String>
{
public boolean empty();
public boolean offer(String element);
public String poll();
public String peek();
}
class Node<String>
{
private String data;
private Node nextNode;
public Node(String dataObject, Node nextNodeObject)
{
this.data=dataObject;
this.nextNode=nextNodeObject;
}
/**
* Gets the next node
* #return next node
*/
public Node getNext()
{
return nextNode;
}
/**
* Sets the next node of the current node
* #param nextNodeObject next node to be set as next to the current node
*/
public void setNext(Node nextNodeObject)
{
nextNode=nextNodeObject;
}
/**
* Sets data of the current node
* #param dataObject data to be inserted in new node
*/
public void setData(String dataObject)
{
this.data=dataObject;
}
/**
* Gets data of the current node
* #return data of the node
*/
public String getData()
{
return this.data;
}
}
class LinkedQueue implements QueueInterface<String>
{
protected Node<String> lastNode=null;
LinkedQueue() {
}
/**
* Checks if the queue is empty
* #return true if empty, false if not empty
*/
public boolean empty() {
if(lastNode==null)
{
return true;
}
else
return false;
}
/**
* Inserts new node in the queue
* #param element data to be inserted in new node
* #return true on success
*/
public boolean offer(String element)
{
Node<String> newLastNode = new Node<String>(element,null);
//If the LinkedQueue is empty, add the node to the last and point next to itself
if(empty())
{
newLastNode.setNext(newLastNode);
}
else
{
// Adding to the front of queue and updating next of the last node
newLastNode.setNext(lastNode.getNext());
lastNode.setNext(newLastNode);
}
lastNode=newLastNode;
return true;
}
/**
* Removes the first node and returns it
* #return data at first node
*/
public String poll()
{
// If queue is empty then return null
if(empty())
return null;
else
{
Node<String> frontNode = lastNode.getNext();
//Check if there will be no node left after polling this one
if (frontNode == lastNode)
{
lastNode = null;
}
else //Remove the first node and update next of the last node
{
lastNode.setNext(frontNode.getNext());
}
return frontNode.getData();
}
}
/**
* Returns data of the first node without removing it from the queue
* #return data at first node
*/
public String peek()
{
if (empty())
{
return null;
}
else
{
Node<String> frontNode = lastNode.getNext();
return frontNode.getData();
}
}
}
class MyQueue<String> extends LinkedQueue{
/**
* Constructor
*
*/
public MyQueue()
{
super();
}
/**
* Returns a string representation of the object
*
* #return a name on different lines
*/
public java.lang.String toString()
{
// create a variable to return
java.lang.String toReturn = "";
// Traversing the list
Node<String> frontNode = lastNode.getNext();
if(empty()) //If queue is empty
return "";
else if(frontNode==lastNode) //If only one elemtn
{
return frontNode.getData().toString();
}
else //More than one element in the queue
{
while(frontNode != lastNode)
{
toReturn=toReturn+frontNode.getData()+"\n";
frontNode=frontNode.getNext();
}
toReturn= toReturn+frontNode.getData()+"\n"; //Appending data of last node because it will be missed in the loop
}
return toReturn;
}
}
If you're compiling on the command line (i.e. javac Program.java), you just have to add the -Xlint:unchecked parameter to have it print out the warnings for you:
javac Program.java -Xlint:unchecked
That should point out the problem spots to you. But, as #DavidWallace mentioned in a comment, you should consider revising your use of generics to be a bit more clear -- that might reveal your issue to you even without using the -Xlint parameter.
If your classes should really only deal with Strings, then you don't need to include a type parameter at all (right now, in your code, <String> is a type parameter, representing the type you pass in when you use the class -- it doesn't signify that it has to be java.lang.String -- that's why #DavidWallace suggested you use T instead). Here's a good tutorial if you want to brush up on how to use Generics.
Assuming that using "String" as the type parameter is not what causes the actual message (or even if it does), with a quick glance I see:
Node<String> frontNode = lastNode.getNext();
but getNext() returns Node instead of Node<String> (should be Node<T> once you fix the type parameter name).
In jGRASP you can add flags for various commands using "Settings" > "Compiler Settings" > "Workspace" (or "Project..." or "File"). Just add "-Xlint" for "Flags or Args" for the "Compile" command for the Java language.
in jGrasp, the option is under the Settings menu item. Go to Settings-> File/Workspace/Project (pick whichever is applicable to you), and then on the Compiler tag, pick the Flags/Args tab, and then click the box next to Compile and enter -Xlint:unchecked into the text box. Click apply, and on your next build, you will get the messages on what was unchecked.
As others have pointed out, this warning is raised because you are using a raw form of a generic class rather than providing a type parameter to it. -Xlint:unchecked will show you where in your code you did that.
In the build.gradle add
allprojects {
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
}
}
}

Categories

Resources