Issues trying to execute Form Class in Netbeans - java

Good evening.
I have a problem using NetBeans v 11.1 for Windows.
I try to open two Frame Forms when the user select an item from a Combo Box.
The forms I want open have a string param in their constructors.
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
Visualizza visualizza = new Visualizza(this.auth);
Inserisci inserisci = new Inserisci(this.auth);
var getItem = jComboBox1.getSelectedItem();
switch(getItem.toString()){
case ("Visualizza Iscritti nel Sistema"):
visualizza.setVisible(true);
break;
case ("Inserisci Atleti nel Sistema"):
inserisci.setVisible(true);
break;
default:
break;
}
} catch (IOException ex) {
Logger.getLogger(Select.class.getName()).log(Level.SEVERE, null, ex);
}
}
The constructors code is:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import org.json.*;
public class Visualizza extends javax.swing.JFrame {
//Attributes declaration
...
public Visualizza(String auth) throws IOException {
initComponents();
btnRicerca.setVisible(false);
txtField.setVisible(false);
this.auth = auth;
Player[] player;
Requests r = new Requests("https://www.kingofthecage.it/API/getAllPlayers.php", auth);
r.sendGet();
if (r.res.equals("Errore") || r.res.equals("[]"))
{
List.removeAll();
List.add(errorMessage);
}
else
{
JSONArray arr = new JSONArray(r.res);
player = new Player[arr.length()];
String[] list = new String[arr.length()];
for (int i = 0; i < arr.length(); i++)
{
String id = arr.getJSONObject(i).getString("ID");
String name = arr.getJSONObject(i).getString("NOME");
String surname = arr.getJSONObject(i).getString("COGNOME");
String date = arr.getJSONObject(i).getString("DATA_NASCITA");
String birthplace = arr.getJSONObject(i).getString("LUOGO_NASCITA");
String residence = arr.getJSONObject(i).getString("RESIDENZA");
String cf = arr.getJSONObject(i).getString("CODICE_FISCALE");
String mail = arr.getJSONObject(i).getString("MAIL");
String mobile = arr.getJSONObject(i).getString("CELLULARE");
String team = arr.getJSONObject(i).getString("NOME_SQUADRA");
player[i] = new Player(id, name, surname, date, birthplace, residence, cf, mobile, mail, team);
List.add(list[i] = player[i].getPlayerString());
}
}
I import the library org.json to parse and interact with a response from a server, called with an HTTP Request and in the for cycle I returned params in a class called Player.
If I run the project from NetBeans works perfectly, the issue come when I build the project and I try to execute the .jar file saved in "./dist" folder. Substantially when I select a value from the ComboBox nothing happens but, as i've said, if I try to run the same code in NetBeans IDE it works.
I specify that I never change any setting from NetBeans IDE.
I hope you can solve my problem!

Related

Can't load the jdbc driver class. ClassNotFoundException

I am using eclipse and have to develop a jsp application that connects to a derby db.
After I setup the database I went into my project and added derbyclient.jar as well as derbyclient.jar as reference.
However each time I try to get the jdbc class I am getting a ClassNotFoundException.
Class.forName("org.apache.derby.jdbc.ClientDriver");
jakarta.servlet.ServletException: java.lang.ClassNotFoundException: org.apache.derby.jdbc.ClientDriver
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:674)
org.apache.jsp.index_jsp._jspService(index_jsp.java:179)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:770)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:467)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:770)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
I have also tried it with a mysql database and got the same result so I thought maybe I did something wrong with the way I reference.
I intend to use a business java class which then will be used in jsp because I don't want to have the db access code in the jsp code.
The current "BusinessManager.java" class looks like this (only mocking stuff which needs to be replaced with database code).
package com.forum.shared;
import java.sql.*;
import java.time.Instant;
import java.util.*;
public class BusinessManager {
public List<ForumEntity> LoadFromDatabase() throws ClassNotFoundException, SQLException
{
//Class.forName("com.mysql.jdbc.Driver");
//Class.forName("org.apache.derby.jdbc.ClientDriver");
//java.sql.Connection connect = null;
//String dbName = "D:/Apache/test/forum";
//String connectionURL="jdbc:derby://localhost:1527/" + dbName + ";create=true";
//connect = DriverManager.getConnection(connectionURL);
List<ForumEntity> result = new ArrayList<ForumEntity>();
ForumEntity mockData = new ForumEntity();
mockData.setID(1);
mockData.setAntwortId(0);
mockData.setAntwort(false);
mockData.setInhalt("Willkommen im Forum!");
mockData.setTitle("Willkommen");
mockData.setName("Admin");
mockData.setMail("admin#hszg.de");
mockData.setZeit(java.util.Date.from(Instant.now()));
ForumEntity answerData = new ForumEntity();
answerData.setID(2);
answerData.setAntwortId(1);
answerData.setName("Max Mustermann");
answerData.setMail("max_mustermann#gmx.com");
answerData.setInhalt("Das ist eine Antwort");
answerData.setZeit(java.util.Date.from(Instant.now()));
mockData.addAnswer(answerData);
result.add(mockData);
return result;
}
public ForumEntity LoadFromDatabaseById(int id)
{
ForumEntity result = new ForumEntity();
result.setID(1);
result.setAntwortId(0);
result.setAntwort(false);
result.setInhalt("Willkommen im Forum!");
result.setTitle("Willkommen");
result.setName("Admin");
result.setMail("admin#hszg.de");
result.setZeit(java.util.Date.from(Instant.now()));
ForumEntity answerData = new ForumEntity();
answerData.setID(2);
answerData.setAntwortId(1);
answerData.setName("Max Mustermann");
answerData.setMail("max_mustermann#gmx.com");
answerData.setInhalt("Das ist eine Antwort");
answerData.setZeit(java.util.Date.from(Instant.now()));
result.addAnswer(answerData);
return result;
}
public boolean CreateAndSafeForumEntity(int antwordId, boolean antwort, String titel, String inhalt, String name, String mail)
{
boolean result = false;
return result;
}
}
I am out of ideas. I have added the jar files for both dbms and non can be loaded. Any ideas?
Edit: I used this eclipse project template
Edit: Update
Now it gets intersting. I decided to try a different approach. I kept the libs as reference but decided to try load them during runtime.
public List<ForumEntity> LoadFromDatabase() throws ClassNotFoundException, SQLException
{
List<File> jars = Arrays.asList(new File("D:\\Apache\\db-derby-10.15.2.0-bin\\lib").listFiles());
URL[] urls = new URL[jars.size()];
for (int i = 0; i < jars.size(); i++) {
try {
urls[i] = jars.get(i).toURI().toURL();
} catch (Exception e) {
e.printStackTrace();
}
}
URLClassLoader childClassLoader = new URLClassLoader(urls, ClassLoader.getSystemClassLoader());
Class.forName("org.apache.derby.jdbc.ClientDriver", true , childClassLoader);
//Class.forName("com.mysql.jdbc.Driver");
//Class.forName("org.apache.derby.jdbc.ClientDriver");
//java.sql.Connection connect = null;
//String dbName = "D:/Apache/test/forum";
//String connectionURL="jdbc:derby://localhost:1527/" + dbName + ";create=true";
//connect = DriverManager.getConnection(connectionURL);
List<ForumEntity> result = new ArrayList<ForumEntity>();
ForumEntity mockData = new ForumEntity();
mockData.setID(1);
mockData.setAntwortId(0);
mockData.setAntwort(false);
mockData.setInhalt("Willkommen im Forum!");
mockData.setTitle("Willkommen");
mockData.setName("Admin");
mockData.setMail("admin#hszg.de");
mockData.setZeit(java.util.Date.from(Instant.now()));
ForumEntity answerData = new ForumEntity();
answerData.setID(2);
answerData.setAntwortId(1);
answerData.setName("Max Mustermann");
answerData.setMail("max_mustermann#gmx.com");
answerData.setInhalt("Das ist eine Antwort");
answerData.setZeit(java.util.Date.from(Instant.now()));
mockData.addAnswer(answerData);
result.add(mockData);
return result;
}
Guess what when I previously reached Class.forName("org.apache.derby.jdbc.ClientDriver") he allways threw the ClassNotFoundException. Now with the runtime library loading code above I don't get the ClassNotFoundException anymore when I execute Class.forName("org.apache.derby.jdbc.ClientDriver"). Very weird. I must have done something wrong while I set the references.

Java Tapestry Autocomplete typeahead include ID on listing

I have a textfield which uses autocomplete mixin on tapestry. The mixin is working fine as it is, but I am having a problem with tagging the values of list of names with duplicate values. Now I am wondering if I can somehow pass the id of the data on autocomplete upon selection.
Here is my code for pupulating the list.
List<String> onProvideCompletionsFromUserName(String partial) {
List<String> matches = new ArrayList<String>();
String partialUpper = partial.toUpperCase();
List<User> users = clientFinder.findUsers();
// int i = 0;
for (User user : users){
String name = NameUtil.toName(user.getFirstName(), user.getFamilyName());
if (name.toUpperCase().contains(partialUpper)) {
matches.add(name );
// if (i++ >= 5) {
// break;
// }
}
}
return matches;
}
Is there a way for me to pass the ID with the list like
(List onProvideCompletionsFromUserName)?
Has anyone encountered this problem as well ? Thanks for your response.
The only way I was able to do it was by extending the Autocomplete mixin with my own version, as the configure method in the mixin is marked protected. Here is my class. Note that I am firing my own event. You will have to give your own values for label, value and uid in the providecompletions handler. The zone parameter is the zone you want to update when the user clicks and item in the completion list.
Mixin:
import java.util.ArrayList;
import java.util.List;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ComponentResources;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.json.JSONLiteral;
import org.apache.tapestry5.json.JSONObject;
import org.got5.tapestry5.jquery.mixins.Autocomplete;
public class UserAutocomplete extends Autocomplete {
public static final String CHANGE_EVENT_NAME = "autocompleteUser";
#Inject
private ComponentResources resources;
#Parameter(defaultPrefix=BindingConstants.LITERAL)
private String zone;
#OnEvent(value = "provideCompletions")
public List<JSONObject> autoComplete(String query) {
List<JSONObject> strings = new ArrayList<JSONObject>();
if(query != null) {
for(User u : service.searchUsers(query.trim())) {
JSONObject so = new JSONObject();
String name = u.getName();
so.put("label", name);
so.put("value", name);
so.put("uid", u.getId());
strings.add(so);
}
}
return strings;
}
protected void configure(JSONObject config) {
config.put("url", resources.createEventLink("autocomplete").toURI());
String url = resources.createEventLink(CHANGE_EVENT_NAME).toURI();
config.put("options", new JSONObject().put("select", new JSONLiteral("function(e, d) {var zone = $('#" + zone + "'); if (!zone) { return; } "
+ "zone.tapestryZone('update', {url: '" + url + "'+'/'+d.item.uid});}")));
}
}
Page Template:
<t:textfield value="query" autocomplete="off" t:mixins="UserAutocomplete" t:zone="resultZone" />
Page Class:
...
#InjectComponent
private Zone resultZone;
#OnEvent(value = UserAutocomplete.CHANGE_EVENT_NAME)
void userChange(Integer id) {
User selectedUser = service.findUser(id);
renderer.addRender(resultZone);
}

Why cant I open 32bit Outlook on a 64bit System using a JAR when it worked in Eclipse...?

The Java app I am developing is an internal tool for others to use to help our daily activities. When the tool is used (on a JButton press which calls the code below) I want it to open a new Outlook EMail for the user to see/edit.
At first I was developing this app in a 64 bit Eclipse and could not get SWT to open Outlook despite all my research. After I had some issues running 64bit versus 32bit SWT, I had the idea to check Outlook, and sure enough the company using is 32 bit. I loaded up a 32 bit eclipse, imported my project, switch SWT to 32 bit and it worked exactly as intended.
I noticed the process that was running was javaw.exe*32 but the 64bit Eclipse was using the process javaw.exe. I exported the JAR from the 32bit Eclipse and gave it a shot and no EMail showed up. I checked the JRE's installed and saw both 32bit and 64bit but my company had a policy that forced only the 64bit JRE in the Java Control Panel. I worked with some others and got both installed and enabled as seen here. Still the JAR fails to open the EMail. I even tried disabling the 64bit and it still does not work.
Is there anything that can be done to remedy this situation? Please let me know if I can elaborate better or provide more info!
package EDM_PKG;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.ole.win32.OLE;
import org.eclipse.swt.ole.win32.OleAutomation;
import org.eclipse.swt.ole.win32.OleClientSite;
import org.eclipse.swt.ole.win32.OleFrame;
import org.eclipse.swt.ole.win32.Variant;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class CreateEmail {
private static Display display = new Display();
public static void sendEMail(String env) {
//String currUser = System.getProperty("user.name");
String msg = getMessage(env);
String sub = getSubject(env);
Shell shell = new Shell(display);
OleFrame frame = new OleFrame(shell, SWT.NONE);
// This should start outlook if it is not running yet
//OleClientSite site = new OleClientSite(frame, SWT.NONE,"OVCtl.OVCtl");
//site.doVerb(OLE.OLEIVERB_INPLACEACTIVATE);
// Now get the outlook application
OleClientSite site2 = new OleClientSite(frame, SWT.NONE, "Outlook.Application");
OleAutomation outlook = new OleAutomation(site2);
OleAutomation mail = invoke(outlook, "CreateItem", 0 /* Mail item */).getAutomation();
setProperty(mail, "BodyFormat", 2 /* HTML */);
setProperty(mail, "Subject", sub);
setProperty(mail, "To", "example#gmail.com");
setProperty(mail, "HtmlBody", msg);
invoke(mail, "Display" /* or "Send" */);
display = null;
}
private static String getMessage(String env) {
String msg = "";
if (env.equalsIgnoreCase("quas")) {
msg = "<html><body>The <b>USER</b> excel has been migrated to <b>QUAS.</b><br><br> This email was generated by Excel Datatable Migrator.</body></html>";
} else if (env.equalsIgnoreCase("prod")) {
msg = "<html><body>The <b>QUAS</b> excel has been migrated to <b>PROD.</b><br><br>This email was generated by Excel Datatable Migrator.</body></html>";
} else {
msg = "Somthing happened with the automated message of EDM. Please contact the user with the eCode: "+System.getProperty("user.name")+".</body></html>";
}
return msg;
}
private static String getSubject(String env) {
String sub = "";
if (env.equalsIgnoreCase("quas")) {
sub = "EDM has been used to move USER to QUAS...";
} else if (env.equalsIgnoreCase("prod")) {
sub = "EDM has been used to move QUAS to PROD...";
} else {
sub = "Somthing didnt quite work right...";
}
return sub;
}
private static OleAutomation getProperty(OleAutomation auto, String name) {
Variant varResult = auto.getProperty(property(auto, name));
if (varResult != null && varResult.getType() != OLE.VT_EMPTY) {
OleAutomation result = varResult.getAutomation();
varResult.dispose();
return result;
}
return null;
}
private static Variant invoke(OleAutomation auto, String command,
String value) {
return auto.invoke(property(auto, command),
new Variant[] { new Variant(value) });
}
private static Variant invoke(OleAutomation auto, String command) {
return auto.invoke(property(auto, command));
}
private static Variant invoke(OleAutomation auto, String command, int value) {
return auto.invoke(property(auto, command),
new Variant[] { new Variant(value) });
}
private static boolean setProperty(OleAutomation auto, String name,
String value) {
return auto.setProperty(property(auto, name), new Variant(value));
}
private static boolean setProperty(OleAutomation auto, String name,
int value) {
return auto.setProperty(property(auto, name), new Variant(value));
}
private static int property(OleAutomation auto, String name) {
return auto.getIDsOfNames(new String[] { name })[0];
}
}
There's no need to use the heavyweight and difficult to use Ole classes.
If all you want is to send an email, just call this:
Program.launch("mailto:bla#blubb.com&subject=Subject&body=Me‌​ssage here");
This will work on all architectures and operating systems.

how to fetch public data and images from flicker using java?

I am trying to get the Flickr data by using API key and secret key provided by flickr . I have written a java code for it.
`package com.flickr.project;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import com.aetrion.flickr.Flickr;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.photos.SearchParameters;
import com.aetrion.flickr.photos.PhotoList;
import com.aetrion.flickr.photos.PhotosInterface;
import com.aetrion.flickr.photos.Photo;
import com.flickr4java.flickr.Auth;
import com.flickr4java.flickr.RequestContext;
public class SampleProgram{
public static void main(String[] args) {
try {
searchImages();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void searchImages() {
// Search photos with tag keywords and get result
try{
//Set api key
String key="";
String svr="www.flickr.com";
String secret="";
RequestContext requestContext = RequestContext.getRequestContext();
Auth auth = new Auth();
auth.setPermission(Permission.READ);
auth.setToken("");
auth.setTokenSecret("");
requestContext.setAuth(auth);
REST rest=new REST();
rest.setHost(svr);
//initialize Flickr object with key and rest
Flickr flickr=new Flickr(key,secret,rest);
Flickr.debugRequest = false;
Flickr.debugStream = false;
Flickr.debugStream=false;
//initialize SearchParameter object, this object stores the search keyword
SearchParameters searchParams=new SearchParameters();
searchParams.setSort(SearchParameters.INTERESTINGNESS_DESC);
//Create tag keyword array
String[] tags=new String[]{"Dog","Doberman"};
searchParams.setTags(tags);
//Initialize PhotosInterface object
PhotosInterface photosInterface=flickr.getPhotosInterface();
//Execute search with entered tags
// PhotoList photoList=null;
PhotoList photoList=photosInterface.search(searchParams,20,1);
System.out.println("here");
//get search result and fetch the photo object and get small square imag's url
if(photoList!=null){
//Get search result and check the size of photo result
for(int i=0;i<photoList.size();i++){
//get photo object
Photo photo=(Photo)photoList.get(i);
//Get small square url photo
StringBuffer strBuf=new StringBuffer();
strBuf.append("<a href=\"\">");
strBuf.append("<img border=\"0\" src=\""+photo.getSmallSquareUrl()+"\">");
strBuf.append("</a>\n");
// ....
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public void userAuthentication(){
/*InputStream in = null;
try {
in = getClass().getResourceAsStream("/setup.properties");
// properties = new Properties();
// properties.load(in);
} finally {
IOUtilities.close(in);
}
f = new Flickr(properties.getProperty("apiKey"), properties.getProperty("secret"), new REST());
requestContext = RequestContext.getRequestContext();
Auth auth = new Auth();
auth.setPermission(Permission.READ);
auth.setToken(properties.getProperty("token"));
auth.setTokenSecret(properties.getProperty("tokensecret"));
requestContext.setAuth(auth);
Flickr.debugRequest = false;
Flickr.debugStream = false;*/
}
} `
I need to fetch all data including images from flickr using the key words i mentioned in the program.
From the look of things, Photo has several methods like the following:
"getSmallSquareAsInputStream" - This returns an input stream, this can be used to fetch the image data.
The full API's list for Photo class is available here

Java file encoding magic

Strange thing happened in Java Kingdom...
Long story short: I use Java API V3 to connect to QuickBooks and fetch the data form there (services for example).
Everything goes fine except the case when a service contains russian symbols (or probably non-latin symbols).
Here is Java code that does it (I know it's far from perfect)
package com.mde.test;
import static com.intuit.ipp.query.GenerateQuery.$;
import static com.intuit.ipp.query.GenerateQuery.select;
import java.util.LinkedList;
import java.util.List;
import com.intuit.ipp.core.Context;
import com.intuit.ipp.core.ServiceType;
import com.intuit.ipp.data.Item;
import com.intuit.ipp.exception.FMSException;
import com.intuit.ipp.query.GenerateQuery;
import com.intuit.ipp.security.OAuthAuthorizer;
import com.intuit.ipp.services.DataService;
import com.intuit.ipp.util.Config;
public class TestEncoding {
public static final String QBO_BASE_URL_SANDBOX = "https://sandbox-quickbooks.api.intuit.com/v3/company";
private static String consumerKey = "consumerkeycode";
private static String consumerSecret = "consumersecretcode";
private static String accessToken = "accesstokencode";
private static String accessTokenSecret = "accesstokensecretcode";
private static String appToken = "apptokencode";
private static String companyId = "companyidcode";
private static OAuthAuthorizer oauth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
private static final int PAGING_STEP = 500;
public static void main(String[] args) throws FMSException {
List<Item> res = findAllServices(getDataService());
System.out.println(res.get(1).getName());
}
public static List<Item> findAllServices(DataService service) throws FMSException {
Item item = GenerateQuery.createQueryEntity(Item.class);
List<Item> res = new LinkedList<>();
for (int skip = 0; ; skip += PAGING_STEP) {
String query = select($(item)).skip(skip).take(PAGING_STEP).generate();
List<Item> items = (List<Item>)service.executeQuery(query).getEntities();
if (items.size() > 0)
res.addAll(items);
else
break;
}
System.out.println("All services fetched");
return res;
}
public static DataService getDataService() throws FMSException {
Context context = getContext();
if (context == null) {
System.out.println("Context is null, something wrong, dataService also will null.");
return null;
}
return getDataService(context);
}
private static Context getContext() {
try {
return new Context(oauth, appToken, ServiceType.QBO, companyId);
} catch (FMSException e) {
System.out.println("Context is not loaded");
return null;
}
}
protected static DataService getDataService(Context context) throws FMSException {
DataService service = new DataService(context);
Config.setProperty(Config.BASE_URL_QBO, QBO_BASE_URL_SANDBOX);
return new DataService(context);
}
}
This file is saved in UTF-8. And it prints something like
All services fetched
Сэрвыс, отнюдь
But! When I save this file in UTF-8 with BOM.... I get the correct data!
All services fetched
Сэрвыс, отнюдь
Does anybody can explain what is happening? :)
// I use Eclipse to run the code
You are fetching data from a system that doesn't share the same byte ordering as you, so when you save the file with BOM, it adds enough information in the file that future programs will read it in the remote system's byte ordering.
When you save it without BOM, it wrote the file in the remote system's byte ordering without any indication of the stored byte order, so when you read it you read it with the local system's (different) byte order. This jumbles up the bytes within the multi-byte characters, making the output appear as nonsense.

Categories