Send multiple types of objects using Java

First of all, I’m not sure whether this could be possible or not. I’m flushing bytes of data as PDF to the browser. Now the requirement is, I want to generate the pdf and also send one more extra object. Is it possible?

I’ve written something like this, but the result object is not getting as response.

YBUtil.GeneratePdf(response,documentBytes, "Bureau"); 
return result; --> I want to pass this object as well

GeneratePdf method

    public static void GeneratePdf(HttpServletResponse response, byte[] documentBytes, String fileName){

    response.setHeader("Content-Disposition", "inline;filename="+fileName+".pdf");
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, postcheck=0, pre-check=0");
    response.setHeader("Pragma", "public");
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
    } catch (IOException e) {

Why does Maven use the wrong JDK version when running from Fish?

I run macOS Sierra, and have installed the Fish shell (

When I try to build a Maven project, it now gives me

Fatal error compiling: invalid target release: 1.8 ->

… which means that it has picked up an older JDK which it tries to use to build my Java 8 project with.

This is made obvious by running mvn -version:

Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

But I have JAVA_HOME set correctly, echo $JAVA_HOME:


and java -version gives me

java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b16)

and javac -version:

javac 1.8.0_112

Why does Maven insist on using the 1.6 JDK? This does not happen when running through Bash, only with Fish.

spark custom receiver unable to process data

I have written a custom receiver to process a stream of data, the code compiles and runs well but when I send the data from a server it gets displayed in the console but I don’t see the inputs being processed.

Custom server:-

nc -lk 9999

Java code:-


import org.apache.spark.SparkConf;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.receiver.Receiver;
import scala.Tuple2;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.regex.Pattern;

 * Custom Receiver that receives data over a socket. Received bytes is interpreted as
 * text and n delimited lines are considered as records. They are then counted and printed.
 * Usage: JavaCustomReceiver <master> <hostname> <port>
 *   <master> is the Spark master URL. In local mode, <master> should be 'local[n]' with n > 1.
 *   <hostname> and <port> of the TCP server that Spark Streaming would connect to receive data.
 * To run this on your local machine, you need to first run a Netcat server
 *    `$ nc -lk 9999`
 * and then run the example
 *    `$ bin/run-example org.apache.spark.examples.streaming.JavaCustomReceiver localhost 9999`

public class JavaCustomReceiver extends Receiver<String> {
  private static final Pattern SPACE = Pattern.compile(" ");

  public static void main(String[] args) throws Exception {
//    if (args.length < 2) {
//      System.err.println("Usage: JavaCustomReceiver <hostname> <port>");
//      System.exit(1);
//    }

//    StreamingExamples.setStreamingLogLevels();

    // Create the context with a 1 second batch size
    SparkConf sparkConf = new SparkConf().setAppName("JavaCustomReceiver").setMaster("local[*]");
    JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, new Duration(10000));

    // Create an input stream with the custom receiver on target ip:port and count the
    // words in input stream of n delimited text (eg. generated by 'nc')
    JavaReceiverInputDStream<String> lines = ssc.receiverStream(
      new JavaCustomReceiver("localhost", 9999));    

//    JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(SPACE.split(""))).iterator();
    JavaDStream<String> words = lines.flatMap(x -> Arrays.asList(SPACE.split(" ")).iterator());
    words.foreachRDD(   x-> {
        x.collect().stream().forEach(n-> System.out.println("item of list: "+n));

    JavaPairDStream<String, Integer> wordCounts = words.mapToPair(s -> new Tuple2<>(s, 1))
        .reduceByKey((i1, i2) -> i1 + i2);
    System.out.println("WordCounts == " + wordCounts);


  // ============= Receiver code that receives data over a socket ==============

  String host = null;
  int port = -1;

  public JavaCustomReceiver(String host_ , int port_) {
    host = host_;
    port = port_;

  public void onStart() {
    // Start the thread that receives data over a connection
    new Thread(this::receive).start();

  public void onStop() {
    // There is nothing much to do as the thread calling receive()
    // is designed to stop by itself isStopped() returns false

  /** Create a socket connection and receive data until receiver is stopped */
  private void receive() {
    try {
      Socket socket = null;
      BufferedReader reader = null;
      try {
        // connect to the server
        socket = new Socket(host, port);
        reader = new BufferedReader(
            new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
        // Until stopped or connection broken continue reading
        String userInput;
        while (!isStopped() && (userInput = reader.readLine()) != null) {
          System.out.println("Received data '" + userInput + "'");
      } finally {
        Closeables.close(reader, /* swallowIOException = */ true);
        Closeables.close(socket,  /* swallowIOException = */ true);
      // Restart in an attempt to connect again when server is active again
      restart("Trying to connect again");
    } catch(ConnectException ce) {
      // restart if could not connect to server
      restart("Could not connect", ce);
    } catch(Throwable t) {
      restart("Error receiving data", t);

Why don’t see I any inputs in the console of the print statement.

Here is my pom.xml



Error on PlainTextByLineStream – openNLP

when i try the following code in apache OpenNLP 1.8 it wont work but when i use the older version (1.5) it does compile and give output. what am i doing wrong ?

public void trainModel() 
    FileInputStream dataIn = null;

        FileInputStream dataIn = new FileInputStream("D:/training.txt");
        ObjectStream lineStream = new PlainTextByLineStream(dataIn, "UTF-8");
        ObjectStream sampleStream = new DocumentSampleStream(lineStream);

        // Specifies the minimum number of times a feature must be seen
        int cutoff = 2;
        int trainingIterations = 30;
        model = DocumentCategorizerME.train("nl",sampleStream,cutoff,trainingIterations);


    catch (IOException e) 
        if (dataIn != null) 
            catch (IOException e) 

Firestore getProductID cannot be null error

I am trying to use the new Firestore released by Firebase in my android app. Unfortunately I keep getting this error when trying to write to the database.

public class MainActivity extends AppCompatActivity {

EditText txtName,txtSurname;

protected void onCreate(Bundle savedInstanceState) {
    Toolbar toolbar =  findViewById(;

    txtName = findViewById(;
    txtSurname = findViewById(;

    FloatingActionButton fab = findViewById(;
    fab.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            FirebaseFirestore db = FirebaseFirestore.getInstance();

            Map<String, Object> user = new HashMap<>();
            user.put("first", "Ada");
            user.put("last", "Lovelace");
            user.put("born", 1815);

                    .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                        public void onSuccess(DocumentReference documentReference) {
                            //Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                    .addOnFailureListener(new OnFailureListener() {
                        public void onFailure(@NonNull Exception e) {
                            //Log.w(TAG, "Error adding document", e);


This is the error I keep getting. I have added the project to my android app via the assistant. So there shouldn’t be an issue.

Process: damn.testapp, PID: 2622
                                                        java.lang.IllegalArgumentException: FirebaseOptions.getProjectId() cannot be null
                                                            at Source)
                                                            at Source)
                                                            at damn.testapp.MainActivity$1.onClick(
                                                            at android.view.View.performClick(
                                                            at android.view.View$
                                                            at android.os.Handler.handleCallback(
                                                            at android.os.Handler.dispatchMessage(
                                                            at android.os.Looper.loop(
                                                            at java.lang.reflect.Method.invoke(Native Method)

Any help would be greatly appreciated.

How is it possible to supply Integer to setter expecting double?

I have this snippet:

class scratch_5{
  public static void main(String theory[]){
    Item i = new Item();
    Integer a = 3;


class Item{
   double num;

   public void setNum(double num){this.num=num;}
   public double getNum(){return num;}

Can you explain to me how is this possible? I understand that double wrapper class is Double, and both Integer and Double are derived from Number, hence they shouldn’t be possible to use interchangeably

Checkbox initialization delay Java FX 8

Can someone tell me why there is a delay on Checkbox initialization with my Code?

What happens is that if I open the program, I have to click the Checkbox several times until it performes the desired Action.

The Controller also contains setter and getter methods.

Thanks a lot

public class Controller {

   /* Defined variables */

    private CheckBox happyboxtick;

    private VBox topbox;

    private VBox designbox;

    public void initialize(){





    public void doSomething(ActionEvent e) {
        //final CheckBox chk1 = new CheckBox("chk 1");
        //final CheckBox chk2 = new CheckBox("chk 2");
        EventHandler eh = new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                if (event.getSource() instanceof CheckBox) {
                    CheckBox chk = (CheckBox) event.getSource();
                    //System.out.println("Action performed on checkbox " + chk.getText());
                        System.out.println("My box is selected.");

                    } else
                        System.out.println("My box is not selected.");

                    if ("Yes".equals(chk.getText())) {
                    } else if ("chk 2".equals(chk.getText())) {



The Code compiles perfectly.
Initialization works.
The right Option is selected.
But when I click the box, I may have to click several times until the Elements are shown. And I don’t know why.

eclipse vs cmd maven repositories

I am working on a project where there is quite a lot of dependencies loaded. I am using a specific settings.xml file which is pointing specific direction for the m2 repository. It set in eclipse preferences for maven to use this settings file and also as a environment variable to use this settings file.

Now, the scenario that I am no sure what happens is:

  1. there was a change in the code that requires an update of the dependencies
  2. you are using the Maven -> Update project… option from project context menu in eclipse, or using the Maven build with the Update snapshots option checked
  3. Dependencies are downloaded and in eclipse you can see that the code is building again.
  4. And here is the part that I do not understand, now I am trying to run simply “mvn clean install” on the specific project but it is not building, I need to use the -U option and when the dependencies are downloaded, then the build is success.

I know that this is long scenario and for someone probably a tl;dr but would be very grateful if someone could explain it to me why there is a need to download the dependencies double.