Java App developed in Eclipse don't work in web page - java

I have developed a small JApplet for a site.
It's the first time I do such a thing, so it's probably a stupid error or misundestanding, but I can't find out what it is.
Here is the first class called from the HTML:
public class MapGenerator extends JApplet {
private static final long serialVersionUID = 1L;
private int numero_immagini;
private BufferedImage[] images;
private int[] floors;
private static final String N_IMMAGINI = "numero_immagini";
private static final String IMMAGINE = "immagine";
private static final String PIANO_IMMAGINE ="numero_piano";
public void init() {
numero_immagini = Integer.parseInt(this.getParameter(N_IMMAGINI));
images = new BufferedImage[numero_immagini];
floors = new int[numero_immagini];
for(int i=0; i< numero_immagini; i++) {
try {
URL url = new URL(this.getParameter(IMMAGINE+i));
images[i] = ImageIO.read(url);
floors[i] = Integer.parseInt(this.getParameter(PIANO_IMMAGINE+i));
} catch (IOException ioe) {}
}
}
public void start() {
Editor ed = new Editor(this.getContentPane(), images, floors);
this.setSize(400, 400);
this.add(ed.getPanel());
Toolkit kit = this.getToolkit();
Dimension dim = kit.getScreenSize();
this.setBounds(dim.width/4, dim.height/4, dim.width/4, dim.height/4);
this.setVisible(true);
this.repaint();
}
}
And here is the HTML:
<applet code="MapGenerator.class"
archive="MapGenerator.jar"
width= 400 height = 200>
<param name=numero_immagini value=1>
<param name=immagine0 value="IMG_20111009_171138.jpg">
<param name=numero_piano0 value=0>
</applet>
In Eclipse I haven't any problem at all, but when I tried with Chrome the page show only a gray box.
Thank to all for help.
EDIT
The app cannot load images from the link that I pass.
It trows, testing with a random link image
java.security.AccessControlException: access denied (java.net.SocketPermission www.hyros.net:80 connect,resolve)
java.lang.NullPointerException

The problem is the code, and not the way I use HTML, the jar file or other things, so I opened a new question here, to describe the problem in a more correct way.
Thank you for your answers.

Related

Exported SVG overflows boundaries

I am visualizing some data with vaadin-charts:3.2.0, and I am trying to export a SVG out from the chart. I get some results but it is not satisfying. I can only share the screenshosts instead of the SVG itself. I also had to pixelate the labels to mask private data.
Original vaadin-charts seen on screen:
Exported SVG:
One problem is that the labels overflow the svg boundaries. And the chart drawings also overflow the boundaries making it seem like an incomplete drawing. Any idea what is wrong with this structure?
public class SvgStreamResource extends StreamResource {
public SvgStreamResource(String svgText, String filename) {
super(new StreamSource() {
#Override
public InputStream getStream() {
InputStream s = new BufferedInputStream( new ReaderInputStream(new StringReader(svgText)));
return s;
}
}, filename + ".svg");
}
#Override
public String getMIMEType() {
return "image/svg+xml";
}
}
Within a component:
Button exportButton = createExportButton("SVG", createSVGStreamSource(conf));
private SvgStreamResource createSVGStreamSource(Configuration conf) {
String svg = SVGGenerator.getInstance().generate(conf);
return new SvgStreamResource(svg, fileBaseName);
}
private Button createExportButton(String caption, SvgStreamResource svgStreamResource) {
Button b = new Button(caption);
FileDownloader downloader = new FileDownloader(svgStreamResource);
downloader.extend(b);
return b;
}

Refresh panel in Wicket with BootstrapDownloadLink

My problem is simple but I have no clue how to solve it. I have a feedbackPanel and I want to show an error message if the BootstrapDownloadLink fails. With a submit I could easily do:
protected void onSubmit(AjaxRequestTarget target) {
...
error("File_not_found"); //Wicket will print this on the feedback panel
target.add(getModalPanel().getFeedbackPanel()); //But i need to refresh it first
}
But the button is inside a panel which I fill with a populateItem and is the only way I know to insert Bootstrap Styles to it. The code of the button:
BootstrapDownloadLink downloadDocument = new BootstrapDownloadLink(IDITEMREPEATER, file) {
#Override
public void onClick() {
File file = (File)getModelObject();
if(file.exists()) {
IResourceStream resourceStream = new FileResourceStream(new org.apache.wicket.util.file.File(file));
getRequestCycle().scheduleRequestHandlerAfterCurrent(new ResourceStreamRequestHandler(resourceStream, file.getName()));
} else {
error(getString("error_fichero_no_existe"));
/// ???? need to refresh-> getModalPanel().getFeedbackPanel()
}
}
};
downloadDocument.setIconType(GlyphIconType.clouddownload);
downloadDocument.add(new AttributeModifier("title", getString("documentos.descargar")));
downloadDocument.add(new AttributeModifier("class", " btn btn-info negrita btn-xs center-block"));
downloadDocument.setVisible(Boolean.TRUE);
list.add(downloadDocument);
You could create or extend from an AjaxDownloadLink, for example like here.
The main idea is to have an AjaxBehavior that does the download, and you get a public void onClick(AjaxRequestTarget target) in which you can add the FeedbackPanel
downloadBehavior = new AbstractAjaxBehavior()
{
private static final long serialVersionUID = 3472918725573624819L;
#Override
public void onRequest()
{
[...]
ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(
AjaxDownloadLink.this.getModelObject(), name);
handler.setContentDisposition(ContentDisposition.ATTACHMENT);
getComponent().getRequestCycle().scheduleRequestHandlerAfterCurrent(handler);
}
};
And use that behavior in the onclick:
#Override
public void onClick(AjaxRequestTarget aTarget)
{
String url = downloadBehavior.getCallbackUrl().toString();
if (addAntiCache) {
url = url + (url.contains("?") ? "&" : "?");
url = url + "antiCache=" + System.currentTimeMillis();
}
// the timeout is needed to let Wicket release the channel
aTarget.appendJavaScript("setTimeout(\"window.location.href='" + url + "'\", 100);");
}
You can use target.addChildren(getPage(), IFeedback.class). This will add all instances of IFeedback interface in the page to the AjaxRequestTarget.
You can also use FeedbackPanel.class instead of the interface.
Or use getPage().visit(new IVisitor() {...}) to find a specific feedback panel if you don't want to add others which are not related.

Use JSON in Java

I'm a beginner. I want to write a weather app that gets some information from the web and show it to the user. But I have trouble to pass the user input to the JSON method. Can anybody help me?
the problem is in ActionListener part.
import com.google.gson.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.imageio.*;
public class Weather extends JFrame implements ActionListener {
static JButton getWeather;
static JTextField inputZip, showCity, showState, showCondition, showTemp;
static JLabel enterZip, city, state, condition, temp, image;
public static double temp_f, temp_c;
static Image pic;
public static String zip, jCity, jState, jCondition, fORc;
public Weather() throws Exception {
//Button
getWeather = new JButton("Get Weather");
getWeather.addActionListener(this);
//TextFiels
inputZip = new JTextField(10);
showCity = new JTextField(10);
showState = new JTextField(10);
showCondition = new JTextField(10);
showTemp = new JTextField(10);
//Labels
enterZip = new JLabel ("Enter Zipcode:");
city = new JLabel ("City:");
state = new JLabel ("State:");
condition = new JLabel ("Condition:");
temp = new JLabel ("temp:");
//Radio Buttons
CheckboxGroup tUnit = new CheckboxGroup();
Checkbox f = new Checkbox ("f", tUnit, true);
Checkbox c = new Checkbox ("c", tUnit, false);
//Image
URL coldPicURL = new URL("https://cdn1.iconfinder.com/data/icons/xmas-color/512/snow_snowflake_winter_cold_weather-128.png");
URL hotPicURL = new URL("http://yowindow.com/img/yo_128.png");
URL picURL = new URL ("http://findicons.com/files/icons/2796/metro_uinvert_dock/128/the_weather_channel.png");
if (temp_f!=0 && temp_f<=60)
pic = ImageIO.read(coldPicURL);
else if (temp_f > 60)
pic = ImageIO.read(hotPicURL);
else
pic = ImageIO.read(picURL);
image = new JLabel(new ImageIcon(pic));
//Frame
JFrame weather = new JFrame ("Weather App");
weather.setVisible(true);
weather.setSize(500,250);
weather.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Panels
JPanel pInput = new JPanel();
JPanel pDisplay = new JPanel();
JPanel pDisplayInfo = new JPanel();
JPanel pTempUnits = new JPanel();
JPanel pImage = new JPanel();
//Panels' Layout
pInput.setLayout(new FlowLayout());
pDisplay.setLayout(new BorderLayout());
pDisplayInfo.setLayout(new GridLayout(5,2));
pTempUnits.setLayout(new FlowLayout());
//Frame Layout
weather.add(pInput, BorderLayout.NORTH);
weather.add(pDisplay, BorderLayout.CENTER);
pDisplay.add(pDisplayInfo, BorderLayout.NORTH);
pDisplay.add(pTempUnits, BorderLayout.CENTER);
weather.add(pImage, BorderLayout.EAST);
//Insertion the objects into the panels
pInput.add(enterZip);
pInput.add(inputZip);
pInput.add(getWeather);
pDisplayInfo.add(city);
pDisplayInfo.add(showCity);
pDisplayInfo.add(state);
pDisplayInfo.add(showState);
pDisplayInfo.add(condition);
pDisplayInfo.add(showCondition);
pDisplayInfo.add(temp);
pDisplayInfo.add(showTemp);
pTempUnits.add(c);
pTempUnits.add(f);
pImage.add(image);
}
public void actionPerformed(ActionEvent e) {
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
getJson (zip);
showCity.setText(jCity);
showState.setText(jState);
showCondition.setText(jCondition);
if (fORc.equals("f"))
showTemp.setText(Double.toString(temp_f));
if (fORc.equals("c"))
showTemp.setText(Double.toString(temp_c));
}
public static void getJson(String zip) throws Exception {
String json="", line;
JsonElement jse;
final String key = "7b86aadc43344a90";
JsonParser parser = new JsonParser();
URL url = new URL("http://api.wunderground.com/api/" +
key + "/conditions/q/" + zip + ".json");
InputStream is = url.openStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
while ((line = rd.readLine()) != null)
json += line;
rd.close();
jse = parser.parse(json);
jCity=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("display_location").getAsJsonObject().get("city").getAsString();
jState=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("display_location").getAsJsonObject().get("state").getAsString();
jCondition=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("weather").getAsString();
temp_f=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("temp_f").getAsDouble();
temp_c=jse.getAsJsonObject().get("current_observation").getAsJsonObject().get("temp_c").getAsDouble();
}
public void itemStateChanged (ItemEvent ie){
Checkbox cb = (Checkbox)ie.getItemSelectable();
fORc = cb.getLabel();
}
public static void main(String[] args) throws Exception {
Weather w = new Weather();
}
}
On a first level:
getJson (zip);
that call throws an exception. And in Java you have to either try/catch that exception; or add it to the signature of the method this happens (using the throws keyword). In your case, that is not possible, as you are actually overriding an existing method; and then you can't add a throws statement to the method signature.
But the real answer here is: slow down. The above compiler error is about a super basic thing within Java. When you don't know what an Exception is, and how to properly deal with that, then you are many hours of learning away from writing a Swing UI application that wants to deal with JSON data from a remote site.
This also becomes obvious when looking in how you structure your code. You clearly separate responsibilities; you create classes around those that help you coming up with a clean OO based model. For example, you would fully separate the UI layer (swing) that displays information from the specifics where such information is coming from. Your JFrame shouldn't know anything about JSON input.
Your code shows nothing of that. I call this the "you should learn to crawl before going for hurdle racing" syndrome.
First,I think you'd better provide more detail information, what kind of problem is? Is that kind of exception for an unexpected result? Or you can just post the result for others to take a look.
Second, I tried to run your program. There are two issue in that.
1. in the code that you wrote a comment : //HERE'S WHERE I'M STUCKED !!! :(
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
getJson (zip);
showCity.setText(jCity);
showState.setText(jState);
the method getJson() you have "throws Exception", so when you invoke the method, you also need to deal with the exception maybe you can just catch the exception like this:
zip = Weather.inputZip.getText();
//HERE'S WHERE I'M STUCKED !!! :(
try {
getJson (zip);
} catch (Exception e1) {
e1.printStackTrace();
}
showCity.setText(jCity);
showState.setText(jState);
Or you can continue throw the exception.
when finished the previous problem, I found the "fORc" will meet a null pointer exception which you need to check your process when to pass the var.
Third,still about the fORc, in your code, you wrote
if (fORc.equals("f"))
showTemp.setText(Double.toString(temp_f));
if (fORc.equals("c"))
showTemp.setText(Double.toString(temp_c));
But I suggest you can change like this, then you can deal when the fORc is a null:
if (null == fORc)
//do something. like throw exception
if ("f".equals(fORc))
showTemp.setText(Double.toString(temp_f));
if ("c".equals(fORc))
showTemp.setText(Double.toString(temp_c));
Hope could help you.

SetIcon NullPointerException

This is a little Program. The Method should set Icons on buttons to a predefined set of icons. But when I start the Program I get a NullPointerException.
The Method
public void SetIcon(boolean isActive) {
ImageIcon IconBold, IconClipboard, IconKursiv, IconUnderline;
Ressources Temp;
if (isActive) {
Temp = new RessourcesAlternate();
} else {
Temp = new RessourcesStandard();
}
IconBold = new ImageIcon(Temp.getBold());
IconClipboard = new ImageIcon(Temp.getClipboard());
IconKursiv = new ImageIcon(Temp.getKursiv());
IconUnderline = new ImageIcon(Temp.getUnderline());
this.btnBold.setText("");
this.btnBold.setIcon(IconBold);
this.btnClipboard.setText("");
this.btnClipboard.setIcon(IconClipboard);
this.btnKursiv.setText("");
this.btnKursiv.setIcon(IconKursiv);
this.btnUnderline.setText("");
this.btnUnderline.setIcon(IconUnderline);
}
The Interface
public interface Ressources {
public URL getBold ();;
public URL getClipboard ();
public URL getUnderline ();
public URL getKursiv ();
}
Class Standard
public final class RessourcesStandard implements Ressources{
final URL CLIPBOARD = Main.class.getResource("Icons/standard/clipboard-icon.png");
final URL BOLD = Main.class.getResource("Icons/standard/bold-icon.png");
final URL UNDERLINE = Main.class.getResource("Icons/standard/underline-icon.png");
final URL KURSIV = Main.class.getResource("Icons/standard/italic-icon.png");
#Override
public URL getBold() {
return BOLD;
}
#Override
public URL getClipboard() {
return CLIPBOARD;
}
#Override
public URL getUnderline() {
return UNDERLINE;
}
#Override
public URL getKursiv() {
return KURSIV;
}
}
Class Alternate
public final class RessourcesAlternate implements Ressources{
final URL CLIPBOARD = Main.class.getResource("Icons/alternate/clipboard-icon.png");
final URL BOLD = Main.class.getResource("Icons/alternate/bold-icon.png");
final URL UNDERLINE = Main.class.getResource("Icons/alternate/underline-icon.png");
final URL KURSIV = Main.class.getResource("Icons/alternate/italic-icon.png");
#Override
public URL getBold() {
return BOLD;
}
#Override
public URL getClipboard() {
return CLIPBOARD;
}
#Override
public URL getUnderline() {
return UNDERLINE;
}
#Override
public URL getKursiv() {
return KURSIV;
}
}
Error Message:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at de.test.Editor.GUI_Tapped.SetIcon(GUI_Tapped.java:262)
at de.test.Editor.GUI.<init>(GUI.java:79)
at de.test.Editor.Main.main(Main.java:23)
GUI is my Main Frame
GUI_Tapped is on possible Open Tab
Okay,
There was some Problem with the URL Objects. They returned Null.
I edited the whole Thing and uses Strings instead of URLs. Now its working.
Thanks
If your NullPointerException occurs on the line where you call setIcon(...) on your JButtons, then your JButtons are likely null. Check the object whose method is being called on the line throwing the NPE and you'll see.
More importantly, you need to learn the general concepts of how to debug a NPE (NullPointerException). You should inspect the line carefully that throws it, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me.
For example, your stack trace has a key line:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at de.test.Editor.GUI_Tapped.SetIcon(GUI_Tapped.java:262) // ***** here *****
at de.test.Editor.GUI.<init>(GUI.java:79)
at de.test.Editor.Main.main(Main.java:23)
This line is the first line of the stacktrace that references one of your classes, and so that is the line that is likely causing the NPE to be thrown. Please check it carefully, please trace back to where your variables should be initialized, and you'll likely solve your problem.

primefaces creating a dynamic dashboard

Following the example at http://www.wobblycogs.co.uk/index.php/computing/jee/49-dynamic-dashboard-with-primefaces im trying to create a dynamic dashboard.
Copying the code works 100% perfeclty, but im trying to use it with my own implementation.
When i load my index page it dosnt show any panels or the dashboard at all. When i navigate to a differet page, and come back the elements appear!
I have no idea why the dashboard is not displayed on initial page load.
Im working with Jboss 5.1, EJB 3.0, JSF 2.0 and Primefaces 3.4.
This is the top of my controller class:
#Model
#ViewController(viewId = "/pages/index.xhtml")
public class MonitorController implements Serializable, ViewInitializer, ViewFinalizer {
#Inject
private transient MonitorService monitorService;
#Inject
private transient MonitorUserService monitorUserService;
#Inject
private transient MonitorView view;
#Inject
private transient Conversation conversation;
#Override
public void initializeView() {
if (conversation.isTransient()) {
conversation.setTimeout(1800000);
conversation.begin();
}
MonitorUser user = monitorUserService.findOrCreateUser();
view.setUser(user);
List<MonitorElement> elements = monitorService.findMonitorElementsByUser();
view.setElements(elements);
view.setUsersMonitorElements(elements);
createDashBoard();
}
This is my method for creating the dashboard, adding panels and setting the column widgets:
public void createDashBoard() {
final int DEFAULT_COLUMN_COUNT = 3;
int columnCount = DEFAULT_COLUMN_COUNT;
Dashboard dashboard;
FacesContext fc = FacesContext.getCurrentInstance();
Application application = fc.getApplication();
dashboard = (Dashboard) application.createComponent(fc, "org.primefaces.component.Dashboard", "org.primefaces.component.DashboardRenderer");
dashboard.setId("dashboard");
DashboardModel model = new DefaultDashboardModel();
for( int i = 0; i < columnCount; i++ ) {
DashboardColumn column = new DefaultDashboardColumn();
model.addColumn(column);
}
dashboard.setModel(model);
view.setModel(dashboard.getModel());
view.setDashboard(dashboard);
int index = 0;
for( MonitorElement i : view.getUsersMonitorElements()) {
Panel panel = (Panel) application.createComponent(fc, "org.primefaces.component.Panel", "org.primefaces.component.PanelRenderer");
panel.setId("id" + i.getId());
panel.setHeader("Dashboard Component " + i.getApplicationName());
panel.setClosable(true);
panel.setToggleable(true);
dashboard.getChildren().add(panel);
DashboardColumn column2 = model.getColumn(index%columnCount);
column2.addWidget(panel.getId());
HtmlOutputText text = new HtmlOutputText();
text.setValue(i.getCount() + "" );
panel.getChildren().add(text);
index++;
}
view.setModel(dashboard.getModel());
view.setDashboard(dashboard);
}
I am implementing the dashboard on my index page using:
<p:dashboard id="dynamic_dashboard3"
binding="#{monitorView.dashboard}">
</p:dashboard>

Categories