How can Univocity Parsers be used from within JavaFX 8?
IntelliJ is being used for this. There are no warnings given by IntelliJ in the coding context, but when running the code there are errors.
Here is the code, and stack trace(abbreviated):
Main.java:
package parse;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("parse.fxml"));
primaryStage.setTitle("Parse Test");
primaryStage.setScene(new Scene(root, 300, 275));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Controller.java:
package parse;
import com.univocity.parsers.common.processor.RowListProcessor;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import javafx.fxml.FXML;
import javafx.scene.control.TextArea;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class Controller {
#FXML
private TextArea textArea;
public Controller() {
}
#FXML
private void initialize() {
}
public void print(String message) {
textArea.appendText(message);
}
public Reader getReader(String relativePath) {
try {
return new InputStreamReader(this.getClass().getResourceAsStream(relativePath), "Windows-1252");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Unable to read input", e);
}
}
#FXML
public void columnSelection() {
print("this is the parsing method" + System.getProperty("line.separator"));
RowListProcessor rowProcessor = new RowListProcessor();
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);
parserSettings.setLineSeparatorDetectionEnabled(true);
parserSettings.setSkipEmptyLines(true);
parserSettings.getFormat().setDelimiter(',');
// Here we select only the columns "Price", "Year" and "Make".
// The parser just skips the other fields
parserSettings.selectFields("AUTHOR", "ISBN");
CsvParser parser = new CsvParser(parserSettings);
parser.parse(getReader("list3.csv"));
List<String[]> rows = rowProcessor.getRows();
String[] strings = rows.get(0);
print(strings[0]);
}
}
parse.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="279.0" prefWidth="322.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="parse.Controller">
<center>
<Button mnemonicParsing="false" onAction="#columnSelection" text="Parse" BorderPane.alignment="CENTER" />
</center>
<top>
<TextArea fx:id="textArea" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
</top>
</BorderPane>
Stack Trace:
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1770)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1653)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
Caused by: java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:97)
at parse.Controller.getReader(Controller.java:34)
at parse.Controller.columnSelection(Controller.java:60)
... 56 more
Related
This question already has answers here:
h:commandButton/h:commandLink does not work on first click, works only on second click
(2 answers)
have to press command button twice
(5 answers)
Closed 7 years ago.
I have a bunch of html files on my server that get loaded into my JSF view when a menu button is clicked.
Many of those files have an action button in them, like so:
<?xml version="1.0" encoding="utf-8"?>
<div xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns="http://www.w3.org/1999/xhtml" id="d10e780" class="content">
<h:form id="publicationForm">
<h:panelGrid columns="2" width="45%">
<h:commandButton id="addToCart" value="Add to publishing Cart" actionListener="#{cartController.addToCart('d10e780.html')}">
<f:ajax execute="#form" render="#none"/>
</h:commandButton>
<h:commandButton id="viewCart" value="View publishing cart" action="#{cartController.viewCart()}"/>
</h:panelGrid>
</h:form>
<div id="d10e780" class="content">
<ul class="level_two">
<li class="level_two">SomeStuff</li>
</ul>
</div>
</div>
when the button is clicked, the name of the file is added to that shopping cart for subsequent publication.
The backing beans look like this:
package controllers;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import org.xml.sax.SAXException;
import utils.PDFCreator;
#Named
#SessionScoped
public class Publication implements Serializable {
private static final long serialVersionUID = -2404153211000142338L;
private List<String> documents = new ArrayList<>();
private Map<Long, Boolean> selected = new HashMap<Long, Boolean>();
public Publication() {
}
public Map<Long, Boolean> getSelected() {
return selected;
}
public void setSelected(Map<Long, Boolean> selected) {
this.selected = selected;
}
public List<String> getDocuments() {
return documents;
}
public void setDocuments(List<String> documents) {
this.documents = documents;
}
public void addDocument(String dokumentId) {
if (!documents.contains(dokumentId)) {
documents.add(dokumentId);
}
}
public void publishPDF() {
List<String> checkedItems = new ArrayList<>();
for (String doc : documents) {
if (selected.get(doc)) {
checkedItems.add(doc);
System.out.println("BEING PUBLISHED " + doc);
}
}
selected.clear();
for (String item : checkedItems) {
try {
PDFCreator.makePDF(Paths.get(item));
} catch (SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and
package controllers;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import views.Pages;
#SessionScoped
#Named
public class CartController implements Serializable {
#Inject
private Publication publication;
private static final long serialVersionUID = 7768738867325966926L;
public CartController() {
}
public void addToCart(String dokumentId) {
System.out.println("CARTCONTROLLER: ADDTOCART: " + dokumentId);
if (getPublication() == null) {
publication = new Publication();
getPublication().addDocument(dokumentId);
} else {
getPublication().addDocument(dokumentId);
}
}
public String viewCart() {
return Pages.PUBLICATION + "?faces-redirect=true";
}
public void editItem(String title) {
}
public void updateCart(String title) {
}
public Publication getPublication() {
return publication;
}
public void setPublication(Publication publication) {
this.publication = publication;
}
}
Now here's the problem: I have to click the button twice for the file name to be added to the list. Why is that? I'd like, of course, to just click the button once and have it work.
Thanks for help and tips!!
I am trying to use phase Listener in one of my beans in jsf but it's not working.
Class:
package com.mycompany.creditcard1;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
#Named(value = "userDetailsLogin1")
#ViewScoped
public class UserDetailsLogin1 implements Serializable, PhaseListener {
private UserDetails userDetails;
Flash flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
#PostConstruct
public void init() {
System.out.println("inti");
userDetails = (UserDetails) flash.get("userDetails");
if (userDetails == null) {
userDetails = new UserDetails();
}
}
public UserDetailsLogin1() {
}
public UserDetails getUserDetails() {
return userDetails;
}
public String action() {
flash.put("userDetails", userDetails);
return "UserDetailsLogin2?faces-redirect=true";
}
#Override
public void afterPhase(PhaseEvent pe) {
System.out.println("after phase");
}
#Override
public void beforePhase(PhaseEvent pe) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}
faces-config file:
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<lifecycle>
<phase-listener>com.mycompany.creditcard1.MyPhaseListener</phase-listener>
</lifecycle>
Error:
Unable to create a new instance of 'com.mycompany.creditcard1.MyPhaseListener': javax.faces.FacesException: com.mycompany.creditcard1.MyPhaseListener
Don't understand why it is showing this?
Any help!!!
Well start by replacing <phase-listener>com.mycompany.creditcard1.MyPhaseListener</phase-listener> by <phase-listener>com.mycompany.creditcard1.UserDetailsLogin1</phase-listener>... you have the wrong class name!
Also, I don't know if it is a good practice to mixup Bean and PhaseListener into the same class...
Does anyone know how to configure a persistent token store for Mule OAuth Provider module?
Adding a normal object store does not support the org.mule.modules.oauth2.provider.token.TokenStore interface.
EDIT
I want to persist to file - disk.
EDIT 2
Flow with OAuth provider setup:
<mule xmlns:objectstore="http://www.mulesoft.org/schema/mule/objectstore" xmlns:context="http://www.springframework.org/schema/context"
xmlns:https="http://www.mulesoft.org/schema/mule/https" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:json="http://www.mulesoft.org/schema/mule/json"
xmlns:mulexml="http://www.mulesoft.org/schema/mule/xml"
xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core"
xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
xmlns:spring="http://www.springframework.org/schema/beans" version="EE-3.5.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ss="http://www.springframework.org/schema/security" xmlns:mule-ss="http://www.mulesoft.org/schema/mule/spring-security"
xmlns:oauth2-provider="http://www.mulesoft.org/schema/mule/oauth2-provider"
xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-current.xsd
http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd
http://www.mulesoft.org/schema/mule/xml http://www.mulesoft.org/schema/mule/xml/current/mule-xml.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/https http://www.mulesoft.org/schema/mule/https/current/mule-https.xsd
http://www.mulesoft.org/schema/mule/oauth2-provider http://www.mulesoft.org/schema/mule/oauth2-provider/current/mule-oauth2-provider.xsd
http://www.mulesoft.org/schema/mule/spring-security http://www.mulesoft.org/schema/mule/spring-security/current/mule-spring-security.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
http://www.mulesoft.org/schema/mule/objectstore http://www.mulesoft.org/schema/mule/objectstore/current/mule-objectstore.xsd">
<spring:beans>
<spring:bean id="oauthTokenStore" name="oauthTokenStore" class="org.mule.util.store.TextFileObjectStore"/>
</spring:beans>
<spring:beans>
<ss:authentication-manager id="resourceOwnerAuthenticationManager">
<ss:authentication-provider>
<ss:user-service id="resourceOwnerUserService">
<ss:user name="${username}" password="${password}" authorities="RESOURCE_OWNER" />
</ss:user-service>
</ss:authentication-provider>
</ss:authentication-manager>
</spring:beans>
<mule-ss:security-manager>
<mule-ss:delegate-security-provider name="resourceOwnerSecurityProvider" delegate-ref="resourceOwnerAuthenticationManager" />
</mule-ss:security-manager>
<oauth2-provider:config name="blazeOauth2Provider"
providerName="Blaze" host="0.0.0.0" port="${blaze.esb.port.https}"
authorizationEndpointPath="api/1.0/authorize" accessTokenEndpointPath="api/1.0/token"
resourceOwnerSecurityProvider-ref="resourceOwnerSecurityProvider"
scopes="BLAH" doc:name="OAuth provider module"
tokenTtlSeconds="${blaze.security.token.lifespan}" connector-ref="httpsServerConnector" supportedGrantTypes="AUTHORIZATION_CODE IMPLICIT" enableRefreshToken="true" tokenStore-ref="oauthTokenStore" >
<oauth2-provider:clients>
<oauth2-provider:client clientId="${blaze.client.id}" secret="${blaze.client.secret}" type="CONFIDENTIAL" clientName="Client" description="Service Front-End">
<oauth2-provider:redirect-uris>
<oauth2-provider:redirect-uri>http://localhost*</oauth2-provider:redirect-uri>
</oauth2-provider:redirect-uris>
<oauth2-provider:authorized-grant-types>
<oauth2-provider:authorized-grant-type>AUTHORIZATION_CODE</oauth2-provider:authorized-grant-type>
<oauth2-provider:authorized-grant-type>TOKEN</oauth2-provider:authorized-grant-type>
</oauth2-provider:authorized-grant-types>
<oauth2-provider:scopes>
<oauth2-provider:scope>BLAH</oauth2-provider:scope>
</oauth2-provider:scopes>
</oauth2-provider:client>
</oauth2-provider:clients>
</oauth2-provider:config>
</mule>
ok, after performing a simple test, I recommend developing your own FileObjectStore for more control.
Create public class, for example:
public class MyFileObjectStore extends AbstractObjectStore { ..}
Use a properties file to store the token, key=value
Implement the methods: doStore, doRetrieve, doRemove, basically to update on a properties files.
Change in you flow:
<spring:bean id="accessTokenStore" class="test.MyFileObjectStore"/>
<spring: bean name="tokenStore" class="org.mule.modules.oauth2.provider.token.ObjectStoreTokenStore">
<spring:property name="accessTokenObjectStore" ref="accessTokenStore" />
There are several ways to set the tokenStore for oauth. You can use for example (the most common):
org.mule.util.store.PartitionedPersistentObjectStore or
org.mule.transport.jdbc.store.JdbcObjectStore
For your requirement, you can use:
org.mule.util.store.TextFileObjectStore
I hope to help;
Based on #Julio answer:
Added a class, that implements a map <String, AccessTokenStoreHolder>:
package xxx;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.mule.api.lifecycle.InitialisationException;
import org.mule.api.store.ObjectDoesNotExistException;
import org.mule.api.store.ObjectStoreException;
import org.mule.config.i18n.CoreMessages;
import org.mule.util.FileUtils;
import org.mule.util.IOUtils;
import org.mule.util.StringUtils;
import org.mule.util.store.InMemoryObjectStore;
import org.mule.modules.oauth2.provider.token.AccessTokenStoreHolder;
public class PersistantOAuthObjectStore extends InMemoryObjectStore<AccessTokenStoreHolder> {
protected File fileStore;
protected String directory;
private Map<String, AccessTokenStoreHolder> tokenStore;
private FileOutputStream output;
public PersistantOAuthObjectStore() {
super();
}
private Map<String, AccessTokenStoreHolder> getTokenStore() {
if (tokenStore == null)
tokenStore = new HashMap<>();
return tokenStore;
}
#Override
public void initialise() throws InitialisationException
{
super.initialise();
if (directory == null)
directory = context.getConfiguration().getWorkingDirectory() + "/objectstore";
try
{
File dir = FileUtils.openDirectory(directory);
fileStore = new File(dir, name + ".dat");
if (fileStore.exists())
loadFromStore();
}
catch (Exception e)
{
throw new InitialisationException(e, this);
}
}
#SuppressWarnings("unchecked")
protected synchronized void loadFromStore() throws Exception
{
ObjectInputStream stream = new ObjectInputStream(new FileInputStream(fileStore));
Object result = stream.readObject();
tokenStore = (Map<String, AccessTokenStoreHolder>)result;
for (Map.Entry<String, AccessTokenStoreHolder> entry : getTokenStore().entrySet())
super.store(entry.getKey().toString(), entry.getValue());
stream.close();
}
#Override
public void store(Serializable id, AccessTokenStoreHolder item) throws ObjectStoreException
{
super.store(id, item);
try
{
synchronized(getTokenStore()) {
getTokenStore().put(id.toString(), item);
saveMap();
}
}
catch (IOException e)
{
throw new ObjectStoreException(e);
}
}
private void saveMap() throws IOException {
if (output == null)
output = new FileOutputStream(fileStore, false);
ObjectOutputStream stream = new ObjectOutputStream(output);
stream.writeObject(getTokenStore());
}
#Override
public AccessTokenStoreHolder remove(Serializable key) throws ObjectStoreException
{
super.retrieve(key);
try
{
synchronized (getTokenStore())
{
if (getTokenStore().containsKey(key)) {
AccessTokenStoreHolder val = getTokenStore().get(key);
getTokenStore().remove(key);
saveMap();
return val;
}
}
throw new ObjectDoesNotExistException(CoreMessages.objectNotFound(key));
}
catch (IOException e)
{
throw new ObjectStoreException(e);
}
}
#Override
public void clear() throws ObjectStoreException
{
super.clear();
try
{
synchronized (getTokenStore()) {
getTokenStore().clear();
saveMap();
}
}
catch (IOException e)
{
throw new ObjectStoreException(e);
}
}
public String getDirectory()
{
return directory;
}
public void setDirectory(String directory)
{
this.directory = directory;
}
#Override
public boolean isPersistent() {
return true;
}
}
Then add 2 spring beans to xml:
<spring:bean id="oauthTokenStore" name="oauthTokenStore" class="org.mule.modules.oauth2.provider.token.ObjectStoreTokenStore">
<spring:property name="accessTokenObjectStore" ref="oauthObjectStore"/>
</spring:bean>
<spring:bean id="oauthObjectStore" class="com.vatit.blaze.esb.utils.objectStore.BlazePersistantObjectStore" init-method="initialise" destroy-method="dispose" name="oauthObjectStore">
<spring:property name="name" value="oauthObjectStore"/>
</spring:bean>
Then ref the tokenStore in your OAuth 2 provider config:
tokenStore-ref="oauthTokenStore"
I think the above answers are correct but not ideal. ObjectStoreTokenStore can be composed of multiple persistent object stores. I am not sure if you even need to write any Java code to have this done.
<spring:bean name="tokenStore" class="org.mule.modules.oauth2.provider.token.ObjectStoreTokenStore">
<spring:property name="accessTokenObjectStore" ref="accessTokenFileObjectStore"/>
<spring:property name="refreshTokenObjectStore" ref="refreshTokenFileObjectStore"/>
</spring:bean>
Here accessTokenFileObjectStore and refreshTokenFileObjectStore can be spring beans created out from TextFileObjectStore
I was trying to use servlet Annotation .
This is my servlet as shown below and the context name is Teste
I dont have any web.xml in my project .
package com;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet(name = "Mine", urlPatterns = { "/Mine" })
public class Mine extends HttpServlet {
private static final long serialVersionUID = 1L;
public Mine() {
super();
System.out.println("I am Called");
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
String str = (String) session.getAttribute("salary");
out.println("str is" + str);
}
}
I am getting Error 404 when i was try to access in browser
Please let me know where i was doing Mistake .
I am writing a small demo program to display a message box in to run in blackberry. As soon as I click the OK button on the dialog, it throws me a JVM Error 104, uncaught:runtimeexception. Any help please? Here is the code :
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.container.*;
public class My_First_App extends UiApplication
{
public static void main(String[] args)
{
My_First_App theApp = new My_First_App();
theApp.enterEventDispatcher();
}
public My_First_App()
{
pushScreen(new My_First_AppScreen());
}
}
final class My_First_AppScreen extends MainScreen
{
public My_First_AppScreen()
{
super();
HorizontalFieldManager _fieldmanager;
_fieldmanager = new HorizontalFieldManager();
/* declare one label to how the application title */
LabelField applicationtitle = new LabelField("Demo",LabelField.ELLIPSIS | LabelField.USE_ALL_WIDTH);
ButtonField _pairMe = new ButtonField("PairMe");
FieldChangeListener listenerPairMe = new FieldChangeListener() {
public void fieldChanged(Field field, int context){
Dialog.alert("You clicked the button!");
}
};
/*set the title*/
add(_fieldmanager);
setTitle(applicationtitle);
_fieldmanager.add(_pairMe);
_pairMe.setChangeListener(listenerPairMe);
}
public boolean onClose()
{
Dialog.alert("Goodbye!");
System.exit(0);
return true;
}
}
create a new workspace. It's related to Eclipse, not to your code