Violet_82 89 Posting Whiz in Training

Hi, is any of you guys aware of any online java project I could join in and help? The thing is, even if I still have a very long way to go before I can code pretty decently, I'm a bit tired of learning with exercises, and I thought perhaps it might be good if I actually do something a bit more interesting.
thanks

Violet_82 89 Posting Whiz in Training

Since it looks like nobody is really giving me a hand with it https://www.daniweb.com/programming/web-development/threads/501777/validating-and-submitting-form-field-php and I don't know much about php, I need to reconsider my decision and perhaps look at an off-the-shelf solution. Can anybody suggest a good php contact form handling script please?

thanks

Violet_82 89 Posting Whiz in Training

yes sorry, when I asked that I completely forgot about the separator variable I was using. Still, the variable should have done its job of getting the correct separator, the problem, I suspect, was with another variable:
`filePath = workingDir + "\sample.txt";
because it's using the window separator. In any case, the change has worked, I've just compiled and run the application on Ubuntu, it works :-)!
Thanks, as usual, for all your help with this.
Here is the latest version of the source code (2 files) if anybody is interested.

/*SentenceRecorder.java
takes a sentence or word as input and saves it on text file. Every new word/sentence is appended at the end of the file
*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import static java.awt.GridBagConstraints.*;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Dimension;
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
import java.lang.SecurityException;//if no permission to write to file
import java.io.FileNotFoundException;//if the file can't be created
import java.io.IOException;
import java.util.Properties;//to get working directory
import java.io.BufferedWriter;
public class SentenceRecorder extends JFrame{
    private JLabel instructions;
    private JButton submit;
    private GridBagLayout gbLayout;
    private JButton clear;
    private JTextArea input;    
    private String stringInput;
    private String filePath;
    private String fileName;
    private File file;
    private BufferedWriter fileWriter;
    private String workingDir;
    private String separator;
    private Scanner scannerInput;
    //private Properties workingDir;
    /* private String string1;
    private String string2; */
    public SentenceRecorder(){
        super("List of sentences to remember");
        separator = System.getProperty("line.separator");//getting the system-dependent separator       
        workingDir = System.getProperty("user.dir");
        instructions = new …
Violet_82 89 Posting Whiz in Training

I've managed to send an email finally, here is the working php script:

 <?php
  //require 'PHPMailer-master/PHPMailerAutoload.php';
  //header('Content-Type: application/json');

  $errors = array();



  $title = (isset($_POST['title']) && ($_POST['title'] != '0')) ?  $_POST['title'] : null;
  $firstName = (isset($_POST['firstName']) && !(empty($_POST["firstName"]))) ? $_POST['firstName'] : null;
  $lastName = (isset($_POST['lastName']) && !(empty($_POST["lastName"]))) ? $_POST['lastName'] : null;  
  $emailAddress = (isset($_POST['emailAddress']) && !(empty($_POST["emailAddress"]))) ? $_POST['emailAddress'] : null;
 $website = isset($_POST['website']) ? $_POST['website'] : '';
 $message = (isset($_POST['message']) && !(empty($_POST["message"]))) ? $_POST['message'] : null;

 if ($title === null) {
     $errors[] = 'You must select a title';
 }

 if ($firstName === null) {
     $errors[] = 'You must enter a first name';
     $firstNameError = "You must enter a first name";
 }

 if ($lastName === null) {
     $errors[] = 'You must enter a last name';
 }

 if ($emailAddress === null || filter_var($emailAddress, FILTER_VALIDATE_EMAIL) === false) {
     $errors[] = 'You must enter a valid email address';
 }

 if ($website !== '') {
     if(strpos($website, '://') === false) {
         $website = 'http://' . $website;
     }

     if (filter_var($website, FILTER_VALIDATE_URL, array('flags' => null)) === false) {
         $errors[] = 'You must enter a valid website address';
     }    
 }

 if ($message === null) {
     $errors[] = 'You must enter a message';
 }

 if (empty($errors)) {
     require __DIR__ . '/PHPMailer-master/PHPMailerAutoload.php';

     //SMTP needs accurate times, and the PHP time zone MUST be set
     //This should be done in your php.ini, but this is how to do it if you don't have access to that
     date_default_timezone_set('Etc/UTC');

     /* $mail = new PHPMailer;
     $mail->isSMTP();
     $mail->Host = 'smtp.gmail.com';
     $mail->Port = 587;
     $mail->SMTPSecure = 'tls'; …
Violet_82 89 Posting Whiz in Training

Will try that, but, realistically, what difference is there gonna be between this code (which is the one I have now ):

workingDir = System.getProperty("user.dir");
...
filePath = workingDir + "\\sample.txt";         
file = new File(filePath);

And this (providing I understood correctly your suggestion, when you say getting the directory from system property):

myDir = System.getProperty("user.dir");
fileName = "sample.txt";
File f = new File(myDir, fileName); // creates a File object with that file in that dir

The two should result in the same platform-independent path, shouoldn't they?

Violet_82 89 Posting Whiz in Training

I was just wondering if anybody here on daniweb has any experience of writing twitterbots, for things like, for instance, looking through tweets for keywords and then submitting a link to your own profile when you find an advert that interests you or something like that. I, perhaps naively, never heard of twetterbots till a few months ago, and now I'm quite curious because I hear more and more about that on a regular basis.
What sort of scripting language are they written in?

Violet_82 89 Posting Whiz in Training

that's interesting actually. I've looked that up in the API, but I'm not sure I understand it correctly, meaning I don't undesrtand what it means by "each pathname string is converted into an abstract pathname and the child abstract pathname is resolved against the parent.". So, this application resides in a usb key, in a folder called "gui", here is the full path (in linux):
/media/KINGSTON/JAVA/GUI/2015/createFrames/files/gui
Windows (can't quite remeber, I think it's G:/KINGSTON/JAVA/GUI/2015/createFrames/files/gui):
So, if I use the new file constructor I could, perhaps, do the following:
file = new File(String gui, String sample.txt );
and that will create the sample.txt file inside the gui directory?

Violet_82 89 Posting Whiz in Training

well seems like I've made some progress, but I don't seem to be able to submit the form. I've got the ajax and the validation up but something isn't right and the form hangs for a while and then it doesn't submit. Here is the form inside index.php:

<div class="pseudoPage contact" data-item="contact">
    <h2>Contact us</h2>   
        <p>We're always excited to work on a new project, so give us a shout!</p>
        <p>Fill in the form or drop us a line at <a href="mailto:info@webdevsolutions.xxx">info@webdevsolutions.xxx</a></p>
    <div class="contactForm">
        <!-- <div class="successMsg"><p>Thank you. The form has been submitted.</p></div> -->
        <div class="contactFormPanel">   
            <form id="contactForm">
                <div class="control-group">
                    <label class="control-label" for="title">Title*</label>
                    <div class="controls">
                        <select id="title" name="title" required>
                            <option value="0">Please select</option>
                            <option value="1">Mr </option>
                            <option value="2">Mrs</option>
                            <option value="3">Ms</option>
                            <option value="4">Sir</option>
                        </select>                                    
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="firstName">First name*</label>
                    <div class="controls">
                        <input id="firstName" type="text" name="firstName" value="" required>                                    
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="lastName">Last name*</label>
                    <div class="controls">
                        <input id="lastName" type="text" name="lastName" value="" required>                                  
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="emailAddress">Email address*</label>
                    <div class="controls">
                        <input id="emailAddress" type="text" name="emailAddress" value="" required>                                  
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="website">Website</label>
                    <div class="controls">
                        <input id="website" type="text" name="website" value="">                                 
                    </div>
                </div>
                <div class="control-group">
                    <label class="control-label" for="message">Enter your message*</label>
                    <div class="controls">
                        <textarea id="message" name="message" required></textarea>                                    
                    </div>
                </div>                           
                <div class="control-group">
                    <div class="controls">
                        <div class="button">
                            <!-- <a href="#">Submit</a> -->
                            <input type="submit" name="submit" value="Submit">
                        </div>
                    </div>
                </div>
                <span class="success"></span>
                <span class="error"></span>
            </form>
        </div>
    </div>

</div>

Script form_en.js:

 $(function(){
      $(document).on("submit", "#contactForm", function(e){
          e.preventDefault();

          $form = $(this);

          $.post("../formhandler.php", $form.serialize())
          .then(function (msg){
              $form[0].reset();
             $("span.success").html(msg).show().delay(2500);
         })
         .fail(function (jqXHR) {
             var errors = JSON.parse(jqXHR.responseText); …
Violet_82 89 Posting Whiz in Training

Does anybody have any idea about the above? I'm relly not into php and I'm a bit lost. I suppose I using ajax will be the best way to submit the form so that the page doesn't jump up to the top and then I could combine this with the php validation? Any idea?

Violet_82 89 Posting Whiz in Training

Right, I've made some more changes now:
I added some conditions to allow the form to be submitted or not depending on the error. I've created a variable $errors = 0; to keep an eye at the errors and if there is an error I change the value to 1 if there isn't, it goes back to 0. This allows me to say:

if($errors == 0){
    mail($to,$subject,$currentMessage,$headers);
}

and so I can choose when to submit and when not. No idea if it's good or not, but it seems to work.

Outstanding issues.
1)title: I still can't maintain the selection of the title option after I pressed submit with an error in the form: the form reloads and the selection reverst back to "Please select"
2)When I click submit the page jumps up to the top - as we know and as mentioned in the previous post - but if I add e.preventDefault() in the javascript the form, of course, doesn't submit anymore.
3)After the form has been submitted the data is still there: shouldn't that disappear?

Here is an updated version of the form and the php code:

<?php
//create variables for validation
$titleError = "";
$firstNameError = "";
$lastNameError = "";
$emailAddressError = "";
$messageError = "";
$websiteError = "";
$titleError = "";

$title = "";
$firstName = "";
$lastName = "";
$emailAddress = "";
$message = "";
$website = "";

//mail variables
$to = "bassabasso@gmail.com";
$subject = "New request";
$currentTitle = $_POST["title"]; …
Violet_82 89 Posting Whiz in Training

Um, yes I knew about executable code, but I thought methods were different...eh eh.

Not the first time you have made this mistake (and probably not the last either :)

Yes, I understand now, I'm creating another separator variable rather than initialising it. And yes, alas, I've done that before. However I went back to the console version of this application and I've notice I've made the very same mistake there, only I haven't noticed it and for whatever reason, in the console application it didn't cause any problem. So since that version was fine it didn't even occur to me that I could have made such a mistake: it's not trying to justify it of course, I should've checked, and I'll try not to make the same mistake again, but it's quite a subtle one, I'm sure that with practice I'll learn not to make it again.
It works now, so what I want to do is to changes a few things slightly and make sure that clearing the text in the textarea sits in its own function so I can call it also as soon as I click on the submit button.
One question: here at home I have Ubuntu and I tried to run the application, it compiles OK but when I press submit in the application I get a FileNotFoundException

catch(FileNotFoundException fileNotFoundException){
                System.err.println("Error opening or creating the file");
                System.exit(1);
            }

and get the error message. It's odd in a way because …

Violet_82 89 Posting Whiz in Training

Ah, sorry I didn't know that calls from outside methods were not allowed. Good to know for next time then.
Now i kind of works in the sense that I managed to get something onto the document, but there are a few problems:
1) the format isn't the one I want. It's pretty much the same issue we had before, in the sense that everything runs together in one line (but this time we have the system-specific separator added fileWriter.append(stringInput + separator);) and every input is followed by "null". An interesting thing is that no matter which application I open the file with, everything still runs in one long line, which makes me think that it's not the same issue we had before. Here is a screenshot:
sentenceFile.jpg
Also, I'm thinking to rewrite the ClearButtonHandling in such a way that it calls a function that clear the text area because if I type one sentence, press submit and then type another one, the first sentence is still there and gets added again, so I think that after you press submit I need to clear the text area anyway.

Violet_82 89 Posting Whiz in Training

Cool, in that case I must be doing something wrong because the compiler doesn't like that:

G:\JAVA\GUI\2015\createFrames\files\gui>javac *.java
SentenceRecorder.java:100: error: invalid method declaration; return type required
                CloseFile();
                ^
SentenceRecorder.java:107: error: invalid method declaration; return type required
                CloseFile();
                ^
2 errors

G:\JAVA\GUI\2015\createFrames\files\gui>

Here are the two inner classes with CloseFile();

}//end of constructor
    //inner class for event handlings
    private class ProcessButtonHandling implements ActionListener{
        public void actionPerformed(ActionEvent event){
            stringInput = input.getText();//copy text from textArea to string
            scannerInput = new Scanner(stringInput);            
            try{    
                fileWriter = new BufferedWriter( new FileWriter(file,true));
            }           
            catch(SecurityException securityException){//if you don't have write access
                System.err.println("You don't have write access to this file");
                System.exit(1);
            }
            catch(FileNotFoundException fileNotFoundException){
                System.err.println("Error opening or creating the file");
                System.exit(1);
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                System.exit(1);
            }
            while(scannerInput.hasNext()){
                stringInput = scannerInput.nextLine();
                try{
                    fileWriter.append(stringInput + separator);
                }
                catch(IOException ioexception){
                    System.err.println("General Error with IO");
                    ioexception.printStackTrace();
                    System.exit(1);
                }
                //System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
            }           
        }//end of actionPerformed
        CloseFile();
    }//end of inner class
    private class ClearButtonHandling implements ActionListener{
        public void actionPerformed(ActionEvent event){
            stringInput = "";
            input.setText("");
        }//end of actionPerformed
        CloseFile();
    }

    public void CloseFile(){
        try{
            fileWriter.close();
        }
        catch(IOException ioexception){
                System.err.println("General Error with IO");
                ioexception.printStackTrace();
                System.exit(1);

            }
    }//closeFile
Violet_82 89 Posting Whiz in Training

Edit: ignore the issue with the "message" problem, I sorted it out. It wasn't working because I made a schoolboy error

Violet_82 89 Posting Whiz in Training

HI guys, as mentioned not too long ago here https://www.daniweb.com/programming/web-development/threads/501668/contact-form-building-my-own-or-already-made I'm building my own php script that is supposed to validate and submit form fields to an email address provided. The problem is that I have no real experience of php so I' just doing some readings, getting bits and bobs from different places and add my own code - probably wrong anyway.
In terms of functionality, this is what I would like to build:
-Each field has its own error message displayed if empty or in case of bad input;
-When the form is submitted I need a message somewhere around the form to say something like "Thank you, form submitted" but I need the form to remain visible
-When I press the submit button, since this is a 1 page site, it will scroll back to the top, as you would expect. Normally I'd address this with one line of jquery

$(".contactForm .button input[type='submit']").click(function(e){
        e.preventDefault();
    });

but that wouldn't work here as I need the form to submit. Any other idea?

So, one way or another I've produced something that partially works but there are quite a lot of problems still. What would be great is if somebody could give me a hand to build this and get it to work: if you glance at the code and tell me that needs a completely rebuild, it's fine, at the end of the day, like I said, I'm not really that good …

Violet_82 89 Posting Whiz in Training

Cool. One thing though: if I want to call method CloseFile(); from within the inner class, how should I call you? I can't call it directly like this:

private class ClearButtonHandling implements ActionListener{
        public void actionPerformed(ActionEvent event){
            stringInput = "";
            input.setText("");
        }//end of actionPerformed
        CloseFile();
    }

    public void CloseFile(){
        try{
            fileWriter.close();
        }
        catch(IOException ioexception){
                System.err.println("General Error with IO");
                ioexception.printStackTrace();
                System.exit(1);

            }
    }//closeFile

as CloseFile() sits directly inside the main class but outside of the inner classes. But I don't have any object there?!

Violet_82 89 Posting Whiz in Training

Well, yes I do it there because the closing file will happen after the object sentenceRecorder comes into existence. Ah wait, you mean that because the event (opening of the file and writing the info on the file) takes place only when you click the button, the method CloseFile() is trying to close a file straightaway as soon as the object is created and before the file is even opened?
If that's the case, where would you recommend to call CloseFile() from? How about calling it at the end of each inner class, after method actionPerformed so that everything is done by the time control gets to there?

Violet_82 89 Posting Whiz in Training

Ah, I see thank you.
OK so I think I've done it correctly, the application compiles but I get a runtime error, nothing to do with the opening file I don't think. Let's look at the amendments first.
I've created a scanner variable scannerInput that takes a string input like so scannerInput = new Scanner(stringInput); and then I have the other variables, private JTextArea input; and private String stringInput;, here is the inner class:

import java.util.Scanner;
...
public class SentenceRecorder extends JFrame{
...
    private Scanner scannerInput;
    private JTextArea input;
    private String stringInput;
}
private class ProcessButtonHandling implements ActionListener{
    public void actionPerformed(ActionEvent event){
        stringInput = input.getText();//copy text from textArea to string
        scannerInput = new Scanner(stringInput);            
        try{    
            fileWriter = new BufferedWriter( new FileWriter(file,true));
        }           
        catch(SecurityException securityException){//if you don't have write access
            System.err.println("You don't have write access to this file");
            System.exit(1);
        }
        catch(FileNotFoundException fileNotFoundException){
            System.err.println("Error opening or creating the file");
            System.exit(1);
        }
        catch(IOException ioexception){
            System.err.println("General Error with IO");
            System.exit(1);
        }
        while(scannerInput.hasNext()){
            stringInput = scannerInput.nextLine();
            try{
                fileWriter.append(stringInput + separator);
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                ioexception.printStackTrace();
                System.exit(1);
            }
            //System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
        }           
    }//end of actionPerformed
}//end of inner class

So that seems sorted, but now (well, I say now but let's not forget that I couldn't compile till now) I get 2 NullPointerExceptions. Now, I know from previous experience that this kind of error means that something hasn't been initialized, or it has been used without being initialized, so I went through …

Violet_82 89 Posting Whiz in Training

Cool, thanks.
OK, so now I have a bit of a problem with the GUI and the functionality rather than the look and feel.
So, I have a textArea (input) where you can type your sentence and a String stringInput in which the sentence gets copied to before being processed (copied to a file) and the problem seems to be with the method hasNext() in while(stringInput.hasNext()){ (see the whole inner class here):

private class ProcessButtonHandling implements ActionListener{
        public void actionPerformed(ActionEvent event){
            stringInput = input.getText();//copy text from textArea to string           
            try{    
                fileWriter = new BufferedWriter( new FileWriter(file,true));
            }           
            catch(SecurityException securityException){//if you don't have write access
                System.err.println("You don't have write access to this file");
                System.exit(1);
            }
            catch(FileNotFoundException fileNotFoundException){
                System.err.println("Error opening or creating the file");
                System.exit(1);
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                System.exit(1);
            }
            while(stringInput.hasNext()){
                try{
                    fileWriter.append(stringInput + separator);
                }
                catch(IOException ioexception){
                    System.err.println("General Error with IO");
                    ioexception.printStackTrace();
                    System.exit(1);
                }
                //System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
            }           
        }//end of actionPerformed
    }//end of inner class

I get an error at compiling time saying:

G:\JAVA\GUI\2015\createFrames\files\gui>javac *.java
SentenceRecorder.java:85: error: cannot find symbol
                        while(stringInput.hasNext()){
                                         ^
  symbol:   method hasNext()
  location: variable stringInput of type String
1 error

G:\JAVA\GUI\2015\createFrames\files\gui>

Now, is that because I removed import java.util.Scanner; from the import statements or because the variable (stringInput) I apply the method to is of type String and not Scanner? Trouble is, the data has now changed, in the sense that the sentence to be processed comes from a textArea, that's why …

Violet_82 89 Posting Whiz in Training

OK added them in, sorry when you mentioned it the first time I thought you said that only because I was having a problem with my code, not in general.

Violet_82 89 Posting Whiz in Training

Cool, thanks, I think I'll have a go at it and see if I can knock up something quick. Will open a new thread

Violet_82 89 Posting Whiz in Training

What I'm thinking is that if I go for a DIY solution, how do I make sure that my code isn't in fact a security risk as opposed to one found on the web? I'm tempted to attemp my own, but I will obviously need help from the community as my php isn't so great

Violet_82 89 Posting Whiz in Training

Hi all, I need to add a contact form to a site I'm working on. I'm just thinking whether it would be better to go with an online solution (grab a form from somewhere and use it on my site) or building my own thing (complete with captcha etc). I'm not really good at php although I did build a very basic php form a very long time ago. Do you guys think it is better to go for an already made one? One of the things I'm slightly concerned about if I get one from the net is privacy: would that be an issue as I don't know where the data collected go?
what do you guys think?

Violet_82 89 Posting Whiz in Training

Brilliant, changes made and it works like a treat! Now even notepad is showing one sentence per line.
Coding the GUI now. WIll post back. Here is the code so far:

/*SentenceRecorder.java
takes a sentence or word as input and saves it on text file. Every new word/sentence is appended at the end of the file
*/
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
import java.lang.SecurityException;//if no permission to write to file
import java.io.FileNotFoundException;//if the file can't be created
import java.io.IOException;
import java.util.Properties;//to get working directory
import java.io.BufferedWriter;
public class SentenceRecorder{
    private Scanner input;
    private String stringInput;
    private String filePath;
    private File file;
    private BufferedWriter fileWriter;
    private String workingDir;
    private String separator;
    //private Properties workingDir;
    /* private String string1;
    private String string2; */
    public SentenceRecorder(){
        String separator = System.getProperty("line.separator");//getting the system-dependent separator
        workingDir = System.getProperty("user.dir");
        //System.out.println("workingDir is " + workingDir);
        input = new Scanner(System.in);     
        filePath = workingDir + "\\sample.txt"; 
        //filePath = "G:\JAVA\GUI\2015\createFrames\files";
        file = new File(filePath);      

        System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
        try{    
                fileWriter = new BufferedWriter( new FileWriter(file,true));
            }           
            catch(SecurityException securityException){//if you don't have write access
                System.err.println("You don't have write access to this file");
                System.exit(1);
            }
            catch(FileNotFoundException fileNotFoundException){
                System.err.println("Error opening or creating the file");
                System.exit(1);
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                System.exit(1);
            }
        while(input.hasNext()){
            stringInput = input.nextLine();                     
            try{
                fileWriter.append(stringInput + separator);
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                System.exit(1);
            }
            System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
        }       
    }//end of constructor
    public void CloseFile(){
        try{
            fileWriter.close();
        }
        catch(IOException ioexception){ …
Violet_82 89 Posting Whiz in Training

Ok, had a look. So I can't really

wrap your FileWriter in a BufferedWriter

like fileWriter = new BufferedWriter(new FileWriter(file,true)); as fileWriter is of FileWriter type, so, can I change the type of fileWriter to be BufferedWriter and then write something like that

...
BufferedWriter fileWriter;
    try{    
                    fileWriter = new BufferedWriter(new FileWriter(file,true));                    
                }           
                catch(SecurityException securityException){//if you don't have write access
                    System.err.println("You don't have write access to this file");
                    System.exit(1);
                }
                catch(FileNotFoundException fileNotFoundException){
                    System.err.println("Error opening or creating the file");
                    System.exit(1);
                }
                catch(IOException ioexception){
                    System.err.println("General Error with IO");
                    System.exit(1);
                }

then use BufferedWriter's newLine() method to write a system-dependent new line char opr sequnce as apropriate.

Reading the API for newLine() got me thinking: about about creating a string variable and doing something like this:

String separator = System.getProperty("line.separator");
...
try{
        fileWriter.append(stringInput + " " + separator);
    }

Would that work?

Violet_82 89 Posting Whiz in Training

OK thanks for the explanation :-). I'll build the GUI now (good luck to me!)

Violet_82 89 Posting Whiz in Training

Ah OK, I see what you mean. I'm on windows at the moment, and notepad displays this
files_notepad.jpg
whereas notepad ++ displays this (which is what I wanted)
files_notepad_++.jpg
Is there a way to get them to behave in the same fashion? I presume the problem is that "/n" in the sense that some editors "read" it some don't. Is that the case? But then again, have I then misinterpreted what the API says

This method returns the rest of the current line, excluding any line separator at the end.

I thought that meant that the "/n" will be effectively be ignored when using nextLine()?

Violet_82 89 Posting Whiz in Training

The file is going to the current working directory, which happens to be where the app is because that's how you're running it.

Ok thanks for clarifying that.
So, amendments done. Now I find the current directory and create the file in that directory. I've also amended the fileWriter issue, now I understand what a stupid mistake I was making.
But I still have an issue: the string entered are rendered on the same line as opposed to be on separate lines. I had a look at the API for nexLine() which is what I'm using and says that "This method returns the rest of the current line, excluding any line separator at the end. "
So rather than

while(input.hasNext()){
            stringInput = input.nextLine();                     
            try{
                fileWriter.append(stringInput + " " + "\n");
            }

I tried

while(input.hasNext()){
            stringInput = input.nextLine();                     
            try{
                fileWriter.append( " " + "\n" + stringInput);
            }

(I wouldn't want to have an empty line to start with, but I thought I'd just truy anyway), but no difference. What would I ned to use to include the /n in the string then?

Here are the amendments you suggested to the constructor:

public SentenceRecorder(){
        workingDir = System.getProperty("user.dir");
        //System.out.println("workingDir is " + workingDir);
        input = new Scanner(System.in);     
        filePath = workingDir + "\\sample.txt"; 
        //filePath = "G:\JAVA\GUI\2015\createFrames\files";
        file = new File(filePath);      

        System.out.printf("Enter your sentence or end of file - ctrl+z or Enter+ctrl+d\n");
        try{    
                fileWriter = new FileWriter(file,true);
            }           
            catch(SecurityException securityException){//if you don't have write access
                System.err.println("You don't have …
Violet_82 89 Posting Whiz in Training

OK, sorted. Basically I replaced the string filePath = "C:/sample.txt"; with filePath = "sample.txt"; and that does the trick. Just realised that this saves the file on the same directory where the application resides, so this will also guarantee support across platform as there are no file separators or full paths involved.
Just one more thing.
I run the application and it kind works but not in every single scenario. Here a a couple of runs.

G:\JAVA\GUI\2015\createFrames\files>java SentenceRecorderTest
Enter your sentence
Sentence 1
^Z
G:\JAVA\GUI\2015\createFrames\files>

This worked. The file now contains "Sentence 1".
Another round (without recompiling the application), and here the problems are evident:

G:\JAVA\GUI\2015\createFrames\files>java SentenceRecorderTest
Enter your sentence
Sentence 2
Sentence 3
^Z
G:\JAVA\GUI\2015\createFrames\files>

The file should now contain all the 3 sentences but in fact it has only:

Sentence 1Sentence 3

So "sentence 2" is lost, overwritten by sentence 3. Is that normal behaviour? What I did was to input the first sentence, then pressed Enter and I had a new empty line, then I input the second sentence ("Sentence 3") and press Enter again but I've lost the previous input and I'm not sure why that is.
Also, I want every sentence appended to the file to be on a separate line, so I amended fileWriter.append(stringInput); to be fileWriter.append(stringInput + "\n"); but no joy. I checked the API and one of the constructors is append(String str) so that should work shouldn't it?
So 2 issues:
-lost input

Violet_82 89 Posting Whiz in Training

Hi thanks, sorry for the slow reply, been busy at work.
As for the other exception, got to admit I haven't come across it in the examples I've looked at, and they all work OK. Strange. In any case, I've looked that up, and it's just a general exception.
I've added this to the import declarations import java.io.IOException; and changed the code to this:

/*SentenceRecorder.java
takes a sentence or word as input and saves it on text file. Every new word/sentence is appended at the end of the file
*/
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
import java.lang.SecurityException;//if no permission to write to file
import java.io.FileNotFoundException;//if the file can't be created
import java.io.IOException;
public class SentenceRecorder{
    private Scanner input;
    private String stringInput;
    private String filePath;
    private File file;
    private FileWriter fileWriter;
    /* private String string1;
    private String string2; */
    public SentenceRecorder(){
        input = new Scanner(System.in);     
        filePath = "C:/sample.txt";             
        file = new File(filePath);      

        System.out.printf("Enter your sentence");
        while(input.hasNext()){
            stringInput = input.nextLine();
            try{    
                fileWriter = new FileWriter(file,true);
            }           
            catch(SecurityException securityException){//if you don't have write access
                System.err.println("You don't have write access to this file");
                System.exit(1);
            }
            catch(FileNotFoundException fileNotFoundException){
                System.err.println("Error opening or creating the file");
                System.exit(1);
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                System.exit(1);
            }           
            try{
                fileWriter.append(stringInput);
            }
            catch(IOException ioexception){
                System.err.println("General Error with IO");
                System.exit(1);
            }
        }       
    }//end of constructor
    public void CloseFile(){
        try{
            fileWriter.close();
        }
        catch(IOException ioexception){
                System.err.println("General Error with IO");
                System.exit(1);
            }
    }//closeFile
}//end of SentenceRecorder

Funny thing is that the compiler wanted me to add a general exception pretty …

Violet_82 89 Posting Whiz in Training

Yes, copy and paste error, sorry for that, but that's not the issue. I refactor the whole thing in the end as I couldn't find a solution:

/*COOKIES*/
function initCookieAlert(){
    //alert("initCookieAlert called");
    var $HTMLcookieString = $('<div class="cookie-alert" style="display:none"><div class="cookie-content"><p>We use cookies to improve your experience on our website. We never pass this data on. See our <a href="#" data-policy="cookiePol" class="cookiePol">Privacy Policy</a></p><div class="cookieButton"><a href="#" class="accept">Accept</a></div><div class="clear_floats"></div></div></div>');
    //eraseCookie();//uncomment to test and delete cookies

    if(readCookie('COOKIE') != "accepted"){
        $HTMLcookieString.appendTo(".carouselImages");
        $HTMLcookieString.clone().appendTo(".policyWrapper").show();
        $HTMLcookieString.show();
        //console.log($(".cookieButton a").length + " cookie buttons");
        $(".cookieButton a").click(function(event){         
            event.preventDefault();
            createCookie("COOKIE","accepted",365);
            //$(".cookieButton a").parents("div.cookie-alert").hide();

            $(".cookieButton a").parents("div.cookie-alert").fadeOut(500, function(){
                if($(this).parents(".policyWrapper")){//if it's the button inside the policy container
                    $('html, body').animate({scrollTop:0}, 'fast');//scroll to the top
                }
            });
        });     
    }
}
Violet_82 89 Posting Whiz in Training

Hi guys,
I'm having some problem with cloning a div with a button in and its functionality. 2 words about the functionality first. Basically I'm creating some HTML with javascript (it has to be done that way I'm afraid) and append it at the top of the page. I also have to append the same HTML snippet at the bottom of the page and make sure that the button inside this container keeps the same functionality, This HTML snippet is essentially my cookie policy and when I click the "accept" button (wherever it is, top or bottom of the page) both buttons and their cookie containers need to disappear. But I can't get it to work. None of the two HTML snippets appear. Let's see some code:

$(document).ready(function(){
    initCookieAlert();//cookie function
    ...
});

/*COOKIES*/
function initCookieAlert(){
    //alert("initCookieAlert called");
    var $HTMLcookieString = $('<div class="cookie-alert" style="display:none"><div class="cookie-content"><p>We use cookies to improve your experience on our website. We never pass this data on. See our <a href="#" data-policy="cookiePol" class="cookiePol">Privacy Policy</a></p><div class="cookieButton"><a href="#" class="accept">Accept</a></div><div class="clear_floats"></div></div></div>');
    var $HTMLcookieStringClone = $HTMLcookieString.clone();//clone previous string
    //eraseCookie();//uncomment to test and delete cookies
    if(readCookie('COOKIE') != "accepted"){
        $("a.accept").click(function(event){//if the accept buttons are clicked
            alert("clicked");
            event.preventDefault();
            createCookie("COOKIE","accepted",365);
            $(this).parents("div.cookie-alert").hide();

        });
        $HTMLcookieString.appendTo(".carouselImages");//append first HTML       
        HTMLcookieStringClone.appendTo(".policyWrapper").show();//append clone and show
        $HTMLcookieString.show();
    }
}

So, to put things in context, this is an older version http://antonioborrillo.co.uk/agency_test/home.html where you can see the first cookie policy at the top. With the code above I should clone that and add it to the bottom of the page, …

Violet_82 89 Posting Whiz in Training

Difficult to say at this stage, i think it might go up to three, but no more than that. Seen what's involved and considered the size of the site (not one page but two now because of the darn privacy policy that I haven't added as yet) I'm quite happy with this approach, but yes, I see your point, should the number of the languages grow, this approach is unsustainable

Violet_82 89 Posting Whiz in Training

Right, I think I'm having some issues with possible exceptions in my code as the compiler is complaning.
It seems like there are an awful lot of ways to write things to file, so I guess I just picked one and went for it. Essentially, I believe I created a file, got the input from the keyboard and attempted to write that to file. Here is the code:

/*SentenceRecorder.java
takes a sentence or word as input and saves it on text file. Every new word/sentence is appended at the end of the file
*/
import java.io.File;
import java.util.Scanner;
import java.io.FileWriter;
import java.lang.SecurityException;//if no permission to write to file
import java.io.FileNotFoundException;//if the file can't be created
public class SentenceRecorder{
    private Scanner input;
    private String stringInput;
    private String filePath;
    private File file;
    private FileWriter fileWriter;
    /* private String string1;
    private String string2; */
    public SentenceRecorder(){
        input = new Scanner(System.in);     
        filePath = "C:/sample.txt";
        try{            
            file = new File(filePath);
        }
        catch(SecurityException securityException){//if you don't have write access
            System.err.println("You don't have write access to this file");
            System.exit(1);
        }
        catch(FileNotFoundException fileNotFoundException){
            System.err.println("Error opening or creating the file");
            System.exit(1);
        }
        System.out.printf("Enter your sentence");
        while(input.hasNext()){
            stringInput = input.nextLine();
            fileWriter = new FileWriter(file,true);
            fileWriter.append(stringInput);
        }       
    }//end of constructor
    public void CloseFile(){
        fileWriter.close();
    }//closeFile
}//end of SentenceRecorder



The compiler is saying:
G:\JAVA\GUI\2015\createFrames\files>javac *.java
SentenceRecorder.java:27: error: exception FileNotFoundException is never thrown in body of corresponding try statement
                catch(FileNotFoundException fileNotFoundException){
                ^
SentenceRecorder.java:34: error: unreported exception IOException; must be caught or declared to be thrown
                        fileWriter = new FileWriter(file,true);
                                     ^
SentenceRecorder.java:35: error: …
Violet_82 89 Posting Whiz in Training

Ah OK, I will amend the link and remove the page name.
About the url change, I meant the one I have now isn't what I will have when the site is launched, but nevermind, not to worry. One thing I've just realized is that I need to add another page, the darn privacy policy page, and that will have to be in two languages, do you think it is OK to take the same approach and have two privacy.php pages, one inside the "en" and one in the "in" directory and use the language script approach to get one or the other?
One more thing: the privacy div currently displayed on the top of the page is generated by a script (cookies.js). Since I have two versions of the pages, I also have two versions of the cookies.js (sitting in the respective folde "en" and "it"), one generating the english cookie message the other one generating the italian cookie message, so depending on which script I'm in, I will provide the relevant link (en/privacy.php for the cookies.js inside the "en" folder and it/privacy.php for the cookies.js inside the "it" folder)

Violet_82 89 Posting Whiz in Training

I think that haas worked pretty well http://antonioborrillo.co.uk/agency_test/test/en/index.php thanks for all your help. Just one thing though: the url will obviously change at some point, but when it does and will look something like www.mysite.com/index.php or do I have to include the "en" and "it" directories?

Violet_82 89 Posting Whiz in Training

thanks. I don't envisage it to get too big, in fact, it will never go past a few MB to be honest, I mean for me it is more a test than anything, I don't see myself using that application every tme, it's just for the sake of building it really.
For me sequential or serialization is the same, in the sense that, I've never used any of them, so I'll just go with whatever you guys think it's best, happy to go for sequential access, if it is better for text only.
A database isn't an option now, because, even if I've worked with databases before, it was in a different setting (ASP.NET) and I haven't got to the "databases with java" part as yet :-)
I don't even need to tag the entries, it will literally be just text, each word/sentence will occupy its own space, then a new line feed and the new sentence/word, and so on, it will be that simple.
OK, so start to build it then.

Violet_82 89 Posting Whiz in Training

Hi guys,
Today I had a look at files and therefore I’d like to create a GUI application that allows me to type a sentence or a word and store it to a text file. The reason for this is that, when I come across an interesting word or sentence I like to keep it somewhere for future reference, which means that the new word/sentence needs to be appended at the end of the file, without overwriting anything. It should also allow for multiple languages, but I don’t see that being a problem.
Following from other applications I developed, and the advices kindly given, I’ll leave the GUI as a last thing (will do it with GridBagLayout of course), so I’ll first create an application that takes a sentence/word as a hardcoded string.
The way I envisage this, providing you guys think it is a good idea, is to have a JTextArea that takes the sentence and then an action button (Save) that will allow the application to save the input to a text file.
I’ve read a bit about Sequential-access text files and object serialization. I’m a bit torn between one and the other, and here is why: I don’t really need to amend the sentence/words I write, the idea is that, I write them to file and they are there for when I want to open the file and take a look at them, but then again, what happens if I make a mistake, …

Violet_82 89 Posting Whiz in Training

Ah OK, got it, sorry I think I misunderstood the first time around, and hardcoded my language menu rather than building it dynamically as you wanted me to do it :-).
Sure thing will do that and rename the files, will post back later.
Thanks again for your help.

Violet_82 89 Posting Whiz in Training

HI sorry, one question. I have my two php pages now, each sitting in its own subfolder (en and it) and each of them with the relevant language php script (placed before the DOCTYPE), as you said above, so something liek this:

home.php (this is the english version where you can see the script and the actual language navigation, div with a class of languageSelection). The home.php inside the subfolder "it" is similar with the version of the php script supporting the italian language and the translation

<?php
    $thisLanguage = 'en';
    $en = '/en/page.php';
    $it = '/it/pagina.php';
?>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Website test</title>
        <link rel="stylesheet" type="text/css" href="../style.css">
        <link rel="stylesheet" type="text/css" href="../tablet.css">
        <link rel="stylesheet" type="text/css" href="../mobile.css">
        <script src="../jquery-1.11.3.min.js"></script>
        <script src="../script.js"></script>
    </head>
    <body>
        <div class="wrapper">
            <div class="header">
                <!-- burger menu -->
                <a href="#" class="burgerMenu"><img src="../images/burger_menu.png" alt=""></a>
                <!-- logo -->
                <a href="#" class="logo"><img src="../images/logo.png" alt=""></a>
                <!-- navigation -->
                <div class="navigation">
                    <a href="#">Home</a>
                    <a href="#" data-item="service">What we can do for you</a>
                    <a href="#" data-item="contact">Get in touch</a>
                    <a href="#" data-item="showcase">Our work</a>
                    <div class="clear_floats"></div>
                </div>
                <div class="languageSelection">
                    <ul>
                        <li class="selected"><a href="#">en |</a></li>
                        <li><a href="#">it</a></li>
                    </ul>
                    <div class="clear_floats"></div>
                </div>
            </div>

There is another script though, this one:

<?php
    echo '<ul class="lang-nav">';
    if ($thisLanguage=='it') echo '<li class="current"><a href="#">IT</a></li><li><a href="' . $en. '">EN</a></li>';
    if ($thisLanguage=='en') echo '<li><a href="' . $it. '">IT</a></li><li class="current"><a href="#">EN</a></li>';
    echo '</ul>';
?>

Where should that go? I couldn't see that on your website (the example)
thanks

Violet_82 89 Posting Whiz in Training

All done and working.

rproffitt commented: Advance +1. +0
Violet_82 89 Posting Whiz in Training

Cool, well I think apache and php will be fine as most providers don't have ISS servers from what I understand. As mentioned the site is pretty small, in fact here it is http://antonioborrillo.co.uk/agency_test/home.html so you can have a better idea of what I'm doing. In terms of languages, I think for now it's two of them, but we could have more in the future.
I'll start implementing your solution gentlemedia - it might take a few days depending how much time I've got at the moment, but i leave this thread open, and post back if I run into problems

Violet_82 89 Posting Whiz in Training

Thanks guys, really useful. I reckon I should've said that the site I'm working at is a very small one, in fact it's a one page website. I had a look at both the examples and I quite like gentlemedia approach as it seems easy to extend if I want to add more languages in the future. The thing is that I have absolutely no experience with .htaccess redirect and the like, so I will probably need to do some readings and probably ask for more help later
Presumably the .htaccess redirect file goes onto the server correct? And that server has to Apache software running on it?
Also, just so I understand the whole thing correctly, and how the html files are arranged, sorry it might be obivous to you but I know only very basic php:
-On your site you use effectively 3 subdomains, en nl and de.
-then you have a .htaccess redirect file which contains (in my case would contain) only this, and this file sits where exactly, in the root folder?

#language redirects
RewriteEngine on
RewriteCond %{HTTP:Accept-Language} ^it [NC]
RewriteRule ^$ /it/ [L,R=301]
RewriteRule ^$ /en/ [L,R=301]

-there are no html pages as such, all your pages are in .php extension because they all contain their own small language-specific php script
-each php page contains its own language version, so all the content is effectively duplicated in the relevant language, except for the navigation?
So the folder structure …

Violet_82 89 Posting Whiz in Training

That sounds good to me. Is that implemented clientside or server side? How does that work in practice? Like, do I effectively need two sites with the same URL or two different ones?
thanks

Violet_82 89 Posting Whiz in Training

I see what you mean, thanks for the feedback, much appreciated :-)!

Violet_82 89 Posting Whiz in Training

Looks like the compiler doesn't like the amendments:

public void countWords(){       
        for (String token : tokens) {
             mp.put(token, mp.getOrDefault(token, 0) +1);
        }
    }

Produces this:

G:\JAVA\GUI\2015\createFrames\word_counter\gbl\preferredSize>javac *.java
WordCount.java:108: error: cannot find symbol
             mp.put(token, mp.getOrDefault(token, 0) +1);
                             ^
  symbol:   method getOrDefault(String,int)
  location: variable mp of type Map<String,Integer>
1 error

G:\JAVA\GUI\2015\createFrames\word_counter\gbl\preferredSize>
Violet_82 89 Posting Whiz in Training

Fair enough so I won't change anything else as far as the GUI is concerned.
Nothing wrong at all with your suggestion of course, I somehow prefer the classic for loop, that's why I used it, more than happy to change it to yours if it's better :-)!
Perhaps mapWords() could then be countWords() ?

Violet_82 89 Posting Whiz in Training

Thanks, yes I did and I didn't see anything different from when that line was in there :-). I mean I suppose it is OK, in the sense that when I run the application it opens up in a window that is 464x518. Admittedly it's a bit small for my 22inches monitor, but then again, bearing in mind what you said before, perhaps it isn't the end of the world? Or do you think it is better, if possible of course, to force the window to be full width regardless of the device? What's the best practice in the industry?

Here is the whole code for reference:

/*WordCountTest.java
    WordCountTest to test the class
*/
import javax.swing.JFrame;
public class WordCountTest{
    public static void main(String[] args){
        WordCount wordCount = new WordCount();
        wordCount.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //wordCount.setSize(900,800);
        wordCount.pack();
        wordCount.setVisible(true);
    }//end of main
}//end of WordCountTest



/*WordCount.java
Application determines how many times a word has occurred in the text given
*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import static java.awt.GridBagConstraints.*;
import java.awt.Insets;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.awt.Dimension;//to sort specify the dimension
public class WordCount extends JFrame{
    private JTextArea textInput;
    private JTextArea textOutput;
    private JButton processButton;
    private JButton clearButton;
    private JLabel instructions;
    private GridBagLayout gbLayout;
    /* private GridBagConstraints inputConstraints;//declare constraints input textAea
    private GridBagConstraints outputConstraints;//declare constraints output textArea
    private GridBagConstraints CountConstraints;//declare constraints count button
    private GridBagConstraints ClearConstraints;//declare constraints clear button
    private GridBagConstraints instructionsConstraints;//declare constraints JLabel */
    private …
Violet_82 89 Posting Whiz in Training

Hi guys, I'm working at a website that, among the other things, the client has requested to be multilingual. The way I envisage it to work is this: if you browse the site from, say, Italy, you get the italian version (with the option to change the language to english of course), otherwise, from anywhere else, you get the default english version, but again with the option to change the language to italian if you wish to (with the option to be able to increase the number of languages). I'm planning to keep only one URL (www.mysite.com) regardless of where you browse from I'm not using any CMS or anything, and that's why I'm not sure what the best way to proceed is. I know that some platforms are offering some nice plugins just to solve issues like that, but I don't want to be using Wordpress or whatever only for that reason (and besides the site is almost ready and I really don't want to re-do the whole thing with wordpress). My site has no CMS at all and I'm not using any funky platform. Can anybody help me thinking of a good solution (got to admit I'm not particularly good in the subject)? Also any advice in general is appreciated

Violet_82 89 Posting Whiz in Training

OK, so if I leave things as they are and remove this wordCount.setSize(900,800); I get everything I need as the application width is all taken care of. Is that correct?