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"); 
result.setStatus("SUCCESS");
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.setContentType("application/pdf");
    response.setHeader("Expires", "0");
    response.setHeader("Cache-Control", "must-revalidate, postcheck=0, pre-check=0");
    response.setHeader("Pragma", "public");
    response.setContentLength(documentBytes.length); 
    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        out.write(documentBytes);
        out.flush();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }       
}

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

I run macOS Sierra, and have installed the Fish shell (https://fishshell.com/).

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:

/Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/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 com.google.common.io.Closeables;

import org.apache.spark.SparkConf;
import org.apache.spark.storage.StorageLevel;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.receiver.Receiver;
import scala.Tuple2;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.Socket;
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);
    wordCounts.count();
    System.out.println("WordCounts == " + wordCounts);
    wordCounts.print();

    ssc.start();
    ssc.awaitTermination();
  }

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

  String host = null;
  int port = -1;

  public JavaCustomReceiver(String host_ , int port_) {
    super(StorageLevel.MEMORY_AND_DISK_2());
    host = host_;
    port = port_;
  }

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

  @Override
  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 + "'");
          store(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

<dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-core_2.11</artifactId>
            <version>2.0.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.microsoft.azure</groupId>
            <artifactId>azure-storage</artifactId>
            <version>5.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.spark</groupId>
            <artifactId>spark-streaming_2.11</artifactId>
            <version>2.0.2</version>
            <scope>provided</scope>
        </dependency>

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;

    try 
    {
        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) 
    {
        e.printStackTrace();
    } 
    finally 
    {
        if (dataIn != null) 
        {
            try 
            {
                dataIn.close();
            } 
            catch (IOException e) 
            {
                e.printStackTrace();
            }
        }
    }
}

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;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar =  findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    txtName = findViewById(R.id.Name);
    txtSurname = findViewById(R.id.Surname);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        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);

            db.collection("users")
                    .add(user)
                    .addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
                        @Override
                        public void onSuccess(DocumentReference documentReference) {
                            //Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        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 com.google.firebase.firestore.FirebaseFirestore.zze(Unknown Source)
                                                            at com.google.firebase.firestore.FirebaseFirestore.getInstance(Unknown Source)
                                                            at damn.testapp.MainActivity$1.onClick(MainActivity.java:44)
                                                            at android.view.View.performClick(View.java:5637)
                                                            at android.view.View$PerformClick.run(View.java:22429)
                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                            at android.os.Looper.loop(Looper.java:154)
                                                            at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

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;
    i.setNum(a);
    System.out.println(i.getNum());
  }

}

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 */

    @FXML
    private CheckBox happyboxtick;


    @FXML
    private VBox topbox;

    @FXML
    private VBox designbox;

     @FXML
    public void initialize(){

    happyboxtick.setSelected(true);

        designbox.setVisible(false);
        designbox.getChildren().removeAll();

        topbox.setVisible(true);
        topbox.getChildren().addAll();

    }


@FXML
    public void doSomething(ActionEvent e) {
        //final CheckBox chk1 = new CheckBox("chk 1");
        //final CheckBox chk2 = new CheckBox("chk 2");
        EventHandler eh = new EventHandler<ActionEvent>() {
            @Override
            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(chk);
                    if(chk.isSelected()){
                        System.out.println("My box is selected.");
                        topbox.setVisible(false);
                        topbox.getChildren().removeAll();

                        designbox.setVisible(true);
                        designbox.getChildren().addAll();
                    } else
                    {
                        System.out.println("My box is not selected.");
                        topbox.setVisible(true);
                        topbox.getChildren().addAll();

                        designbox.setVisible(false);
                        designbox.getChildren().removeAll();
                    }/*
                    if ("Yes".equals(chk.getText())) {
                        chk2.setSelected(!chk1.isSelected());
                    } else if ("chk 2".equals(chk.getText())) {
                        chk1.setSelected(!chk2.isSelected());
                    }*/
                }
            }
        };

        happyboxtick.setOnAction(eh);

        //chk1.setOnAction(eh);
        //chk2.setOnAction(eh);
    }
    }

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.