JavaFX, SceneBuilder, Populating TableView with MySQL Result Set - mysql

I have finally overcome my issue with a NPE in my code whilst learning FX/FXML. I now however have a different problem, a window opens with my TableView however there is no content in the table at all. As you cann I have printed out the JobList to make sure there is content being returned, and this returns three jobs (the correct amount). Am I missing something that binds the table to the returned list?
Here is the code;
public class SecondInterface implements Initializable {
private JobDataAccessor jAccessor;
private String aQuery = "SELECT * FROM progdb.adamJobs";
private Parent layout;
private Connection connection;
#FXML
TableView<Job> tView;
public void newI(Connection connection) throws Exception {
Stage primaryStage;
primaryStage = MainApp.primaryStage;
this.connection = connection;
System.out.println(connection);
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Test1.fxml"));
fxmlLoader.setController(this);
try {
layout = (Parent) fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
primaryStage.getScene().setRoot(layout);
}
public Parent getLayout() {
return layout;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
jAccessor = new JobDataAccessor();
try {
System.out.println("This connection: " + connection);
System.out.println("This query: " + aQuery);
List<Job> jList = jAccessor.getJobList(connection, aQuery);
for (Job j : jList) {
System.out.println(j);
}
tView.getItems().addAll(jAccessor.getJobList(connection, aQuery));
} catch (SQLException e) {
e.printStackTrace();
}
}
}

Related

How can I mock RabbitMQClient of io.quarkiverse.rabbitmqclient.RabbitMQClient and write junit for basic send and consume operation?

I'm new to the quarkus framework where I'm writing rabbitmq-client library based on quarkur framework. I'm using io.quarkiverse.rabbitmqclient.RabbitMQClient.
I need to write JUnit for basic send and consume operations, please help me with how can I write junit and mock RabbitMQClient. I'm using the below code to send and consume message.
#ApplicationScoped
public class RabbitMQProducerAdapterImpl extends RabbitMQCongiguration implements RabbitMQProducerAdapter {
#Override
public void sendMessage(String exchange, String routingKey, String messagePayload) throws IOException {
setUpConnectionAndChannel();
channel.basicPublish(exchange, routingKey, null, messagePayload.getBytes(StandardCharsets.UTF_8));
Log.info("message sent succefully: " + messagePayload);
}
}
Here is the RabbitMQCongiguration
#ApplicationScoped
public class RabbitMQCongiguration {
#Inject
private RabbitMQClient rabbitClient;
protected Channel channel;
protected void setUpConnectionAndChannel() {
try {
// create a connection
Connection connection = rabbitClient.connect();
// create a channel
channel = connection.createChannel();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
protected void setupQueueInDirectExchange(String exchangeName, String routingKey, String queueName,
boolean createExchangeQueues) throws IOException {
setUpConnectionAndChannel();
if (createExchangeQueues) {
this.channel.exchangeDeclare(exchangeName, BuiltinExchangeType.DIRECT, true, false, false, null);
// declaring a queue for this channel. If queue does not exist,
// it will be created on the server. this line not needed if queue already
// present
this.channel.queueDeclare(queueName, true, false, false, null);
}
// Bind Routing Key to Exchange
this.channel.queueBind(queueName, exchangeName, routingKey);
}
}
Below is the class for consumer
#ApplicationScoped
public class RabbitMQConsumerAdapterImpl extends RabbitMQCongiguration implements RabbitMQConsumerAdapter, Runnable {
private String queueName;
private MessageProcessor messageProcessor;
#Override
public void consumeMessage(String exchange, String queueName, String routingKey,
MessageProcessor messageProcessor) throws IOException {
Log.info("starting consumer...");
try {
this.queueName = queueName;
this.messageProcessor = messageProcessor;
Log.info("setting up rabbitMQPrefetchCountConfig");
setupQueueInDirectExchange(exchange, routingKey, queueName, false);
Thread consumerThread = new Thread(this);
consumerThread.start();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#Override
public void run() {
try {
// start consuming messages. Auto acknowledge messages.
Log.info("Start consuming messages from thread...");
channel.basicConsume(this.queueName, false, (Consumer) new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String msgPayload = null;
if (body == null || body.length == 0) {
Log.warn("Invalid Message Body - Consumer Tag : " + consumerTag + ", Message DeliveryTag : "
+ envelope.getDeliveryTag());
channel.basicReject(envelope.getDeliveryTag(), false);
} else {
msgPayload = new String(body);
try {
JsonParser.parseString(msgPayload);
} catch (JsonSyntaxException ex) {
Log.error(msgPayload + " is not a valid json, Reason - ", ex);
channel.basicReject(envelope.getDeliveryTag(), false);
Log.warn("Rejected the current payload.");
return;
}
messageProcessor.processMessage(msgPayload);
channel.basicAck(envelope.getDeliveryTag(), false);
}
// just print the received message.
Log.info("Received: " + new String(body, StandardCharsets.UTF_8));
}
});
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
#ApplicationScoped
public class MessageProcessorImpl implements MessageProcessor{
#Override
public void processMessage(String messagePayload) {
Log.info("message consumed: " + messagePayload);
}
}

JavaFx combobox from mysql

Good Day I am completely new to coding. I am building an app which uses a combobox besides other library items. The problem I am facing is that while attempting to populate combobox items from a Mysql Db the item values get duplicated each time the drop down is clicked.
How I can keep this from happening ? I do understand that my approach itself could be erroneous.
#FXML
public void getStation() {
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
comboBoxStation.getItems().add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
Ok so I moved the function to the initialize() method in the controller and created an Observabale list called station
private ObservableList<String> stationsList = FXCollections.observableArrayList();
#Override
public void initialize(URL url, ResourceBundle rb) {
//
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
stationsList.add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
and then left only this line in the original function....seems to be working.
#FXML
private void getStation() {
comboBoxStation.setItems(stationsList);
}

send message to mobile api j2me

Hello everyone I'm getting this error:
Uncaught exception: java.lang.IllegalArgumentException: Port Number formatted badly
- com.sun.midp.io.j2me.sms.Protocol.openPrimInternal(), bci=209
- com.sun.midp.io.j2me.sms.Protocol.openPrim(), bci=4
- javax.microedition.io.Connector.open(), bci=47
- javax.microedition.io.Connector.open(), bci=3
- javax.microedition.io.Connector.open(), bci=2
- travel.entities.SendMessage$1.run(SendMessage.java:31)
- java.lang.Thread.run(), bci=5
when converting those two textfields to send them
public TextField tfDestination = new TextField("Destination","", 20, TextField.PHONENUMBER);
public TextField tfPort = new TextField("Port", "50001", 6, TextField.NUMERIC);
using this method:
public static void execute(final String destination, final String port, final String message) {
Thread th = new Thread(new Runnable() {
public void run() {
MessageConnection msgConnection;
try {
msgConnection = (MessageConnection) Connector.open("sms://:"+port+":"+destination);
TextMessage textMessage = (TextMessage)msgConnection.newMessage(MessageConnection.TEXT_MESSAGE);
textMessage.setPayloadText(message);
msgConnection.send(textMessage);
msgConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
}
I'm getting the error on this line:
msgConnection = (MessageConnection)Connector.open("sms://:"+destination+":"+port);
Anyone have an idea?
Your destination should come before port number.
Try this:
public static void execute(final String destination, final String port, final String message) {
Thread th = new Thread(new Runnable() {
public void run() {
MessageConnection msgConnection;
String address = "sms://:"+destination+":"+port;
try {
msgConnection = (MessageConnection) Connector.open(address);
TextMessage textMessage = (TextMessage) msgConnection.newMessage(MessageConnection.TEXT_MESSAGE);
textMessage.setAddress(address);
textMessage.setPayloadText(message);
msgConnection.send(textMessage);
msgConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
th.start();
}

JList lazy load images

since i am not a java swing expert i need some help to understand why my images in my JList do not appear.
I have a JList that pops up containing all products (with inline pictures) while the user enters a search criteria. The results come from lucene and will be rendered in a JList in real time.
To lazy load the inline product images i am using a swingworker inside my rendering class.
Any help would be great!
public abstract class MatchRenderer implements ListCellRenderer {
#Override
public Component getListCellRendererComponent(JList list, final Object value, int index,
boolean isSelected, boolean cellHasFocus) {
Component component = defaultRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (quickRenderMode) {
return component;
} else {
try {
component = renderHook(value, component);
} catch (Exception e) {
System.err.println("Search string: " + searchString);
System.err.println(value.toString());
e.printStackTrace();
}
JPanel itemPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JLabel label = new JLabel(defaultIcon, SwingConstants.HORIZONTAL);
itemPanel.add(label);
itemPanel.add(component);
if (value instanceof QoogleEntity && ((QoogleEntity) value).isProduct()) {
QoogleEntity qoogleItem = (QoogleEntity) value;
String imageUrl = qoogleItem.getQInfos().get(0).getqValue();
//LAZY LOAD STARTS HERE...
new ImageRetriever(label, imageUrl).execute();
}
return itemPanel;
}
}
protected abstract Component renderHook(Object value, Component component);
class ImageRetriever extends SwingWorker<ImageIcon, String> {
private JLabel lbImage;
private String imageUrl;
public ImageRetriever(JLabel lbImage, String imageUrl) {
this.lbImage = lbImage;
this.imageUrl = imageUrl;
}
#Override
protected void done() {
try {
lbImage.setIcon(get());
lbImage.repaint();
} catch (Exception e) {
}
}
#Override
protected ImageIcon doInBackground() throws Exception {
return ImageLoader.loadImageFromUrl(imageUrl, 80, 80);
}
};

Ehcache hangs in test

I am in the process of rewriting a bottle neck in the code of the project I am on, and in doing so I am creating a top level item that contains a self populating Ehcache. I am attempting to write a test to make sure that the basic call chain is established, but when the test executes it hands when retrieving the item from the cache.
Here are the Setup and the test, for reference mocking is being done with Mockito:
#Before
public void SetUp()
{
testCache = new Cache(getTestCacheConfiguration());
recordingFactory = new EntryCreationRecordingCache();
service = new Service<Request, Response>(testCache, recordingFactory);
}
#Test
public void retrievesResultsFromSuppliedCache()
{
ResultType resultType = mock(ResultType.class);
Response expectedResponse = mock(Response.class);
addToExpectedResults(resultType, expectedResponse);
Request request = mock(Request.class);
when(request.getResultType()).thenReturn(resultType);
assertThat(service.getResponse(request), sameInstance(expectedResponse));
assertTrue(recordingFactory.requestList.contains(request));
}
private void addToExpectedResults(ResultType resultType,
Response response) {
recordingFactory.responseMap.put(resultType, response);
}
private CacheConfiguration getTestCacheConfiguration() {
CacheConfiguration cacheConfiguration = new CacheConfiguration("TEST_CACHE", 10);
cacheConfiguration.setLoggingEnabled(false);
return cacheConfiguration;
}
private class EntryCreationRecordingCache extends ResponseFactory{
public final Map<ResultType, Response> responseMap = new ConcurrentHashMap<ResultType, Response>();
public final List<Request> requestList = new ArrayList<Request>();
#Override
protected Map<ResultType, Response> generateResponse(Request request) {
requestList.add(request);
return responseMap;
}
}
Here is the ServiceClass
public class Service<K extends Request, V extends Response> {
private Ehcache cache;
public Service(Ehcache cache, ResponseFactory factory) {
this.cache = new SelfPopulatingCache(cache, factory);
}
#SuppressWarnings("unchecked")
public V getResponse(K request)
{
ResultType resultType = request.getResultType();
Element cacheEntry = cache.get(request);
V response = null;
if(cacheEntry != null){
Map<ResultType, Response> resultTypeMap = (Map<ResultType, Response>) cacheEntry.getValue();
try{
response = (V) resultTypeMap.get(resultType);
}catch(NullPointerException e){
throw new RuntimeException("Result type not found for Result Type: " + resultType);
}catch(ClassCastException e){
throw new RuntimeException("Incorrect Response Type for Result Type: " + resultType);
}
}
return response;
}
}
And here is the ResponseFactory:
public abstract class ResponseFactory implements CacheEntryFactory{
#Override
public final Object createEntry(Object request) throws Exception {
return generateResponse((Request)request);
}
protected abstract Map<ResultType,Response> generateResponse(Request request);
}
After wrestling with it for a while, I discovered that the cache wasn't being initialized. Creating a CacheManager and adding the cache to it resolved the problem.
I also had a problem with EHCache hanging, although only in a hello-world example. Adding this to the end fixed it (the application ends normally).
CacheManager.getInstance().removeAllCaches();
https://stackoverflow.com/a/20731502/2736496