Okey so my problem is next: I use web scraping to take some data from web page IMDB in this case, that data is titles of movies, and I already tried to print it in console and that works fine. My problem is that I can not save that titles in my table columns, I put all needed codes for this problem, and I cant find where I made mistake and why titles wont show in table columns. At the and, user need to pick one title and that title need to be stored in text field. Have someone any idea, please?
I have table:
TableColumn izborAuta = new TableColumn("Izbor auta");
TableColumn lokacijaPreuzimanja = new TableColumn("Lokacija
preuzimanja");
TableColumn lokacijaVracanja = new TableColumn("Lokacija Vracanja");
TableColumn cena = new TableColumn("Cena");
I have this code to setup columns:
izborAuta.setCellValueFactory(new PropertyValueFactory<Vozila, String>
("izborAuta"));
lokacijaPreuzimanja.setCellValueFactory(new
PropertyValueFactory<Vozila, String>("lokacijaPreuzimanja"));
lokacijaVracanja.setCellValueFactory(new
PropertyValueFactory<Vozila, String>("lokacijaVracanja"));
cena.setCellValueFactory(new PropertyValueFactory<Vozila, String>
("cena"));
tableView.setItems(Baza.baza.prikazBaze());
tableView.getColumns().addAll(izborAuta, lokacijaPreuzimanja,
lokacijaVracanja, cena);
I have this code, so when I pick one item from table that item need to be stored in textField:
tableView.setOnMouseClicked((e) -> {
Vozila v = (Vozila)
tableView.getSelectionModel().getSelectedItem();
txIzborAuta.setText(v.getIzborAuta());
txLokacijaPreuzimanja.setText(v.getLokacijaPreuzimanja());
txLokacijaVracanja.setText(v.getLokacijaVracanja());
txCena.setText(v.getCena());
});
And at the end I use web scraping to save items in table:
Document doc = Jsoup.connect("https://www.imdb.com/chart/top?
ref_=nv_mv_250").get();
Elements elems = doc.select("table.chart.full-width");
for (Element e : elems) {
String izborAuta = e.select(".titleColumn").text();
String lokacijaPreuzimanja = e.select(".titleColumn").text();
String lokacijaVracanja = e.select(".titleColumn").text();
String cena = e.select(".titleColumn").text();
Vozila v = new Vozila();
v.setIzborAuta(izborAuta);
v.setLokacijaPreuzimanja(lokacijaPreuzimanja);
v.setLokacijaVracanja(lokacijaVracanja);
v.setCena(cena + " " + "RSD");
Baza.insertVozila(v);
}
Related
I am beginner with springboot. I came across a situation.Ok, let me give table structure before I explain.
Expenses
expensesId, categories,
Categories
categoryId, categoryname
Expenses table is referring to category table with categoryId.
I am able to populate datatable with expensesList that was sent from a controller to view successfully. But my problem is I get columnid in populated but I wish to populate that column with categoryname instead. I thought for possible solutions for some time and I come up with stupid Idea using If the condition in thymeleaf of mapping categoryId with categoryName but I don't wish to go for that part as I can have more categories growing in future and code is difficult to maintain.
I could really use some help on this.
Link to git project
expensespage link
expenses controller link
Please do provide links if a solution is already available which I missed during my google search on this issue.
Apologies for bad english for Title part as I cannot squeeze question further.
I just added category object containing Id and name to every expenses object in
Expenses Object List and passed to controller. Now I can directly use CategoryName in View with Thymeleaf as follows
<td th:text="${expense.categories.categoryname}"></td>>
What I changed in controller.
Before
#RequestMapping(value = "/expenses")
public String toExpensesPage(Model model) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = monitorService.getUserByUserName(authentication.getName()).get(0);
List<Categories> categoriesList = monitorService.getAllCategories();
model.addAttribute("expenses",new Expenses());
if(categoriesList != null) {
model.addAttribute("categories",categoriesList);
}
List<Expenses> expensesList = monitorService.getAllExpensesActive(user.getUserid());
model.addAttribute("expensesList",expensesList);
return "common/expensespage";
}
To.
#RequestMapping(value = "/expenses")
public String toExpensesPage(Model model) {
Map<Integer,String> categoryMap = new HashMap<Integer, String>();
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
User user = monitorService.getUserByUserName(authentication.getName()).get(0);
/* getting Category List This contains both categoryId and categoryname */
List<Categories> categoriesList = monitorService.getAllCategories();
/* Using hashmap to map id to name so we dont need to iterate categoryList or call to database with category Id..*/
for(int i = 0; i < categoriesList.size();i++){
categoryMap.put(categoriesList.get(i).getCategoryid(),
categoriesList.get(i).getCategoryname());
}
model.addAttribute("expenses",new Expenses());
if(categoriesList != null) {
model.addAttribute("categories",categoriesList);
}
List<Expenses> expensesList = monitorService.getAllExpensesActive(user.getUserid());
/*Assigning category object to expenses object*/
for(int i = 0; i < expensesList.size();i++){
Categories categories = new Categories();
categories.setCategoryid(expensesList.get(i).getCategories().getCategoryid());
categories.setCategoryname(categoryMap.get(expensesList.get(i).getCategories().getCategoryid()));
expensesList.get(i).setCategories(categories);
}
model.addAttribute("expensesList",expensesList);
return "common/expensespage";
}
Added Comment's inside code on how I did. Hope someone find it helpful.
I need to make a programm in JavaFX where I need to manage a movie library. I have a tableview that is filled by an observable list. Then I made bindings between the Properties and the Textboxes or Labels next to the tableview. Now the problem is, I have also pictures that are related to the movies, like cinema posters. and at the moment I just use a hardcoded one:
imgPoster = new Image(getClass().getResourceAsStream("../resources/images/posters/" + 5 + ".jpg"));
In the datafile there is one column with the ID of the movie and the same number is also the picture for it. So I need to replace that "5" in the sample code with a binding or so that it actively changes the picture as soon as I click on a row in the tableview.
How do I do that?
edit:
After the first comment i did that:
imgOscars = new Image(getClass().getResourceAsStream("../resources/images/oscar/Oscar-logo.png"));
oscars = new ImageView(imgOscars);
oscars.setPreserveRatio(true);
oscars.setFitHeight(45);
but question stays
Either add a listener to the selected item property in the table (I am just guessing at the model you are using for the table):
TableView<Movie> table = ... ;
table.getSelectionModel().selectedItemProperty().addListener((obs, oldSelectedMovie, newSelectedMovie) -> {
if (newSelectedMovie == null) {
oscars.setImage(null);
} else {
// get image from new selection
Image image = new Image(getClass().getResourceAsStream("../resources/images/oscar/"+newSelectedMoviegetId()+".png"));
oscars.setImage(image);
}
});
or use a binding:
oscars.imageProperty().bind(Bindings.createObjectBinding(() -> {
if (table.getSelectionModel().getSelectedItem() == null) {
return null ;
} else {
Movie selected = table.getSelectionModel().getSelectedItem();
return new Image(getClass().getResourceAsStream("../resources/images/oscar/"+selected.getId()+".png")); ;
},
table.getSelectionModel().selectedItemProperty());
I need to create a table at the location of particular bookmark. ie i need to find the bookmark and insert the table . how can i do this using docx4j
Thanks in Advance
Sorry Jason, I am new to Stackoverflow so i couldnt write my problem clearly, here is my situation and problem.
I made changes in that code as you suggested and to my needs, and the code is here
//loop through the bookmarks
for (CTBookmark bm : rt.getStarts()) {
// do we have data for this one?
String bmname =bm.getName();
// find the right bookmark (in this case i have only one bookmark so check if it is not null)
if (bmname!=null) {
String value = "some text for testing run";
//if (value==null) continue;
List<Object> theList = null;
//create bm list
theList = ((ContentAccessor)(bm.getParent())).getContent();
// I set the range as 1 (I assume this start range is to say where the start the table creating)
int rangeStart = 1;
WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
// create the table
Tbl table = factory.createTbl();
//add boards to the table
addBorders(table);
for(int rows = 0; rows<1;rows++)
{// create a row
Tr row = factory.createTr();
for(int colm = 0; colm<1;colm++)
{
// create a cell
Tc cell = factory.createTc();
// add the content to cell
cell.getContent().add(wordPackage.getMainDocumentPart()
.createParagraphOfText("cell"+colm));
// add the cell to row
row.getContent().add(cell);
}
// add the row to table
table.getContent().add(row);
// now add a run (to test whether run is working or not)
org.docx4j.wml.R run = factory.createR();
org.docx4j.wml.Text t = factory.createText();
run.getContent().add(t);
t.setValue(value);
//add table to list
theList.add(rangeStart, table);
//add run to list
//theList.add(rangeStart, run);
}
I dont need to delete text in bookmark so i removed it.
I dont know whats the problem, program is compiling but I cannot open the word doc , it says "unknown error". I test to write some string "value" it writes perfectly in that bookmark and document is opening but not in the case of table. Please help me
Thanks in advance
You can adapt the sample code BookmarksReplaceWithText.java
In your case:
line 89: the parent won't be p, it'll be body or tc. You could remove the test.
line 128: instead of adding a run, you want to insert a table
You can use TblFactory to create your table, or the docx4j webapp to generate code from a sample docx.
For some reason bookmark replacement with table didn't workout for me, so I relied on text replacement with table. I created my tables from HTML using XHTML importer for my use case
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
String xhtml= <your table HTML>;
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
int ct = 0;
List<Integer> tableIndexes = new ArrayList<>();
List<Object> documentContents = documentPart.getContent();
for (Object o: documentContents) {
if (o.toString().contains("PlaceholderForTable1")) {
tableIndexes.add(ct);
}
ct++;
}
for (Integer i: tableIndexes) {
documentPart.getContent().remove(i.intValue());
documentPart.getContent().addAll(i.intValue(), XHTMLImporter.convert( xhtml, null));
}
In my input word doc, I defined text 'PlaceholderForTable1' where I want to insert my table.
I can't seem to update an existing record in my table using a strongly-typed dataset. I can add a new record, but if I make changes to an existing record it doesn't work.
Here is my code:
private void AddEmplMaster()
{
dsEmplMast dsEmpMst = new dsEmplMast();
SqlConnection cn = new SqlConnection();
cn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["cn.ConnectionString"];
SqlDataAdapter da1 = new SqlDataAdapter("SELECT * FROM UPR00100", cn);
SqlCommandBuilder cb1 = new SqlCommandBuilder(da1);
da1.Fill(dsEmpMst.UPR00100);
DataTable dtMst = UpdateEmpMst(dsEmpMst);
da1.Update(dsEmpMst.UPR00100);
}
This procedure is called from above to assign the changed fields to a record:
private DataTable UpdateEmpMst(dsEmplMast dsEmpMst)
{
DataTable dtMst = new DataTable();
try
{
dsEmplMast.UPR00100Row empRow = dsEmpMst.UPR00100.NewUPR00100Row();
empRow.EMPLOYID = txtEmplId.Text.Trim();
empRow.LASTNAME = txtLastName.Text.Trim();
empRow.FRSTNAME = txtFirstName.Text.Trim();
empRow.MIDLNAME = txtMidName.Text.Trim();
empRow.ADRSCODE = "PRIMARY";
empRow.SOCSCNUM = txtSSN.Text.Trim();
empRow.DEPRTMNT = ddlDept.SelectedValue.Trim();
empRow.JOBTITLE = txtJobTitle.Text.Trim();
empRow.STRTDATE = DateTime.Today;
empRow.EMPLOYMENTTYPE = "1";
dsEmpMst.UPR00100.Rows.Add(empRow);
}
catch { }
return dtMst;
}
Thank you
UPDATE:
Ok I figured it out. In my UpdateEmpMst() procedure I had to check if the record exists then to retrieve it first. If not then create a new record to add. Here is what I added:
try
{
dsEmplMast.UPR00100Row empRow;
empRow = dsEmpMst.UPR00100.FindByEMPLOYID(txtEmplId.Text.Trim());
if (empRow == null)
{
empRow = dsEmpMst.UPR00100.NewUPR00100Row();
dsEmpMst.UPR00100.Rows.Add(empRow);
}
then I assign my data to the new empRow I created and updates fine.
In order to edit an existing record in a dataset, you need to access a particular column of data in a particular row. The data in both typed and untyped datasets can be accessed via the following:
With the indices of the tables, rows, and columns collections.
By passing the table and column names as strings to their respective collections.
Although typed datasets can use the same syntax as untyped datasets, there are additional advantages to using typed datasets. For more information, see the "To update existing records using typed datasets" section below.
To update existing records in either typed or untyped datasets
Assign a value to a specific column within a DataRow object.
The table and column names of untyped datasets are not available at design time and must be accessed through their respective indices.
I am developing an application which sets up an http connection with a website and by using GET call. I am getting Data Set IDs and I want to show these DATA SET ID's in a drop down menu, so that the user can select it.
I also want to store the selected data set id in a variable as it will be used in future in my application.
This is how I am getting the values in DSid (string array to store data set id returned in JSON format )
URL urlDS = new URL("http:/link.json?key="+APIkey);
HttpURLConnection httpConDS = (HttpURLConnection) urlDS.openConnection();
StringBuilder sbDS = new StringBuilder();
while ((inputLineDS = inDS.readLine()) != null) {
sbDS.append(inputLineDS);
System.out.println(inputLineDS);
}
String ResultDS;
ResultDS=sbDS.toString();
System.out.println("result:"+ResultDS);
String jsonSourceDS = ResultDS;
JSONArray arrayDS;
try {
arrayDS = new JSONArray(jsonSourceDS);
for (int i = 0; i < arrayDS.length(); i++) {
JSONObject firstObject = (JSONObject) arrayDS.get(i);
System.out.println("Data set ID " + firstObject.getString("datasetId"));
DSid[i]=firstObject.getString("datasetId");
++countDSid;
}
}
I used JComboBox but it is not helping me.
combo.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String selected = (String) cb.getSelectedItem();
labelp3.setText("You selected: " + selected);
}
} );
and this in the constructor of my Log-in class
JComboBox combo = new JComboBox(DSid);
This DSid is an string array which is storing the data set id, using GET call.
I am not able to create the drop down menu with the data set ids, it is being empty if I am using these.
So how can I create dynamic drop down menu and also store the selected value in a variable?
The values shown in data set (2,3) are given by me statically in the DSid array in the class login.