Getting a null result on my GWT Project - java

I'm using Eclipse + GWT to make a call to iTunes API. This is the URI I want to get information:
itunes.apple.com/es/rss/topsongs/limit=25/json
The console isn't throwing me any error, and neither GWT Development Console.
This is the part of the code I think is making ChartSearch null:
(Each Pastebin link is a Java class)
public class ITunesAPI implements EntryPoint {
private Button searchButton = new Button("Search");
private TextBox searchField = new TextBox();
private HorizontalPanel searchPanel = new HorizontalPanel();
private Label statusLabel = new Label();
private final iTunesServiceAsync iTunesService = GWT.create(iTunesService.class);
public void onModuleLoad() {
searchField.setText("PaĆ­s");
searchPanel.add(searchField);
searchPanel.add(searchButton);
searchPanel.add(statusLabel);
// Add panel to the page
RootPanel.get("form").add(searchPanel);
// Focus the cursor on the name field when the app loads
searchField.setFocus(true);
searchField.selectAll();
searchButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
statusLabel.setText("Searching...");
final String pais = searchField.getText();
RootPanel.get("iTunes").clear();
try{
iTunesService.getChart(pais, new AsyncCallback<ChartSearch>(){
public void onSuccess(ChartSearch result) {
statusLabel.setText("Exito");
showChart(pais, result);
}
public void onFailure(Throwable caught) {
statusLabel.setText("Error");
}
});
}catch(Exception e){
statusLabel.setText("Error (try/catch): " + e.getMessage());
}
}
});
}
private void showChart(String pais, ChartSearch result) {
String output="<fieldset>";
output += "<legend>" + pais + " Top 25 Chart</legend>";
if (result != null) {
for (Entry a : result.getFeed().getEntry()) {
output +="<span>" + a.getTitle().getLabel() + "</span><br/>";
}
}else
output="<span>No results</span>";
output +="</fieldset>";
HTML albums = new HTML(output);
RootPanel.get("iTunes").add(albums);
}
public class iTunesServiceImpl extends RemoteServiceServlet implements iTunesService{
String country;
public ChartSearch getChart(String country) {
this.country = country;
ClientResource cr = new ClientResource("https://itunes.apple.com/" + country + "/rss/topsongs/limit=25/json");
ChartSearch message = cr.get(ChartSearch.class);
return message;
}
If you need the rest of the project, or some specific class, tell me, I'll be glad to upload it.
Thanks,

Related

Spring boot app with Vaadin UI constantly refreshing screen

I have a boot app that I am adding some crud screens to. I decided to use Vaadin and it seems to work great until I deploy it to a multi-nodal production environment.
Once in the prod environment the screens constantly refresh for no apparent reason. For example there is a grid in one screen that when a row is clicked a dialog pops up that shows item details. but as soon as the dialog pops up the page refreshes numerous times.
This forum thread here https://vaadin.com/forum/thread/17586129/routerlayout-causing-page-refresh is an example of the same layout I am using and describes a very similar issue.
I have a base abstract class that extends VerticalLayout and all of the concrete classes extend this base abstract class. Each concrete class defines its own route and use a common layout class.
I have reached out on gitter, vaadin forum and opened a bug in github but no one from Vaadin want to respond to anything as far as I can tell.
Here are the versions of everything I am using:
Vaadin Flow version: 14
Java version: 12.0.1+12
OS version: Mac 10.14.5
Browser version: Fire Fox 70.0.1, Chrome 78.0.3904.97
Code snippets from my implementation:
Main View
#Slf4j
#RoutePrefix("v1/crud")
#Theme(value = Material.class, variant = Material.DARK)
public class MainView extends Div implements RouterLayout {
private H1 h1 = new H1("Vaadin Crud UI");
private HorizontalLayout header = new HorizontalLayout(h1);
private Div content = new Div();
private ApplicationContext context;
#Inject
public MainView(ApplicationContext context) {
this.context = context;
setSizeFull();
h1.setWidthFull();
content.setWidthFull();
header.setWidthFull();
header.setAlignItems(FlexComponent.Alignment.CENTER);
VerticalLayout navigationBar = new VerticalLayout();
navigationBar.setWidth("25%");
navigationBar.add(createNavigationButton("Home", VaadinIcon.HOME, ReportTab.class));
navigationBar.add(createNavigationButton("Batch Search", VaadinIcon.SEARCH, BatchSearchTab.class));
... a bunch more buttons
HorizontalLayout layout = new HorizontalLayout(navigationBar, content);
layout.setWidthFull();
VerticalLayout page = new VerticalLayout(header, layout);
page.setWidthFull();
add(page);
}
#Override
public void showRouterLayoutContent(HasElement hasElement) {
if (hasElement != null) {
Element newElement = hasElement.getElement();
if (newElement != null) {
content.removeAll();
content.getElement().appendChild(newElement);
}
}
}
private Button createNavigationButton(String caption, VaadinIcon icon, Class<? extends BaseEditor> editor) {
Button button = new Button(caption, icon.create());
button.addClickListener(event -> UI.getCurrent().navigate(editor));
button.addThemeVariants(ButtonVariant.MATERIAL_CONTAINED);
button.getStyle().set("background-color", "#00819D");
button.setWidthFull();
return button;
}
}
Base Component:
#Slf4j
#Data
#SpringComponent
#UIScope
public abstract class BaseEditor<P, B> extends VerticalLayout {
private final RememberMeService rememberMe;
private final P businessProcess;
protected Binder<B> binder;
protected Dialog editDialog = new Dialog();
protected Button save = new Button("Save", VaadinIcon.CHECK.create());
protected Button close = new Button("Close", VaadinIcon.EXIT.create());
protected Button delete = new Button("Delete", VaadinIcon.TRASH.create());
protected B bean;
private ChangeHandler changeHandler;
private boolean proceed = true;
public BaseEditor(P businessProcess, RememberMeService rememberMe) {
this.rememberMe = rememberMe;
this.businessProcess = businessProcess;
save.addClickListener(e -> save());
delete.addClickListener(e -> delete());
}
public abstract void delete();
public abstract void save();
protected abstract Component getContent();
protected void edit(B e) {
bean = e;
editDialog.open();
getBinder().setBean(e);
}
protected void initEditorPanel(Component... components) {
HorizontalLayout actions = new HorizontalLayout(save, close, delete);
VerticalLayout data = new VerticalLayout(components);
data.add(actions);
editDialog.removeAll();
editDialog.add(data);
getBinder().bindInstanceFields(this);
close.addClickListener(e -> editDialog.close());
}
public interface ChangeHandler {
void onChange();
}
void setChangeHandler(ChangeHandler h) {
changeHandler = h;
}
void errorDialog(String message) {
final Button close = new Button("Close", VaadinIcon.CLOSE.create());
H3 h3 = new H3(message);
final Dialog errorDialog = new Dialog(h3, close);
errorDialog.open();
close.addClickListener(e -> errorDialog.close());
}
BaseEditor filter(Predicate<B> predicate) {
Objects.requireNonNull(predicate);
proceed = predicate.test(bean);
return this;
}
void buttonConsumer(Consumer<B> consumer) {
if (!proceed) {
proceed = true;
return;
}
try {
consumer.accept(bean);
} catch (Exception e) {
errorDialog(e.getMessage());
} finally {
editDialog.close();
getChangeHandler().onChange();
}
}
void either(Consumer<B> whenTrue, Consumer<B> whenFalse) {
try {
if (proceed) {
whenTrue.accept(bean);
} else {
whenFalse.accept(bean);
}
} catch (Exception e) {
errorDialog(e.getMessage());
} finally {
proceed = true;
editDialog.close();
getChangeHandler().onChange();
}
}
}
Concrete Component:
#Slf4j
#Route(value = "search/batch", layout = MainView.class)
public class BatchSearchTab extends BaseEditor<BatchService, Batch> {
private TextField searchField1;
private TextField searchField2;
public BatchSearchTab(BatchService businessProcess, RememberMeService rememberMe) {
super(businessProcess, rememberMe);
binder = new Binder<>(Batch.class);
save.setIcon(VaadinIcon.REPLY.create());
save.setText("Replay");
delete.setIcon(VaadinIcon.CLOSE.create());
delete.setText("Cancel");
getContent();
}
#Override
public void delete() {
buttonConsumer(b -> getBusinessProcess().cancelBatch(b.getBatchId(), b.getUserAgent()));
}
#Override
public void save() {
filter(b -> b.isReplayable()).buttonConsumer(b -> getBusinessProcess().buildAndSendFile((getBean())));
}
#Override
public void edit(Batch batch) {
HorizontalLayout actions = new HorizontalLayout();
H2 h2 = new H2();
if (batch.isReplayable()) {
h2.setText("Would you like to replay the following.");
actions.add(save, delete, close);
} else {
h2.setText("This record is not eligible for replay.");
actions.add(close);
}
Label batchId = new Label("Correlation Id: " + batch.getBatchId());
Label txnCount = new Label("Transaction Count: " + batch.getTotalTxns());
Label txnAmount = new Label("Total: " + batch.getTotalBatchAmount());
VerticalLayout data = new VerticalLayout(h2, batchId, txnCount, txnAmount, actions);
data.add(actions);
editDialog.removeAll();
editDialog.add(data);
close.addClickListener(e -> editDialog.close());
editDialog.open();
getBinder().setBean(batch);
}
#Override
protected Component getContent() {
final H2 h2 = new H2("Locate Batches");
searchField1 = new TextField("Batch Code");
searchField2 = new TextField("User Agent");
searchField2.addKeyPressListener(Key.ENTER, e -> keyPressListener());
Button searchBtn = new Button("Search", VaadinIcon.SEARCH.create());
HorizontalLayout search = new HorizontalLayout(searchField1, searchField2);
searchBtn.addClickListener(e -> {
search(searchField1.getValue(), searchField2.getValue());
});
add(h2, search, searchBtn);
return this;
}
private void search(String code, String userAgent) {
log.info("Searching {} and {}", code, userAgent);
List<Batch> batches =
getBusinessProcess().getBatchesForUserAgent(code, userAgent, 60);
log.info("Found {} batches", batches.size());
if (batches.size() > 0) {
buildGrid(batches, "BatchId", "totalTxns", "totalBatchAmount", "status");
} else {
errorDialog("No Records found for criteria");
}
}
private void keyPressListener() {
String code = StringUtils.isNotBlank(searchField1.getValue()) ? searchField1.getValue() : null;
if (StringUtils.isNotBlank(searchField2.getValue())) {
search(code, searchField2.getValue());
}
}
private void buildGrid(Collection<Batch> records, String... columns) {
Component result;
if (records.size() == 0) {
result = new Label("NO REPORT DATA AVAILABLE.");
} else {
final Grid<Batch> grid = new Grid<>(Batch.class);
grid.setHeightByRows(records.size() < 10);
grid.setColumns(columns);
grid.setItems(records);
grid.setWidthFull();
grid.asSingleSelect().addValueChangeListener(l -> Optional.ofNullable(l.getValue()).ifPresent(this::edit));
result = grid;
}
if (getComponentCount() < 3) {
add(result);
} else {
replace(getComponentAt(2), result);
}
}
private void loadData(String code, String userAgent) {
if (StringUtils.isNotBlank(code)) {
search(null, userAgent);
} else {
search(code, userAgent);
}
}
}
Disclaimer: some further fact finding happended via IRC
The answer to the question is related to OP running multiple instances of the application behind an round robin load ballancer. The clients hit random servers and therefor had no session running there.
The solution to this is having a shared session store and ideally have the load ballancer dispatch on existing session, so "hot" backend servers get hit.

Drag Cursor not showing on OSX

We have a large Java app that is used on both Windows and OSX.
We do custom Drag and Drop between 2 of our JTables.
On Windows, this works perfectly. The custom cursor is displayed as you drag over the target JTable.
On the Mac, the custom cursor is never displayed. Instead a gray rectangle (border only) is displayed when you start dragging. This rectangle is the width of the table column, and the height of the table. Our logging is showing that the dragOver() and dropActionChanged() methods are getting called, and we are setting the custom cursor. It just never gets displayed.
If I disable our custom cursor code, the same box is displayed - but it has the Circle/slash icon in the middle as well.
I want to get rid of the weird box, and display the custom cursor.
Excerpts from the code:
private class FileTransferHandler extends TransferHandler {
private static final long serialVersionUID = 1L;
private final Logger log = LogManager.getLogger();
private final CursorDragSourceListener dragSourceListener = new CursorDragSourceListener();
// Left out the Drop handling code that was here
#Override
public int getSourceActions( final JComponent c) {
log.debug("FileTransferHandler.getSourceAction: ");
return COPY | MOVE;
}
#Override
protected Transferable createTransferable( final JComponent c) {
log.debug("FileTransferHandler.createTransferable:");
List<iFilePage> pages = new ArrayList<iFilePage>();
// Left out the code that builds the pages list
DragSource.getDefaultDragSource().addDragSourceListener(dragSourceListener);
dragSourceListener.setCursorChoice(pages.size() == 1);
return new FilePageTransferable(pages);
}
#Override
protected void exportDone( final JComponent c,
final Transferable t,
final int action) {
log.debug("FileTransferHandler.exportDone: {}", action, t);
tblFixed.getSelectionModel().clearSelection();
DragSource.getDefaultDragSource().removeDragSourceListener(dragSourceListener);
return;
}
}
private static class CursorDragSourceListener implements DragSourceListener {
private Cursor singlePage = null;
private Cursor multiPage = null;
private Cursor badSinglePage = null;
private Cursor useCursor = null;
private boolean useSingle = false;
public CursorDragSourceListener() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
URL url;
String name;
Image img;
url = FileUtils.getResourceURL("/images/page.png");
name = "DragPage";
img = toolkit.createImage(url);
singlePage = toolkit.createCustomCursor(img, new Point(16, 16), name);
url = FileUtils.getResourceURL("/images/badpage_stack.png");
name = "DragBadPage";
img = toolkit.createImage(url);
badSinglePage = toolkit.createCustomCursor(img, new Point(16, 16), name);
url = FileUtils.getResourceURL("/images/page_stack.png");
name = "DragPageStack";
img = toolkit.createImage(url);
multiPage = toolkit.createCustomCursor(img, new Point(16, 16), name);
return;
}
public void setCursorChoice( final boolean single) {
log.debug("CursorDragSourceListener.setCursorChoice: {}", single);
useSingle = single;
if (useSingle) {
useCursor = singlePage;
} else {
useCursor = multiPage;
}
return;
}
#Override
public void dropActionChanged( final DragSourceDragEvent dsde) {
log.debug("CursorDragSourceListener.dropActionChanged: {}", dsde.getDropAction(), useSingle);
if (dsde.getDropAction() == 2) {
if (!useSingle) {
useCursor = badSinglePage;
} else {
useCursor = singlePage;
}
} else {
if (useSingle) {
useCursor = singlePage;
} else {
useCursor = multiPage;
}
}
dsde.getDragSourceContext().setCursor(useCursor);
return;
}
#Override
public void dragOver( final DragSourceDragEvent dsde) {
try {
Object x = dsde.getDragSourceContext().getTransferable()
.getTransferData(DataFlavor.javaFileListFlavor);
log.trace("CursorDragSourceListener.dragOver: {}", (x != null) ? x.getClass().getSimpleName() : "null");
if (x instanceof ArrayList) {
dsde.getDragSourceContext().setCursor(useCursor);
}
} catch (Exception e) {
log.error("CursorDragSourceListener.dragOver:", e);
}
}
#Override
public void dragExit( final DragSourceEvent dse) {
}
#Override
public void dragEnter( final DragSourceDragEvent dsde) {
}
#Override
public void dragDropEnd( final DragSourceDropEvent dsde) {
}
}
After a bunch more checking and analysis, it turns out that our Custom Selection Model was causing this problem on OSX.
We have a selection model that allows you to select multiple individual cells, not just whole rows.
So the getMinSelectionindex() and getMaxSelectionIndex() methods returned dummy data, since we never used them.
That works fine on MS Win, but apparently the OSX drag and drop for JTable uses those calls.
After modifying our code to return reasonable values, the selection box is no longer as tall as the table.
The custom cursors appear most of the time, but still randomly disappear for no apparent reason.

add server side data into html list?

i am new in gwt.i want to add data come from serverside in html listbox,so how can w do this??
name is splitted string which i want to add in the listbox...
actually i want to make jqxlistbox type module.http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxlistbox/index.htm
public class imagegrid implements EntryPoint
{
Label l = new Label("search");
TextBox tb=new TextBox();
VerticalPanel panel=new VerticalPanel();
String name=null;
private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
public void onModuleLoad()
{
tb.addKeyUpHandler(new handler());
panel.add(l);
panel.add(tb);
RootPanel.get().add(panel);
}
public class handler implements KeyUpHandler
{
public void onKeyUp(KeyUpEvent event)
{
String ab =tb.getText();
if(ab.length()>0)
{
greetingService.server(ab,new AsyncCallback<String>()
{
#Override
public void onFailure(Throwable caught)
{
Window.alert("Invalid");
}
#Override
public void onSuccess(String result)
{
System.out.println("At the client side..."+result);
if(result.isEmpty())
{
name="not found";
}
else
{
String match=tb.getText();
for (String retval: result.split("/"))
{
name=retval;
}
}
}
});
}
}
}
}
I think what you are looking for is CellList in GWT. You can find the sample code in showcase.
Sorry, I missed the search part of your question. For that you may need to create a new implementation og SuggestBox with CellList as drop-down. Like someone has shown here.

Cannot open website link in J2ME

I am working on a simple J2ME application and i have a StringItem linked to a terms and conditions page online.
I have the StringItem setup and it appears underlined (giving the feeling that it is linked); but when i click on it, it does not perform any action.
Find below my code:
public class mobiMidlet extends MIDlet implements CommandListener {
private Display display;
private TextField userName,password;
public Form form;
private Command login, register, forgot, terms, cancel;
private Image img_error, img_login, img_register, img_forgot, img_terms;
private String termsurl = "http://example.com/terms.php";
private StringItem termsItem;
public mobiMidlet() {
form = new Form("Welcome to My App");
termsItem = new StringItem("", "Terms and Conditions", Item.HYPERLINK);
termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1));
ItemCommandListener listener = new ItemCommandListener() {
public void commandAction(Command cmd, Item item) {
if(cmd==terms)
{
try {
platformRequest(termsurl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
termsItem.setItemCommandListener(listener);
userName = new TextField("LoginID:", "", 30, TextField.ANY);
password = new TextField("Password:", "", 30, TextField.PASSWORD);
cancel = new Command("Cancel", Command.CANCEL, 2);
login = new Command("Login", Command.OK, 2);
try{
img_login = Image.createImage("/logo.jpg");
img_register = Image.createImage("/error2.png");
img_forgot = Image.createImage("/logo.jpg");
img_register = Image.createImage("/error2.png");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
public void startApp() {
display = Display.getDisplay(this);
form.append(termsItem);
form.append(userName);
form.append(password);
form.addCommand(cancel);
form.addCommand(login);
form.setCommandListener(this);
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
String label = c.getLabel();
if(label.equals("Cancel")) {
destroyApp(true);
} else if(label.equals("Login")) {
validateUser(userName.getString(), password.getString());
}
}
}
How can I fix this so that when I click on the terms and conditions link, it opens the page on a browser?
You have not initialized variable terms, so it remains null. Therefore condition cmd==terms is always false and you never enter the if statement.
Separate line termsItem.setDefaultCommand(new Command("terms", Command.ITEM, 1)); to two:
terms = new Command("terms", Command.ITEM, 1);
termsItem.setDefaultCommand(terms);
Now you have a chance.
BTW why not to debug you program? Run it in emulator, put break point into commandAction and see what happens.

Wrap Extended Frame View in a Window

I have an assignment from my university to continue a JAVA card project from the students from last semester, which happens to be sucked. Because we have to carry on with someones work instead ours..
So my first step is to make an window image icon and tray icon for the application`s window.
The thing is, this code below is based on extended FrameView instead of JWindow.
My idea is to wrap the extended FrameView up into a Window.
Can someone help me with that?
Thanks much I would appreciate that.
CODE:
public class DesktopApplication1View extends FrameView implements IProgressDialogObserver
{
//============================================================
// Fields
// ===========================================================
private Connection connection = new Connection();
private ProgressDialogUpdater pbu = ProgressDialogUpdater.getInstance();
private Vector<CourseFromCard> courseListFromCard = new Vector<CourseFromCard>();
private Vector<School> schoolList = new Vector<School>();
private Vector<CourseFromFile> courseList = new Vector<CourseFromFile>();
private int cardReaderRefreshHelper = 0;
private Student student = null;
JLabel jLabelBilkaImage = null;
final String ICON = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_32.png";
final String PIC = new File("").getAbsolutePath() + System.getProperty("file.separator") + "src" + System.getProperty("file.separator") + "resources" + System.getProperty("file.separator") + "image" + System.getProperty("file.separator") + "BilKa_Icon_128.png";
private JLabel getJLabelBilkaImage() {
if (jLabelBilkaImage == null) {
Icon image = new ImageIcon(PIC);
jLabelBilkaImage = new JLabel(image);
jLabelBilkaImage.setName("jLabelBilkaImage");
}
return jLabelBilkaImage;
}
//============================================================
// Constructors
// ===========================================================
public DesktopApplication1View(SingleFrameApplication app)
{
super(app);
pbu.registriere(this);
app.getMainFrame().setIconImage(Toolkit.getDefaultToolkit().getImage("icon.png"));
initComponents();
refreshConnectionState();
readFilesFromLocalHDD();
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++)
{
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener()
{
public void propertyChange(java.beans.PropertyChangeEvent evt)
{
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName))
{
if (!busyIconTimer.isRunning())
{
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
}
else if ("done".equals(propertyName))
{
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
}
else if ("message".equals(propertyName))
{
String text = (String) (evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
}
else if ("progress".equals(propertyName))
{
int value = (Integer) (evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
}
.........
SingleFrameApplication provides the method getMainFrame(), which returns the JFrame used to display a particular view. The code you listed in your question is one such view. If you need to operate on the frame, it's probably better to do it in code subclassing SingleFrameApplication than the code you posted.
There's a tutorial on using the Swing Application Framework, which might provide more help.

Categories