JSF Read Text File - java

I've been googling all over the place for information on how to display content from a .txt file onto a web page using JSF with no success.
From what I think/guess, the basic jsf form would be something like
<h:outputText value="#{beanName.printTextFileMethod}"/>
or something.
Help on how to set up bean appreciated. I tried playing with InputStream/BufferedStream, having a lot of problem just trying to get rid of the red lines in codes. Also I'm absolutely horrid at defining relative path. And absolute path doesn't seem to work with inputstream?
Thank you for your time.

public class TextFileBean{
String completeMessage = null;
public TextFileBean(){
try{
//read data from the text file
java.io.BufferedReader in=
new java.io.BufferedReader(
new java.io.InputStreamReader(
TextFileBean.this.getClass().
getResourceAsStream("txtFile.txt"
)));
System.out.println("in :" +in);
readData(in);
in.close();
} catch (java.io.IOException IOex) {
System.out.println("IO Error :" +IOex);
}
}
private void readData(BufferedReader br) {
// dosomethig
String line = null;
StringBuffer appendMessage = null;
try {
appendMessage = new StringBuffer(16384);
while ((line = br.readLine()) != null) {
appendMessage.append(line);
appendMessage.append('\n');
}
if (appendMessage != null) {
completeMessage = appendMessage.toString();
}
} catch (Exception e) {
}
}
public String printTextFileMethod()
{
System.out.println("completeMessage:: "+ completeMessage);
return completeMessage;
}
}

Related

How to load saved item from JSON file in java

I am making an app where user can change theme (dark and light mood) as per his convenience. And the theme that the user chooses will be saved and the saved theme will be there when the app is opened again later.
I have saved the data to file using JSON.
And when the user clicks on the theme change button, the data will be written to the file.
The code of the theme:
private void darkTheme() {
FlatDarkLaf.setup();
UIManager.put("TextField.foreground", new ColorUIResource(Color.WHITE));
UIManager.put("Label.foreground", new ColorUIResource(Color.WHITE));
UIManager.put("Button.foreground", new ColorUIResource(Color.WHITE));
SwingUtilities.updateComponentTreeUI(contentPane);
for(int i=0; i<arList.size(); i++) {
((JLabel)arList.get(i).getRenderer()).setHorizontalAlignment(SwingConstants.CENTER);
}
}
And the Code for the theme change and write to the file button:
btnDark.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String path = "resources/config.cfg";
JSONObject json = new JSONObject();
try {
json.put("Theme", "darkTheme();");
} catch (JSONException ex) {
ex.printStackTrace();
}
try (PrintWriter out = new PrintWriter(new FileWriter(path))) {
out.write(json.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
darkTheme();
}
});
I can read the file but can't Load the save data.
Here the code for read the file:
private void readData() {
try {
String path = "resources/config.cfg";
InputStream is = Button.class.getResourceAsStream(path);
if (is == null) {
throw new NullPointerException("Cannot find resource file " + path);
}
JSONTokener tokener = new JSONTokener(is);
JSONObject object = new JSONObject(tokener);
// object.getString("darkTheme();");
object.getJSONObject("Theme");
}
catch (Exception e) {
}
}
Can anyone please help me how to do this correctly.
Ok Finally I've got a solution by my own and someone's idea.
I have changed the line in btnDark
json.put("Theme", "darkTheme();");
to
json.put("Theme", "Dark");
and in the readData() method I write like this
private void readData() {
String jsonText;
try {
String path = "resources/config.cfg";
jsonText = IOUtils.toString(new FileInputStream(new File(path)));
int i = jsonText.indexOf("{");
jsonText = jsonText.substring(i);
JSONObject ob = new JSONObject(jsonText);
String Theme = ob.getString("Theme");
if(Theme.equals("Dark")) {
darkTheme();
}
else if(Theme.equals("Light")) {
lightTheme();
}
}catch(Exception ex) {
ex.printStackTrace();
}
}
And now it's work perfectly

how can i replace the try catch to not get the error exception when i am not sending the file?

I am sending variables from ajax to java! in my ajax method I am sending 2 variables: idtabPrest and idPolice!
I am getting an error exception because I am not passing the File ! how can I make this function work and read the variables even if i am not sending the File.
I commented the Try/catch of the file to pass the variables! but in some ajax methods I am using the file.
public String upload_via_ajax() {
try {
String property = "java.io.tmpdir";
String tempDir = System.getProperty(property);
String html = "inside upload via ajax";
// try {
// File destFile = new File(tempDir, myFileFileName.substring(0,
// myFileFileName.lastIndexOf(".")) + ".csv");
// FileUtils.copyFile(myFile, destFile);
//
// getRequest().getSession().setAttribute("filePath",
// destFile.getPath());
//POUR REFERENCE DECLARATION
if(annee != null) {
TableReferentielDto tableReferentielDto = new TableReferentielDto();
tableReferentielDto.setId(Long.parseLong(annee));
TableReferentielDto anneeLabel =(TableReferentielDto) tableReferentielGetByIdCmd
.execute(tableReferentielDto);
getRequest().getSession().setAttribute("annee",
anneeLabel.getLibelle());
}
//POUR DATE DEBUT DECLARATION
if(moisDebutDeclaration != null){
getRequest().getSession().setAttribute("moisDebutDeclaration",
moisDebutDeclaration);
}
//POUR DATE FIN DECLARATION
if(moisFinDeclaration != null){
getRequest().getSession().setAttribute("moisFinDeclaration",
moisFinDeclaration);
}
//ID POLICE
if(idPolice != null){
getRequest().getSession().setAttribute("idPolice",
idPolice);
}
if(idTabPrest != null) {
getRequest().getSession().setAttribute("idTabPrest",
idTabPrest);
}
if(idTabTarif != null){
getRequest().getSession().setAttribute("idTabTarif",
idTabTarif);
}
html = "file uploaded";
// } catch (IOException e) {
//
// html = "error in uploading file";
// e.printStackTrace();
// }
return SUCCESS;
} catch (Exception e) {
return SUCCESS;
}
}

Downloading GitHub issues to .csv file

GitHub issues download using eclipse egit doesn't return anything.
Recently, i've been attempting to create a java desktop application (for windows), that will download GitHub issues from a specific GitHub issue repository, and save them in a .csv file.
I've created a simple GUI using Swing to enable the input of repository names. I'm also using eclipse's egit library to establish a connection to GitHub in order to download issues. I use authentication, entered using a .properties file in order to authenticate egit's connection with GitHub.
Here is the main code my application uses to download the issues and write them to a .csv file:
package io.github.psgs.issuesdownload;
import io.github.psgs.issuesdownload.gui.GUI;
import org.eclipse.egit.github.core.Issue;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.IssueService;
import java.io.FileWriter;
import java.io.IOException;
public class IssuesDownload {
public static void main(String[] args) {
try {
Config.loadConfiguration();
} catch(IOException ex) {
}
GUI.main(args);
}
public static String saveIssues(String repoDetails) {
String[] repoInfo = repoDetails.split("/");
String repoOwner = repoInfo[0];
String repoName = repoInfo[1];
GitHubClient client = new GitHubClient();
client.setCredentials(Config.githubuser, Config.githubpass);
IssueService issueService = new IssueService(client);
try {
FileWriter writer = new FileWriter("issues.csv");
//String[] header = {"Id", "Title", "Creator", "Assignee", "Milestone", "State", "Body Text"};
writer.append("Id, Title, Creator, Assignee, Milestone, State, Body Text");
writer.append("\n");
for (Issue issue : issueService.getIssues(repoOwner, repoName, null)) {
//String[] data = {String.valueOf(issue.getId()), issue.getTitle(), issue.getUser().getName(), issue.getAssignee().getName(), issue.getMilestone().getTitle(), issue.getState(), issue.getBodyText()};
writer.append(String.valueOf(issue.getId()) + ",");
writer.append(issue.getTitle() + ",");
writer.append(issue.getUser().getName() + ",");
writer.append(issue.getAssignee().getName() + ",");
writer.append(issue.getMilestone().getTitle() + ",");
writer.append(issue.getState() + ",");
writer.append(issue.getBodyText());
writer.append("\n");
}
writer.flush();
writer.close();
return "Download Complete!";
} catch (IOException ex) {
System.out.println("An IOException has occured!");
ex.printStackTrace();
if (ex.getMessage().equalsIgnoreCase("api.github.com")) {
return "An error has occured, reaching " + ex.getMessage() + "! Please check your network connection.";
}
}
return "An error has occured!";
}
}
This code is also available at: https://gist.github.com/psgs/9048602
The whole repository can be found at: https://github.com/psgs/IssuesDownload
When I run this code, with the .properties file in the same directory as the compile .jar file, the GitHub issues don't appear in the .csv file. I've tested the .csv file output, and the headers write correctly when I remove the download code.
Would anybody know why this is happening? Perhaps it's an authentication problem that i've missed?
After trying a few new API wrappers, i've found an API library that works. I'm now using Kohsuke Kawaguchi's GitHub API for Java to connect to GitHub.
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>github-api</artifactId>
<version>1.49</version>
</dependency>
My code now reads as follows:
package io.github.psgs.issuesdownload;
import io.github.psgs.issuesdownload.gui.GUI;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHIssueState;
import org.kohsuke.github.GHRepository;
import org.kohsuke.github.GitHub;
import java.io.FileWriter;
import java.io.IOException;
public class IssuesDownload {
public static void main(String[] args) {
try {
Config.loadConfiguration();
} catch (IOException ex) {
System.out.println("An IOException had occured while loading the configuration!");
ex.printStackTrace();
}
GUI.main(args);
}
public static String saveIssues(String repoDetails, GHIssueState issueState) {
String[] repoInfo = repoDetails.split("/");
try {
GitHub github = GitHub.connectUsingOAuth(Config.githubtoken);
GHRepository repository = github.getUser(repoInfo[0]).getRepository(repoInfo[1]);
FileWriter writer = new FileWriter("issues.csv");
writer.append("Id, Title, Creator, Assignee, Milestone, State, Body Text");
writer.append("\n");
for (GHIssue issue : repository.getIssues(issueState)) {
writer.append(String.valueOf(issue.getNumber()) + ",");
writer.append(issue.getTitle() + ",");
writer.append(issue.getUser().getLogin() + ",");
if (issue.getAssignee() != null) {
writer.append(issue.getAssignee().getName() + ",");
} else {
writer.append(" ,");
}
if (issue.getMilestone() != null) {
writer.append(issue.getMilestone().getTitle() + ",");
} else {
writer.append(" ,");
}
writer.append(issue.getState() + ",");
writer.append(issue.getBody() + ",");
writer.append("\n");
}
writer.flush();
writer.close();
return "Download Complete!";
} catch (IOException ex) {
System.out.println("An IOException has occured!");
ex.printStackTrace();
if (ex.getMessage().equalsIgnoreCase("api.github.com")) {
return "An error has occurred reaching " + ex.getMessage() + "! Please check your network connection.";
}
}
return "An error has occured!";
}
}
It looks like the method you're using is meant to be used to retrieve the issues for the currently authenticated user.
Perhaps this test (in the project's repository) would be helpful. The only difference I see is that you're not passing a singletonMap and I'm not sure you exactly have to.
public static <T> void outputCsv(String fileName, String[] headerName,
List<T> listResult, HttpServletRequest request) {
HttpServletResponse response = ResponseUtil.getResponse();
OutputStream out;
try {
// Encode file name
fileName = Util.encodeUnicodeFile(fileName, request);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/octet-stream; charset="
+ Constant.CONST_SJIS_ENCODING);
response.setHeader("Content-disposition", "attachment; filename=\""
+ fileName + "\"");
response.setCharacterEncoding(Constant.CONST_SJIS_ENCODING);
out = response.getOutputStream();
CSVWriter writer = new CSVWriter(new OutputStreamWriter(out,
Constant.CONST_WINDOW_JAPAN_ENCODING),
Constant.CONST_CSV_SEPARATOR_COMMA);
// Convert list result data to List <String[]>
List<String[]> list = convertListDataToCsvArray(listResult,
headerName);
// Write list data
writer.writeAll(list);
writer.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static <T> List<String[]> convertListDataToCsvArray(
List<T> listResult, String[] headerName) {
List<String[]> listCsv = new ArrayList<String[]>();
// First row is header
listCsv.add(headerName);
for (T object : listResult) {
// Get all fields of object
Field[] fields = object.getClass().getFields();
// Init row
String[] row = new String[headerName.length];
int index = 0;
for (Field field : fields) {
try {
if (field.getType().equals(Long.class)) {
// Read field value and set to string array
Long value = (Long) field.get(object);
row[index] = value != null ? String.valueOf(value) : "";
} else if (field.getType().equals(String.class)) {
// Read field value and set to string array
String value = (String) field.get(object);
row[index] = value != null ? value : "";
} else if (field.getType().equals(BigDecimal.class)) {
// Read field value and set to string array
BigDecimal value = (BigDecimal) field.get(object);
row[index] = value != null ? String.valueOf(value) : "";
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
index++;
}
// Add row
listCsv.add(row);
}
return listCsv;
}

Using JSoup to save the contents of this url: http://www.aw20.co.uk/images/logo.png to a file

I am try to use JSoup to get the contents of this url http://www.aw20.co.uk/images/logo.png, which is the image logo.png, and save it to a file. So far I have used JSoup to connect to http://www.aw20.co.uk and get a Document. I then went and found the absolute url for the image I am looking for, but now am not sure how to this to get the actual image. So I was hoping someone could point me in the right direction to do so? Also is there anyway I could use Jsoup.connect("http://www.aw20.co.uk/images/logo.png").get(); to get the image?
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class JGet2 {
public static void main(String[] args) {
try {
Document doc = Jsoup.connect("http://www.aw20.co.uk").get();
Elements img = doc.getElementsByTag("img");
for (Element element : img) {
String src = element.absUrl("src");
System.out.println("Image Found!");
System.out.println("src attribute is: " + src);
if (src.contains("logo.png") == true) {
System.out.println("Success");
}
getImages(src);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
private static void getImages(String src) throws IOException {
int indexName = src.lastIndexOf("/");
if (indexName == src.length()) {
src = src.substring(1, indexName);
}
indexName = src.lastIndexOf("/");
String name = src.substring(indexName, src.length());
System.out.println(name);
}
}
You can use Jsoup to fetch any URL and get the data as bytes, if you don't want to parse it as HTML. E.g.:
byte[] bytes = Jsoup.connect(imgUrl).ignoreContentType(true).execute().bodyAsBytes();
ignoreContentType(true) is set because otherwise Jsoup will throw an exception that the content is not HTML parseable -- that's OK in this case because we're using bodyAsBytes() to get the response body, rather than parsing.
Check the Jsoup Connection API for more details.
Jsoup isn't designed for downloading the content of the url.
Since you are able to use a third party library, you can try apache common IO for downloading the content of a given URL to file using:
FileUtils.copyURLToFile(URL source, File destination);
It is only one line.
This method does not work well. Please careful when using it.
byte[] bytes = Jsoup.connect(imgUrl).ignoreContentType(true).execute().bodyAsBytes();
You can use these methods or part of these methods to solve your problem.
NOTE: IMAGE_HOME is the absolute path. e.g. /home/yourname/foldername
public static String storeImageIntoFS(String imageUrl, String fileName, String relativePath) {
String imagePath = null;
try {
byte[] bytes = Jsoup.connect(imageUrl).ignoreContentType(true).execute().bodyAsBytes();
ByteBuffer buffer = ByteBuffer.wrap(bytes);
String rootTargetDirectory = IMAGE_HOME + "/"+relativePath;
imagePath = rootTargetDirectory + "/"+fileName;
saveByteBufferImage(buffer, rootTargetDirectory, fileName);
} catch (IOException e) {
e.printStackTrace();
}
return imagePath;
}
public static void saveByteBufferImage(ByteBuffer imageDataBytes, String rootTargetDirectory, String savedFileName) {
String uploadInputFile = rootTargetDirectory + "/"+savedFileName;
File rootTargetDir = new File(rootTargetDirectory);
if (!rootTargetDir.exists()) {
boolean created = rootTargetDir.mkdirs();
if (!created) {
System.out.println("Error while creating directory for location- "+rootTargetDirectory);
}
}
String[] fileNameParts = savedFileName.split("\\.");
String format = fileNameParts[fileNameParts.length-1];
File file = new File(uploadInputFile);
BufferedImage bufferedImage;
InputStream in = new ByteArrayInputStream(imageDataBytes.array());
try {
bufferedImage = ImageIO.read(in);
ImageIO.write(bufferedImage, format, file);
} catch (IOException e) {
e.printStackTrace();
}
}
Also is there anyway I could use Jsoup.connect("http://www.aw20.co.uk/images/logo.png").get(); to get the image?
No, JSoup will only get text and such but cannot be used to download files or binary data. That being said, just use the file name and path that you've gotten through JSoup and then use standard Java I/O to download the file.
I've used NIO to do the downloading. i.e.,
String imgPath = // ... url path to image
String imgFilePath = // ... file path String
URL imgUrl;
ReadableByteChannel rbc = null;
FileOutputStream fos = null;
try {
imgUrl = new URL(imgPath);
rbc = Channels.newChannel(imgUrl.openStream());
fos = new FileOutputStream(imgFilePath);
// setState(EXTRACTING + imgFilePath);
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (rbc != null) {
try {
rbc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Two Dimensional String Pass to JTable

I'm trying to take data from a CSV file, parse it to a two dimensional array and then return that to a GUI that displays it in a JTable. Doesn't seem to be going too well!
METHOD TO GET FROM CSV
static String[][] readGUIFromPropertyFile(String sFileName, String userName) throws FileNotFoundException
{
String thisLine;
String tempArray[][] = new String[20][4];
int i = 0;
BufferedReader reader = new BufferedReader(new FileReader(sFileName));
try
{
while((thisLine = reader.readLine()) != null)
{
String propertyDetails[] = thisLine.split(",");
if (propertyDetails[0].equals(userName))
{
tempArray[i][0] = propertyDetails[1];
tempArray[i][1] = propertyDetails[2];
tempArray[i][2] = propertyDetails[3];
tempArray[i][3] = propertyDetails[4];
tempArray[i][4] = propertyDetails[5];
i++;
}
}
return tempArray;
}
catch(IOException e)
{
System.out.print("\nProperties do not exist\n");
e.printStackTrace();
}
finally{
try
{ reader.close();
}catch (IOException e){}}
return tempArray;
}
}
CODE FOR GUI
else if (event.getSource() == reload)
{
try {
data = CSVWrite.readGUIFromPropertyFile(propertyFile, userName);
JOptionPane.showMessageDialog(frame, "Properties Loaded");
userPropertyView.add(displayProperties);
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(frame, "Properties Not Loaded");
e.printStackTrace();
}
}
I have it working with a command interface so I know the code is working, but I have to implement both a GUI and a command line. I can write from GUI to CSV, no issue, but having trouble displaying it. I've looked into ArrayLists and I actually have a lecture on them tomorrow so that's also a possibility.
I can't use OpenCSV as I have to use default libraries for this.
put String tempArray[][] as JTables constructor JTable(Object[][] rowData, Object[] columnNames) directly
better way should be to add a new row to the TableModel, not replace the JTable on runtime, more in tutorial Creating a Table Model

Categories

Resources