Hello i am trying to make a program that will allow me to load in a file and upload the name of it to a list. Once i select a file name in the list it should go through that file and take each line an put it in the specified jtextfield. But when i try and load a second file and try and select it, it tells me arrayIndexOutOfBounds. Can someone please explain to me what I'm doing wrong. I am using NetBeans.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package prog24178.assignment4;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
public class CustomerView extends javax.swing.JFrame {
/**
* Creates new form CustomerView
*/
private Application ass4App = new Application();
public ArrayList<Customer> customer = new ArrayList<Customer>();
public ArrayList<String> names = new ArrayList<String>();
public String fileName;
public Customer customers = new Customer();
public int i;
public void setApplication(Application customerApp) {
this.ass4App = ass4App;
}
public CustomerView() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
private void jExitItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.exit(0);
}
private void jOpenCusItemActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String currentPath = System.getProperty("user.dir");
JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File[] file = fc.getSelectedFiles();
for (int i = 0; i < file.length; i++) {
try {
customers.constructCustomer(file[i]);
} catch (FileNotFoundException ex) {
Logger.getLogger(CustomerView.class.getName()).log(Level.SEVERE, null, ex);
}
customer.add(customers);
names.add(customer.get(i).getName());
}
jCustomerList.setListData(names.toArray());
}
}
private void jCustomerListValueChanged(javax.swing.event.ListSelectionEvent evt) {
// TODO add your handling code here:
jCusNameField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getName());
jAddressField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getAddress());
jCityField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getCity());
jProvinceField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getProvince());
jPostalCodeField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getPostalCode());
jEmailAddressField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getEmailAddress());
jPhoneNumberField.setText((String) customer.get(jCustomerList.getSelectedIndex()).getPhoneNumber());
}
I fix the problem. I realized that i was just adding the variable customers to customer without giving it a proper value.
customer.add(customers.constructCustomer(file[i]));
I don't know what customers.constructCustomer(file[i]); or customer.add(customers); do, exactly -- we don't have enough code to know -- but you are using i to iterate through the array of File objects and to obtain a customer (customers.get(i)). That's the second place I'd look.
The FIRST place I'd look is at the error message; it tells you the line on which the array index was out of bounds, the value of the index, and the upper bound on the array.
Related
So everything is showing correctly in my Java IDE and runs as it should. I have it where the data automatically writes to the csv file every few minutes. The problem I'm having is that the "Meter 2" column is not showing up and I have a feeling that the HashSet in my code might think that it's a duplicate and deleting it.
Here's the code:
package HourMeter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Hours {
Set<String> hour = new HashSet<>();
String filename;
/**
* #param filename filename of the .csv file to update
* #param addresses Array of Strings of addresses to add to the .csv file
* #throws IOException Throws exception on incorrect filename
*/
public Hours(String filename, String[] addresses) throws IOException {
if(filename==null) throw new IllegalArgumentException();
this.filename = filename;
try (BufferedReader reader = new BufferedReader(new
FileReader("Hours.csv"))) {
while(reader.ready())
{
hour.add(reader.readLine());
}
}
if(addresses != null)
{
hour.addAll(Arrays.asList(addresses));
}
}
Hours(String string) {
throw new UnsupportedOperationException("Not supported yet."); //To
change body of generated methods, choose Tools | Templates.
}
public void outputFile() throws IOException
{
try (PrintWriter out = new PrintWriter("Hours.csv")) {
hour.forEach((s) -> {
out.println(s);
});
}
}
}
Below is a photo of the program and the csv report.
As you can see, the csv report is missing a set of string values, meter 2. What should I think about doing or changing in my code to make this show in the csv report? Thanks for the help. I have been trying to figure this out for a few days now. Any help would be greatly appreciated!
Is it possible in Apache Flink to write to multiple text files depending on a key? For instance, I have some data like this.
key1, foo, bar
key2, baz, foo
key3, etc, etc
The value of the key isn’t known at compile time; new keys would come in and I’d like to write the results for that key to a separate file to those of the other keys.
I'd expect to see 3 files, named 'key1.txt', 'key2.txt' and 'key3.txt'.
Is this something Flink can do out of the box?
You can try the following sink's implementation, which can be used with KeyedStream :
KeyedStream<Tuple2<String, String>, Tuple> keyedDataStream = dataStream.keyBy(0);
StreamKeyPartitionerSink<Tuple2<String, SynopsesEvent>> sinkFunction = new StreamKeyPartitionerSink<Tuple2<String, SynopsesEvent>>(
"../data/key_grouping", "f0"); // f0 is the key field name
keyedDataStream.addSink(sinkFunction);
For more info about state managament in Flink : https://ci.apache.org/projects/flink/flink-docs-release-1.3/dev/stream/state.html#keyed-state since I used it for managing state per key.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
/**
* * Flink sink writes tuples to files partitioned by their keys, which also writes the records as
* batches.
*
* #param <IN> Input tuple type
*
* #author ehabqadah
*/
public class StreamKeyPartitionerSink<IN> extends RichSinkFunction<IN> {
private transient ValueState<String> outputFilePath;
private transient ValueState<List<IN>> inputTupleList;
/**
* Number of rcords to be hold before writing.
*/
private int writeBatchSize;
/**
* The output directory path
*/
private String outputDirPath;
/**
* The name of the input tuple key
*/
private String keyFieldName;
public StreamKeyPartitionerSink(String outputDirPath, String keyFieldName) {
this(outputDirPath, keyFieldName, 1);
}
/**
*
* #param outputDirPath- writeBatchSize the size of on hold batch before write
* #param writeBatchSize - output directory
*/
public StreamKeyPartitionerSink(String outputDirPath, String keyFieldName, int writeBatchSize) {
this.writeBatchSize = writeBatchSize;
this.outputDirPath = outputDirPath;
this.keyFieldName = keyFieldName;
}
#Override
public void open(Configuration config) {
// initialize state holders
`//for more info about state management check `//
ValueStateDescriptor<String> outputFilePathDesc =
new ValueStateDescriptor<String>("outputFilePathDesc",
TypeInformation.of(new TypeHint<String>() {}));
ValueStateDescriptor<List<IN>> inputTupleListDesc =
new ValueStateDescriptor<List<IN>>("inputTupleListDesc",
TypeInformation.of(new TypeHint<List<IN>>() {}));
outputFilePath = getRuntimeContext().getState(outputFilePathDesc);
inputTupleList = getRuntimeContext().getState(inputTupleListDesc);
}
#Override
public void invoke(IN value) throws Exception {
List<IN> inputTuples =
inputTupleList.value() == null ? new ArrayList<IN>() : inputTupleList.value();
inputTuples.add(value);
if (inputTuples.size() == writeBatchSize) {
writeInputList(inputTuples);
inputTuples = new ArrayList<IN>();
}
// update the state
inputTupleList.update(inputTuples);
}
/**
* Write the tuple list, each record in separate line
*
* #param tupleList
* #throws Exception
*/
public void writeInputList(List<IN> tupleList) {
String path = getOrInitFilePath(tupleList);
try (PrintWriter outStream = new PrintWriter(new BufferedWriter(new FileWriter(path, true)))) {
for (IN tupleToWrite : tupleList) {
outStream.println(tupleToWrite);
}
} catch (IOException e) {
throw new RuntimeException("Exception occured while writing file " + path, e);
}
}
private String getOrInitFilePath(List<IN> tupleList) {
IN firstInstance = tupleList.get(0);
String path = null;
try {
path = outputFilePath.value();
if (path == null) {
Field keyField = firstInstance.getClass().getField(keyFieldName);
String keyValue = keyField.get(firstInstance).toString();
path = Paths.get(outputDirPath, keyValue + ".txt").toString();
setUpOutputFilePathPath(outputDirPath, path);
// save the computed path for this key
outputFilePath.update(path);
}
} catch (IOException | NoSuchFieldException | SecurityException | IllegalArgumentException
| IllegalAccessException e) {
throw new RuntimeException(
"ExceptionsetUpOutputFilePathPath occured while fetching the value of key field " + path,
e);
}
return path;
}
private void setUpOutputFilePathPath(String outputDirPath, String path) throws IOException {
if (!Files.exists(Paths.get(outputDirPath))) {
Files.createDirectories(Paths.get(outputDirPath));
}
// create the file if it does not exist and delete its content
Files.write(Paths.get(path), "".getBytes(), StandardOpenOption.CREATE,
StandardOpenOption.TRUNCATE_EXISTING);
}
}
That is not possible ouf-of-the-box. However, you can implement an own output format and use it via result.out(...) (for Batch API); see https://ci.apache.org/projects/flink/flink-docs-release-1.1/apis/batch/index.html#data-sinks
For Streaming API, it would be stream.addSink(...); see https://ci.apache.org/projects/flink/flink-docs-release-1.1/apis/streaming/index.html#data-sinks
The code breaks if I'm using it in this combination:
Save a value, Delete a value, Save a value.
The moment I save that value a 2nd time it will even add the deleted values back to it.
So if I would save the configurations 1, 2 ,3, 4, delete 3, and save 5, this would save 3 as well making the final values : 1,2,3,4,5 even though I deleted 3.
Here is the code that I think is important
/**
* This is the save class.
* This class contains the action for when the user clicks on the save button.
*/
package controller;
/**
* These are the imports for the class.
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import model.ModelFacade;
public class Save {
/**
* These are the fields for the class.
*/
ModelFacade mf = new ModelFacade();
Properties prop = new Properties();
/**
* This method sets the entered value for the matching property.
*
* #param property
* #param value
*/
public void setPropertyValue(String property, String value) {
try {
try{
//set the properties value
FileInputStream fis = new FileInputStream("config.properties");
prop.load(fis);
fis.close();
prop.setProperty(property, value);
}
catch (IOException ex) {
}
//save properties to project root folder
FileOutputStream fos = new FileOutputStream("config.properties");
prop.store(fos, null);
fos.close();
System.out.println("saved " + property + " as " + value);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* This is the delete class.
* This class contains the action for when the user clicks on the delete button.
*/
package controller;
/**
* These are the imports of the class.
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import model.ModelFacade;
public class Delete {
/**
* These are the fields of the class.
*/
ModelFacade mf = new ModelFacade();
Properties prop = new Properties();
/**
* This method deletes the values of the selected config.
*
* #param config
*/
public void deleteAction(String config) {
if(mf.checkProperty() == true){
try {
FileInputStream fis = new FileInputStream("config.properties");
prop.load(fis);
fis.close();
#SuppressWarnings("rawtypes")
Enumeration em = prop.keys();
int i = 0;
while(em.hasMoreElements()){
Object obj = em.nextElement();
String str = (String)obj;
//If the property contains the configuration name in its name it will be deleted.
if(str.endsWith(config)){
i++;
System.out.println("Deleted: "+str);
prop.remove(str);
FileOutputStream fos = new FileOutputStream("config.properties");
prop.store(fos, null);
fos.close();
}
}
//The system prints a message of the missing configuration.
if(i < 1){
System.out.println("The configuration could not be found.");
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//The system prints a message that the property file could not be found.
else{
System.out.println("The property file could not be found.");
}
}
}
These are the 2 methods that are being used. I hope this is enough information for you to help. And sorry for being so short with my words. I'm kinda tired and short in time for now. If it's needed I can explain this more into detail. But I'm kinda hoping that the problem is in this code.
I am relatively new to Java and seem to not be able to figure out whats wrong, I looked into the matter and even though I followed a tutorial for it I still cant seem to make it work, it sees the file since it gives a different error when I try to open file that actually doesn't exist, but it can't get the variables from the database
My code:
String userEnteredString = UserEntered.getText();
String userHomeLocal = Tutschedule.userHome;
FileReader dataFile = null;
try {
dataFile = new FileReader(userHomeLocal+"/Users/"+userEnteredString+".data");
} catch (FileNotFoundException ex) {
Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
}
String dbData = dataFile.toString();
System.out.println(dbData);
JSONObject dataInfo = (JSONObject)dbData.parse(dataFile);
And here are my imports:
import java.io.*;
import java.util.Iterator;
//import java.io.FileNotFoundException;
import org.json.*;
//import java.io.FileReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.simple.parser.*;
and here is the part that writes to the DB, I am sure that the problem doesnt lie here because it writes fine, since I checked the db it created and its in there (the line that sends user to login form is not there when I want to create a user for now):
public class Tutschedule {
// TODO Add the MySQL Database Support
public static String userHome;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws JSONException {
boolean loggedIn = false;
if (loggedIn != true) {
LoginForm.LoginForm();
}
userHome = System.getProperty("user.home")+"/TutSchedule";
System.out.print(userHome);
Scanner scan = new Scanner(System.in);
String username = scan.next();
String password = scan.next();
JSONObject user = new JSONObject();
user.put("username", username);
user.put("password", password);
boolean dirCreate;
String directories =userHome+"/Users";
dirCreate = (new File(directories)).mkdirs();
try {
FileWriter userDataFile = new FileWriter(userHome+"/Users/"+username+".data");
userDataFile.write(user.toString());
userDataFile.flush();
userDataFile.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(user);
}
}
I suspect you may need to change this
JSONObject dataInfo = (JSONObject)dbData.parse(dataFile);
to
JSONObject dataInfo = (JSONObject)JSONValue.parse(dataFile);
as dbData is a String and has no parse() method.
I am a beginner with Java and currently i am developing a SWING JAVA app.
What does this app. do.
If an user tipes some numbers (let' say) [input], then the app. connects to the specific website and searches in there (url : http://www.example.com/search?text=[user's input]). The output (i want so) will be if user's input could be found or not (with help of boolean true/false and url connection). Just this.
I already read A java program to search in a certain website, but i dont want to use crawler. Seems to hard for me.
Also, i think, i dont need to parse a website, because if the user's input exists it will return what the user is looking for. So programs like jsoup are not needed.
My Question is this: What meathod should i use. How to solve this problem?
Basically, how to put user's input into the website URL and then click with swing button for search on that website
EDIT:
so a few points.
The user input should return possitive result , such as this e.g. "example.com/descriptionOfProduct.k973311" where 97311 is a specific ID of that product. It has alsways 6 numbers. And the letter "k." is there always too.
If the user input doesnt exists then 404. If it does then see above. AND the descriptionOfProduct is always a completely different. And it' absolutely random.
I use httpclient apache.
About that specific website : no api for search and it's e-commerce (eshop).
Here is my code, which is not finished because of this search functionality.
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Scanner;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
public class Connection {
/**
* #param args
* #throws URISyntaxException
*/
#SuppressWarnings({ "resource", "unused" })
public static void main(String[] args) throws URISyntaxException {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.example.cz");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
connection.getInputStream();
System.out.println("Connected to website");
// do something with the input stream here
// InputStream error = ((HttpURLConnection) connection).getErrorStream();
// # means special ID to understand where & what is wrong
} catch (MalformedURLException e1) {
e1.printStackTrace();
System.err.println("Something's wrong #1");
} catch (IOException e1) {
e1.printStackTrace();
System.err.println("Something's wrong #2");
} finally {
if(null != connection) { connection.disconnect(); }
}
URIBuilder builder = new URIBuilder();
builder.setScheme("http").setHost("www.example.com").setPath("/search")
.setParameter("text", "");
URI uri = builder.build();
HttpGet httpget = new HttpGet(uri);
and Here is the swing app
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
/**
* #author John Malc
* #version
*
*/
public class app {
private JFrame frame;
private JTextField textField;
private JButton btnSearch;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
app window = new app();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public app() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(getTextField(), BorderLayout.NORTH);
frame.getContentPane().add(getBtnSearch(), BorderLayout.SOUTH);
}
private JTextField getTextField() {
if (textField == null) {
textField = new JTextField();
textField.setColumns(10);
}
return textField;
}
private JButton getBtnSearch() {
if (btnSearch == null) {
btnSearch = new JButton("search");
}
return btnSearch;
}
}
Once you have the remote file you could always do something like this Java Grep Library
Basically, you need to get the remote file and search through the file for a string that matches your user input.