writing UI content to a file on a server - textarea

I've got a pop-up textarea, where the user writes some lengthy comments. I would like to store the content of the textarea to a file on the server on "submit". What is the best way to do it and how?
THanks,

This would be very easy to do. The text could be just a string or stringBuffer for size and formatting, then just pass that to your java code and use file operations to write to a file.
This is some GWT code, but it's still Ajax, so it will be similar. Get a handler for an event to capture the button submittal, then get the text in the text area.
textArea.addChangeHandler(new ChangeHandler() {
public void onChange(ChangeEvent changeEvent) {
String text = textArea.getText();
}
});
The passing off mechanism I don't know because you don't show any code, but I just created a file of filenames, line by line by reading filenamesout of a list of files with this:
private void writeFilesListToFile(List<File> filesList) {
for(File file : filesList){
String fileName = file.getName();
appendToFile(fileName);
}
}
private void appendToFile(String text){
try {
BufferedWriter out = new BufferedWriter(new FileWriter<file path andfile name>));
out.write(text);
out.newLine();
out.close();
} catch (IOException e) {
System.out.println("Error appending file with filename: " + text);
}
}
You could do something similar, only write out the few lines you got from the textarea. Without more to go on I can't really get more specific.
HTH,
James

Related

How to download a file with Vaadin 10?

I want to let user to download a file from server.
I looked up for the solution and when trying to make an example - ended up with this:
#Route("test-download")
public class Download extends VerticalLayout {
public Download() {
Anchor downloadLink = new Anchor(createResource(), "Download");
downloadLink.getElement().setAttribute("download", true);
add(downloadLink);
}
private AbstractStreamResource createResource() {
return new StreamResource("/home/johny/my/important-file.log", this::createExportr);
}
private InputStream createExportr(){
return null;
}
}
Which is giving java.lang.IllegalArgumentException: Resource file name parameter contains '/' when I go to the page in browser.
How do I make a download button (or anchor) knowing file location on disk?
Have a look at the documentation, paragraph "Using StreamResource". The first parameter is just a file name that will be used by the browser to propose that file name to the user when downloading. So you could pass it like "important-file.log". The content of the download is provided by the InputStream parameter. For instance, you could read from your file, see here:
File initialFile = new File("src/main/resources/sample.txt");
InputStream targetStream = new FileInputStream(initialFile);

How do I use SimpleFileVisitor in Java to find a file name whose encoding may vary?

I'm using SimpleFileVisitor to search for a file. It works fine on Windows and Linux. However when I try using it on Unix like operating systems It doesn't work as expected. I would get errors like this:
java.nio.file.NoSuchFileException:
/File/Location/MyFolder/\u0082\u0096\u0096âĜu0099\u0081\u0097K
\u0097\u0099\u0096\u0097\u0085\u0099Ĝu0089\u0085
It looks like the obtained name is in different character encoding and maybe that is what causing the issue. It looks like in between the obtaining the name and trying to obtain the access to the file, the encoding is getting missed up. This result in calling preVisitDirectory once then visitFileFailed for every file it tries to visit. I'm not sure why the walkFileTree method is doing that. Any idea?
My using for SimpleFileVisitor code looks like this:
Files.walkFileTree(serverLocation, finder);
My SimpleFileVisitor class:
public class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private final List<Path> matchedPaths = new ArrayList<Path>();
private String usedPattern = null;
Finder(String pattern) {
this.usedPattern = pattern;
matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
}
void match(Path file) { //Compare pattern against file or dir
Path name = file.getFileName();
if (name != null && matcher.matches(name))
matchedPaths.add(file);
}
// Check each file.
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
match(file);
return CONTINUE;
}
// Check each directory.
#Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
match(dir);
return CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
System.out.println("Issue: " + e );
return CONTINUE;
}
Try using "Charset.defaultCharset()" when you create those "file" and "dir" strings you pass around. Otherwise, you could very likely mangle the names in the process of creating those strings to pass them to your visit methods.
You might also check your default encoding on the JVM your are running, if it is out of sync with the file system you are reading, your results will be, err, unpredictable.

Twitter data streaming - dynamic keyword value change

I have currently doing Sentiment Analysis on Twitter data in Hadoop.
I have configured FLUME to bring data based upon certain keywords, which I have maintained in "FLUME.conf" file, as shown below
TwitterAgent.sources.Twitter.keywords = Kitkat, Nescafe, Carnation, Milo, Cerelac
With mentioning this, I would like to know whether it is possible to dynamically change the keywords, based upon a java program that will pop-up asking for keywords from user.
Also, apart from this method, please provide any other methods you folks would suggest to hide this complexity of updating the Flume.conf file.
Best Regards,
Ram
Flume provides an Application class to run its configuration file using a Java program.
public class Flume{
public static void main(String[] args) throws Exception
{
new Conf().setConfiguration();
String[] args1 = new String[] { "agent","-nTwitterAgent",
"-fflume.conf" };
BasicConfigurator.configure();
Application.main(args1);
System.setProperty("hadoop.home.dir", "/");
}
}
Here you will get a change to edit your conf file using some file utils like this
class Conf{
int ch;
String keyword ="";
Scanner sc= new Scanner(System.in);
public void setConfiguration(){
System.out.println("Enter the keyword");
keyword=sc.nextLine();
byte[] key= keyword.getBytes();
FileOutputStream fp=null;
FileInputStream src=null;
try{
fp= new FileOutputStream("flumee.conf");
src= new FileInputStream("flume.conf");
while((ch=src.read())!=-1){
fp.write((char)ch);
}
fp.write(key);
}catch(Exception e){
System.out.println("file Exception:"+ e);
}finally{
try{
if(fp!=null){
fp.close();
}
if(src!=null){
src.close();
}
}catch(Exception e){
System.out.println("file closing Exception:"+ e);
}
}
}
}
Now you need to keep the TwitterAgent.sources.Twitter.keywords= line at the end of your flume configuration file so that it will be easier for you to add the keywords into the file. My flume.conf file looks like this
TwitterAgent.sources= Twitter
TwitterAgent.channels= MemChannel
TwitterAgent.sinks=HDFS
TwitterAgent.sources.Twitter.type = com.cloudera.flume.source.TwitterSource
TwitterAgent.sources.Twitter.channels=MemChannel
TwitterAgent.sources.Twitter.consumerKey=xxx
TwitterAgent.sources.Twitter.consumerSecret=xxx
TwitterAgent.sources.Twitter.accessToken=xxx
TwitterAgent.sources.Twitter.accessTokenSecret=
TwitterAgent.sinks.HDFS.channel=MemChannel
TwitterAgent.sinks.HDFS.type=hdfs
TwitterAgent.sinks.HDFS.hdfs.path=hdfs://localhost:9000/user/flume/direct
TwitterAgent.sinks.HDFS.hdfs.fileType=DataStream
TwitterAgent.sinks.HDFS.hdfs.writeformat=Text
TwitterAgent.sinks.HDFS.hdfs.batchSize=1000
TwitterAgent.sinks.HDFS.hdfs.rollSize=0
TwitterAgent.sinks.HDFS.hdfs.rollCount=10000
TwitterAgent.sinks.HDFS.hdfs.rollInterval=600
TwitterAgent.channels.MemChannel.type=memory
TwitterAgent.channels.MemChannel.capacity=10000
TwitterAgent.channels.MemChannel.transactionCapacity=1000
TwitterAgent.sources.Twitter.keywords=
When i run the program it will ask for the keywords first and then it will start collecting the tweets about that keyword.

reading epub file in blackberry

can you tell me a hint to start an Epub reader app for blackberry?
I want the simplest way to do it, is there any browser or UI component that can read & display it?
I want to download it from a server then view it to the user to read it.
couple of days ago, an Epub reader library was added here, I tried to use it, but it has some difficulties, it could open Epubs only from resources, but not from file system, so I decided to download the source and do some adaptation.
First, I wrote a small function that opens the Epub file as a stream:
public static InputStream GetFileAsStream(String fName) {
FileConnection fconn = null;
DataInputStream is = null;
try {
fconn = (FileConnection) Connector
.open(fName, Connector.READ_WRITE);
is = fconn.openDataInputStream();
} catch (IOException e) {
System.out.println(e.getMessage());
return is;
Then, I replaced the call that opens the file in com.omt.epubreader.domain.epub.java, so it became like this:
public Book getBook(String url)
{
InputStream in = ConnectionController.GetFileAsStream(url);
...
return book;
}
after that, I could read the file successfully, but a problem appeared, it wasn't able to read the sections, i.e. the .html files, so I went into a short debug session before I found the problem, whoever wrote that library, left the code that read the .html file names empty, in com.omt.epubreader.parser.NcxParser it was like this:
private void getBookNcxInfo()
{
...
if(pars.getEventType() == XmlPullParser.START_TAG &&
pars.getName().toLowerCase().equals(TAG_CONTENT))
{
if(pars.getAttributeCount()>0)
{
}
}
...
}
I just added this line to the if clause:
contentDataFileName.addElement(pars.getAttributeValue("", "src"));
and after that, it worked just perfectly.

Formating a textfile to display in an EditText on android

I got my little html fisher working and it grabs a text file form a URL string. I can call setText to my EditText view and it will indeed display the text in the text file, but there is like no formatting at all (I am talking simple stuff like carriage returns and line feeds). How can I get this to render a bit more nicely in the EditText? Original text file looks like:
Imagine the following from a resource:
http://www.someaddress.com/thetextfile.txt
Original Text File here.
1. First thing on the text file.
2. Second thing on the text file...
Finally the end of the text file. This is a long string blah blah
that I like to use here. Notice the carriage return line breaks and indentation
on the paragraph.
I can get the above as a string but there is no carriage returns at all when it displays in the EditView. Is there anyway I can add this? Its not a matter of adding \n or \r cause those would already be in the text file I would suspect (was written in Notepad++). So is there anyway to get this even ever so slightly more formatted? (and preserve the formatting when the string is saved back out to disk or to a database?
EDIT:
<EditText android:id="#+id/contract_text_input"
android:layout_width="650sp" android:layout_height="wrap_content"
android:lines="25"
android:scrollbars = "vertical"
android:gravity="top|left" android:inputType="textMultiLine"
android:scrollHorizontally="false"
android:minWidth="10.0dip"
android:maxWidth="5.0dip"/>
EDIT:
These are the methods that fetch this text file from the internet. They seem to be ripping out all the \n and \r. But if I inspect that file that's on line it only has \t's in it. So maybe its filezilla's uploading to my webserver of the file?
public static InputStream getInputStreamFromUrl(String url){
InputStream contentStream = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
contentStream = response.getEntity().getContent();
} catch(Exception e){
e.printStackTrace();
}
return contentStream;
}
public static String getStringFromUrl(String url) {
BufferedReader br = new BufferedReader(new InputStreamReader(getInputStreamFromUrl(url)));
StringBuffer sb = new StringBuffer();
try{
String line = null;
while ((line = br.readLine())!=null){
sb.append(line);
}
}catch (IOException e){
e.printStackTrace();
}
return sb.toString();
}
This is how I am ultimately updating the EditText:
private class FragmentHttpHelper extends AsyncTask<Void, Void, String>{
protected void onPostExecute(String result) {
contractTextTxt.setText(result);
}
#Override
protected String doInBackground(Void... params) {
return getStringFromUrl(urlReferenceTxt.getText().toString());
}
}
Check the Android API. The problem is in the following line of code:
while ((line = br.readLine())!=null)
{
//code goes here
}
The call to readLine() removes newlines, carriage returns and linefeeds. You need to use read() if you want to get everything.
Hi sorry I just did a similar thing in an app of mine
and called
((EditText) findViewById(R.id.textView1))
.setText("Original Text File here.\r\n\r\n1. First thing on the text file.\r\n\r\n2. Second thing on the text file...\r\n\r\n Finally the end of the text file. This is a long string blah blah that I like to use here. Notice the carriage return line breaks and indentation on the paragraph.");
which would be the same as your string
and I get
which looks fine to me!
my edit text was
<EditText android:id="#+id/textView1" android:layout_width="wrap_content"
android:layout_weight="0" android:layout_height="wrap_content"></EditText>
edit sorry huge image
edit2: check the debugger's string value

Resources