How to parse JSON in Java

I have the following JSON text. How can I parse it to get pageName, pagePic, post_id, etc.?

{
   "pageInfo": {
         "pageName": "abc",
         "pagePic": "http://example.com/content.jpg"
    }
    "posts": [
         {
              "post_id": "123456789012_123456789012",
              "actor_id": "1234567890",
              "picOfPersonWhoPosted": "http://example.com/photo.jpg",
              "nameOfPersonWhoPosted": "Jane Doe",
              "message": "Sounds cool. Can't wait to see it!",
              "likesCount": "2",
              "comments": [],
              "timeOfPost": "1234567890"
         }
    ]
}

How can i edit pdf and put it inside zip during stream then download using IText and java?

My use case is this: when the client clicks download on a pdf, I want to edit/write some text on to the pdf using Itext pdf editor, then zip the pdf then let it download, All during the stream. I am aware of memory issue if the pdf is large etc. which won’t be an issue since its like 20-50kb. I have the zipping during the stream before downloading working using byte array, now have to make the pdfeditor method also run before zipping, add some text then let the download happen.

Here is my code so far:

    public class zipfolder {

        public static void main(String[] args) {
            try {
                System.out.println("opening connection");
                URL url = new URL("http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/form.pdf");
                InputStream in = url.openStream();
                // FileOutputStream fos = new FileOutputStream(new
                // File("enwiki.png"));
                PdfEditor writepdf = new PdfEditor();

                writepdf.manipulatePdf(url, dest, "field"); /// where i belive i
                                                            /// should execute the
                                                            /// editor function ?

                File f = new File("test.zip");

                ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
                ZipEntry entry = new ZipEntry("newform.pdf");
                zos.putNextEntry(entry);

                System.out.println("reading from resource and writing to file...");
                int length = -1;
                byte[] buffer = new byte[1024];// buffer for portion of data from
                                                // connection
                while ((length = in.read(buffer)) > -1) {
                    zos.write(buffer, 0, length);
                }
                zos.close();
                in.close();
                System.out.println("File downloaded");
            } catch (Exception e) {
                System.out.println("Error");
                e.printStackTrace();
            }

         }
         }

        public class PdfEditor {
            public String insertFields (String field, String value) {
                return field + " " + value;
                // System.out.println("does this work :" + field);
            }

            // public static final String SRC = "src/resources/source.pdf";
            // public static final String DEST = "src/resources/Destination.pdf";
            //
            // public static void main(String[] args) throws DocumentException,
            // IOException {
            // File file = new File(DEST);
            // file.getParentFile().mkdirs();
            // }

            public String manipulatePdf(URL src, String dest, String field) throws Exception {
                System.out.println("test");
                try {
                    PdfReader reader = new PdfReader(src);
                    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
                    AcroFields form = stamper.getAcroFields();
                    Item item = form.getFieldItem("Name");
                    PdfDictionary widget = item.getWidget(0);
                    PdfArray rect = widget.getAsArray(PdfName.RECT);
                    rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
                    String value = field;
                    form.setField("Name", value);
                    form.setField("Company", value);
                    stamper.close();
                } catch (Exception e) {
                    System.out.println("Error in manipulate");
                    System.out.println(e.getMessage());
                    throw e;
                }
                return field;
            }
        }

TableView autorefresh

I am working on an JavaFx project and am facing a problem.

So there is my Controller class :

package ArticleGUI;

import Entities.Article;
import Gestion.GestionArticle;
import com.sun.prism.impl.Disposer.Record;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.util.Callback;

public class ListeArticleFXMLController extends TableCell<Record, Boolean> implements Initializable{

    @FXML
    private TableView<Article> tabArt;
    @FXML
    private TableColumn<Article, Integer> refCol;
    @FXML
    private TableColumn<Article, Hyperlink> titreCol;
    @FXML
    private TableColumn<Article, String> descCol;
    @FXML
    private TableColumn<Article, String> contCol;
    @FXML
    private TableColumn<Article, String> medCol;
    @FXML
    private TableColumn supCol;
    @FXML
    private TableColumn modifCol;
    @FXML
    private TableColumn affichCol;
    @FXML
    private Button reload;


    GestionArticle ga = new GestionArticle();
    ArrayList<Article> listA = (ArrayList<Article>) ga.afficherArticle();
    public ObservableList<Article> articleData = FXCollections.observableArrayList(listA);



    @Override
    public void initialize(URL url, ResourceBundle rb) {

        tabArt.setItems(articleData);

        refCol.setCellValueFactory( new PropertyValueFactory<Article,Integer>("Reference"));

        titreCol.setCellValueFactory(
                   new PropertyValueFactory<Article,Hyperlink>("Nom"));

        descCol.setCellValueFactory(
                   new PropertyValueFactory<Article,String>("Description"));

        contCol.setCellValueFactory(
                   new PropertyValueFactory<Article,String>("Contenu"));

        medCol.setCellValueFactory(
                   new PropertyValueFactory<Article,String>("IdMed"));


        supCol.setCellValueFactory(
                new Callback<TableColumn.CellDataFeatures<Record, Boolean>, ObservableValue<Boolean>>() {

            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Record, Boolean> p) {
                return new SimpleBooleanProperty(p.getValue() != null);
            }
        });

        supCol.setCellFactory(
                new Callback<TableColumn<Record, Boolean>, TableCell<Record, Boolean>>() {

            @Override
            public TableCell<Record, Boolean> call(TableColumn<Record, Boolean> p) {
                return new DelButton();
            }

        });


        modifCol.setCellValueFactory(
                new Callback<TableColumn.CellDataFeatures<Record, Boolean>, ObservableValue<Boolean>>() {

            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Record, Boolean> p) {
                return new SimpleBooleanProperty(p.getValue() != null);
            }
        });

        modifCol.setCellFactory(
                new Callback<TableColumn<Record, Boolean>, TableCell<Record, Boolean>>() {

            @Override
            public TableCell<Record, Boolean> call(TableColumn<Record, Boolean> p) {
                return new ModifButton();
            }

        });

        affichCol.setCellValueFactory(
                new Callback<TableColumn.CellDataFeatures<Record, Boolean>, ObservableValue<Boolean>>() {

            @Override
            public ObservableValue<Boolean> call(TableColumn.CellDataFeatures<Record, Boolean> p) {
                return new SimpleBooleanProperty(p.getValue() != null);
            }
        });

        affichCol.setCellFactory(
                new Callback<TableColumn<Record, Boolean>, TableCell<Record, Boolean>>() {

            @Override
            public TableCell<Record, Boolean> call(TableColumn<Record, Boolean> p) {
                return new AffichButton();
            }

        });

    }

    public void refresh(){
        articleData.clear();
        List<Article> la=new ArrayList<>();
        la=ga.afficherArticle();
        articleData.setAll(la);
        tabArt.setItems(articleData);
    }

    public void setTabArt(TableView<Article> tabArt) {
        this.tabArt = tabArt;
    }

    public TableColumn<Article, Integer> getRefCol() {
        return refCol;
    }

    public void setRefCol(TableColumn<Article, Integer> refCol) {
        this.refCol = refCol;
    }

    public TableColumn<Article, Hyperlink> getTitreCol() {
        return titreCol;
    }

    public void setTitreCol(TableColumn<Article, Hyperlink> titreCol) {
        this.titreCol = titreCol;
    }

    public TableColumn<Article, String> getDescCol() {
        return descCol;
    }

    public void setDescCol(TableColumn<Article, String> descCol) {
        this.descCol = descCol;
    }

    public TableColumn<Article, String> getContCol() {
        return contCol;
    }

    public void setContCol(TableColumn<Article, String> contCol) {
        this.contCol = contCol;
    }

    public TableColumn<Article, String> getMedCol() {
        return medCol;
    }

    public void setMedCol(TableColumn<Article, String> medCol) {
        this.medCol = medCol;
    }

    public ObservableList<Article> getArticleData() {
        return articleData;
    }



}

And there is my Button class :

package ArticleGUI;

import Entities.Article;
import Gestion.GestionArticle;
import com.sun.prism.impl.Disposer.Record;
import java.util.Optional;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.TableCell;

public class DelButton extends TableCell<Record, Boolean> {

    ListeArticleFXMLController l = new ListeArticleFXMLController();
    final Button supp = new Button("Supprimer");

    public DelButton() {
        supp.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent t) {
                GestionArticle ga = new GestionArticle();
                try {
                    Article currentArt = (Article) DelButton.this.getTableView().getItems().get(DelButton.this.getIndex());
                    Alert a1 = new Alert(Alert.AlertType.CONFIRMATION);
                    a1.setTitle("Suppresion Article");
                    a1.setHeaderText(null);
                    a1.setContentText("Etes vous vraiment sur de vouloir supprimer " + currentArt.getNom() + " ?\n");
                    Optional<ButtonType> button = a1.showAndWait();
                    if (button.get() == ButtonType.OK) {
                        l.getArticleData().remove(currentArt);
                        ga.supprimerArticle(currentArt);
                        l.refresh();
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }            
        });
    }

    @Override
    protected void updateItem(Boolean t, boolean empty) {
        super.updateItem(t, empty);
        if (!empty) {
            setGraphic(supp);
        }
    }


}

and this is how it appears (supprimer=delete) :

So i want my TableView to refresh automatically when I delete an article. Is there anyone who could help me?

Thanks everyone.

How to add an ImageIcon to an object?

I have the object ‘Team’ with some score variables, the name (String) and a logo. The logo has the type ImageIcon:

public class Team {

    public String name;
    public ImageIcon logo;
    public int points;
    public int plusGoals;
    public int minGoals;
    public int goalsTotal;


public Team (String name, ImageIcon logo, int points, int plusGoals, int minGoals, int goalsTotal){      

    this.name = name;
    this.logo = logo;
    this.points = points;
    this.plusGoals = plusGoals;
    this.minGoals = minGoals;
    goalsTotal = plusGoals - minGoals;

When I want to create a new object, and I enter the values of the object properties, I don’t know how I can add the ImageIcon path.

So:

Team Blabla = new Team("Blabla", ..., 0, 0, 0, 0);

I tried this things, but they doens’t work:

Team Blabla = new Team("Blabla", C:\\Users\\path.png, 0, 0, 0, 0);
Team Blabla = new Team("Blabla", "C:\\Users\\path.png", 0, 0, 0, 0);
Team Blabla = new Team("Blabla", ImageIcon("C:\\Users\\path.png"), 0, 0, 0, 0);

How can I directly add an image path in this line?

Selenium Webdriver. Getting same text from different pages

I’m using ChromeDriver to access TripAdvisor.com and searching for “fishing” activities. I can extract all the information about the providers on the first page using:

    String myText = driver.findElement(By.xpath("//*[@id=\"search_result\"]/div/div[1]/div[1]/div[2]")).getText();
    System.out.println(myText + "\n");

The result:

Osprey Cruises
797 reviews
1 Padre Blvd, South Padre Island, Texas
fishing matches 328 reviews
Fishing was very good I caught about a dozen sand trout. They allowMay 20, 2017

But when I go to the next page:

    driver.findElement(By.xpath("//*[@id=\"search_result\"]/div/div[3]/div/a[2]")).click();

and trying to extract the result from the second page using

    String myText2 = driver.findElement(By.xpath("//*[@id=\"search_result\"]/div/div[1]/div[1]/div[2]")).getText();
    System.out.println(myText2 + "\n");

I’m getting the XPath by using Chrome and inspecting the element on page 2.
It is giving me the same result from the page one:

Osprey Cruises
797 reviews
1 Padre Blvd, South Padre Island, Texas
fishing matches 328 reviews
Fishing was very good I caught about a dozen sand trout. They allowMay 20, 2017

How can I get the result from page 2? I’m new to Selenium and any help would be appreciated, Thanks.

what happen when override spring repository method without implementing

Here is my spring repository interface

    interface TupleRepository extends JpaRepository<Tuple, Integer> {

    @Override
    @CacheEvict(cacheNames="tuples", allEntries=true)
    void delete(Tuple tuple);

}

As you see I overrided withoud giving any implementation.
the method is still working.

Which implem is being called.

I tried the debugging and investigation but ended up in the aop class managing the call.

does this method still call the jpaRepository implementation or what ?

Unable to read

text under

using selenium

I have an html code something like:

<h3> Some Heading </h3>
<p> Some String </p>
<p> more string </p>
<h3> Other heading</h3>
<p> some text </p>

I am trying to access Some String, more string and some text. With java, am trying to access like this:

List<WebElement> h3Tags = driver.findElements(By.tagName("h3"));

List<WebElement> para = null;

WebElement bagInfo = h3Tags.get(0);  //reads first h3
if(bagInfo.getText().contains("carry-on") || bagInfo.getText().contains("Carry-on")){
        para = AutoUtils.findElementsByTagName(bagInfo, "p");
        System.out.println(para.get(0).getText());  //Null pointer here 
}

bagInfo = h3Tags.get(1);
if(bagInfo.getText().contains("checked") || bagInfo.getText().contains("Checked")){
        para = AutoUtils.findElementsByTagName(bagInfo, "p");
        System.out.println(para.get(0).getText());  //Null pointer here too
}

Tried xpath like "h3['/p']" but still no luck. What is the best way to access those <p> strings?