Iterating document data by passing multiple values in mongo java

The Json data is:

[
    "Team" : {
        "A" : {
            "Default" : 1, 
            "Options": [
                1,
                2
            ]
        },
        "B" : {
            "Default" : 1, 
            "Options": [
                1,
                2
            ]
        },
        "D" : {
            "Default" : 1, 
            "Options": [
                1,
                2
            ]
        },
        "E" : {
            "Default" : 1, 
            "Options": [
                1,
                2
            ]
        },
    }
]  

I am getting the below output using above code:
{ }

i.e. its showing blank output.
The desired output should be:
[
    "A" : {

            "Options": [
                1,
                2
            ]
        },
        "B" : {

            "Options": [
                1,
                2
            ]
        },
        "C" : {

            "Options": [
                1,
                2
            ]
        },
        "D" : {

            "Options": [
                1,
                2
            ]
        },
    }
]

Please specify where I am going wrong to fetch the specific node data on the basis of passing values. I have used ‘Team.Condition.get(i).Options’ for passing values from the list like ‘Team.A.Options’, ‘Team.B.Options’, ‘Team.C.Options’ & ‘Team.D.Options’. Thanks for any help.

Jersey proxy client can’t deserialize JSON response to RAML generated classes

I’ve generated classes with raml-to-jaxrs maven plugin (2.1.1-SNAPSHOT) from this RAML file and call the service with Jersey proxy client like this:

Client client = ClientBuilder.newClient();
Logger logger = Logger.getLogger(getClass().getName());
Feature feature = new LoggingFeature(logger, Level.INFO, null, null);
client.register(feature);        
client.register(new PostiSmartShipAuthenticator(username, password));
WebTarget target = client.target(URI);
Addresses proxy = WebResourceFactory.newResource(Addresses.class, target);
GetAddressesAgentsResponse response = proxy.getAddressesAgents("ITELLASP", null, "51270", null, "FI", null);

The service responds with an array of objects:

INFO: 1 * Sending client request on thread main
1 > GET https://.../addresses/agents?type=ITELLASP&zip=51270&countryCode=FI
1 > Accept: application/json
1 > Authorization: Basic ...

INFO: 1 * Client response received on thread main
1 < 200
1 < Connection: Keep-Alive
1 < Content-Type: application/json;charset=UTF-8
1 < Date: Sun, 15 Oct 2017 10:38:53 GMT
1 < Keep-Alive: timeout=5, max=100
1 < Server: Apache
1 < Transfer-Encoding: chunked
[{"id":"512053201","name":"Pakettiautomaatti, S-market Kangasniemi","address1":"Otto Mannisen tie 10","address2":null,"zipcode":"51205","city":"KANGASNIEMI","state":null,"countryCode":"FI","contact":null,"phone":null,"fax":null,"email":null,"sms":null,"serviceType":null,"serviceCode":null,"openingHours":"ma-la 7.00 - 21.00, su 10.00 - 21.00"},{"id":"761053201","name":"Pakettiautomaatti, K-citymarket Pieksämäki","address1":"Kukkaroniementie 3","address2":null,"zipcode":"76105","city":"PIEKSÄMÄKI","state":null,"countryCode":"FI","contact":null,"phone":null,"fax":null,"email":null,"sms":null,"serviceType":null,"serviceCode":null,"openingHours":"ma-pe 8.00 - 21.00, la 8.00 - 20.00, su 11.00 - 18.00"},{"id":"408053201","name":"Pakettiautomaatti, S-market Vaajala","address1":"Asematie 1","address2":null,"zipcode":"40805","city":"VAAJAKOSKI","state":null,"countryCode":"FI","contact":null,"phone":null,"fax":null,"email":null,"sms":null,"serviceType":null,"serviceCode":null,"openingHours":"ma-la 7.00 - 22.00, su 10.00 - 22.00"},{"id":"409053201","name":"Pakettiautomaatti, S-market Säynätsalo","address1":"Parviaisentie 6","address2":null,"zipcode":"40905","city":"SÄYNÄTSALO","state":null,"countryCode":"FI","contact":null,"phone":null,"fax":null,"email":null,"sms":null,"serviceType":null,"serviceCode":null,"openingHours":"ma-la 7.00 - 21.00, su 10.00 - 21.00"},{"id":"405253201","name":"Pakettiautomaatti, S-market Kuokkala","address1":"Syöttäjänkatu 2","address2":null,"zipcode":"40525","city":"JYVÄSKYLÄ","state":null,"countryCode":"FI","contact":null,"phone":null,"fax":null,"email":null,"sms":null,"serviceType":null,"serviceCode":null,"openingHours":"ma-la 7.00 - 23.00, su 10.00 - 23.00"}]

However, the array of objects can not be deserialized to GetAddressesAgentsResponse:

Caused by: javax.json.bind.JsonbException: Can't deserialize JSON array into: class haba713.postismartship.resources.Addresses$GetAddressesAgentsResponse
at org.eclipse.yasson.internal.serializer.DeserializerBuilder.build(DeserializerBuilder.java:129)
at org.eclipse.yasson.internal.Unmarshaller.deserializeItem(Unmarshaller.java:56)
at org.eclipse.yasson.internal.Unmarshaller.deserialize(Unmarshaller.java:50)
at org.eclipse.yasson.internal.JsonBinding.deserialize(JsonBinding.java:45)
at org.eclipse.yasson.internal.JsonBinding.fromJson(JsonBinding.java:85)
at org.glassfish.jersey.jsonb.internal.JsonBindingProvider.readFrom(JsonBindingProvider.java:99)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.invokeReadFrom(ReaderInterceptorExecutor.java:257)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:236)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:156)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:1091)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:874)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:834)
at org.glassfish.jersey.client.ClientResponse.readEntity(ClientResponse.java:363)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:936)
... 37 more

For some reason the plugin seems to generate always classes with com.fasterxml.jackson annotations even though I have

<generateTypesWith>
    <value>jaxb</value>
</generateTypesWith>

in pom.xml. Probably this is not the actual issue.

The effective dependencies currently are

javax.ws.rs:javax.ws.rs-api:2.1
org.glassfish.jersey.core:jersey-client:2.26
org.glassfish.jersey.core:jersey-common:2.26
org.glassfish.jersey.ext:jersey-proxy-client:2.26
org.glassfish.jersey.inject:jersey-hk2:2.26
org.glassfish.jersey.media:jersey-media-jaxb:2.26
org.glassfish.jersey.media:jersey-media-json-binding:2.26
org.glassfish.jersey.media:jersey-media-json-jackson:2.26
org.raml.jaxrs:jaxrs-code-generator:2.1.1-SNAPSHOT

Should I use some other interface than Addresses here?

Addresses proxy = WebResourceFactory.newResource(Addresses.class, target);

What should be changed to make deserialization to work?

Kind regards,

Harri

Spring,JSP > sesssion variable keeps being null even though it is set

I’m learning Spring and is trying to use Spring and JSP to write a login page.

The session variable is set when the API is called from the front-end, yet when the page is directed and the program tries to check the session variable, it keeps getting null.

The code run in the back-end when the submit button of login page is pressed:

(the password and userid is sent for authentication, and the token key is stored in session storage when the response is back)

@Controller
@SessionAttributes("token")
public class AuthAction {
    @Autowired
    UserMapper userMapper;
    Logger logger = Logger.getLogger(TableAction.class);

    @RequestMapping(value="auth",method = RequestMethod.GET, produces="application/json")
    public @ResponseBody HashMap<String,Object> auth(
            ServletRequest req,
            @RequestParam(value = "id") String id
            ,@RequestParam(value = "password") String password
            ,ModelMap model) {
        HashMap<String,Object> map = new HashMap<String,Object>();  
        try {

            String token;
            User user = new User();
            user.setId(id);
            User result = userMapper.selectUser(user);

            if(result == null) {
                // no user exists
                throw new NoSuchUserException();
            }
            if(result.getPassword().equals(password) ) {
                // password is right
                // check if the user's authorized
                if(result.getAuthcode() != 1) {
                    throw new NotAuthorizedException();
                }
                // generate token
                SecureRandom random = new SecureRandom();
                byte bytes[] = new byte[20];
                random.nextBytes(bytes);
                token = bytes.toString();

                // set session variable
                 HttpServletRequest request = (HttpServletRequest) req;
                 HttpSession session = request.getSession(true);
                 session.setAttribute("token", token);
                 model.addAttribute("token",token);

                 System.out.println(session.getAttribute("token"));

            }else {
                // password is wrong
                throw new WrongPasswordException();
            }
            map.put("success", true);
            map.put("mes", token);
        }catch(NoSuchUserException e) {
            map.put("success", false);
            map.put("mes", 0);
        }catch(WrongPasswordException e) {
            map.put("success", false);
            map.put("mes", 1);
        }catch(NotAuthorizedException e) {
            map.put("success", false);
            map.put("mes", 2);
        }
        return map;
    }
}

This line did print out the right token key:

System.out.println(session.getAttribute("token"));

The JSP page which checks if the token key stored in session storage equals session variable:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" session="true"%>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>CMS</title>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-beta/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/limonte-sweetalert2/6.6.6/sweetalert2.min.css">
    <script charset="utf-8" type="text/javascript" language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/6.6.9/sweetalert2.common.js"></script>
    <script type="text/javascript">
        // from spring session variable
        var sessionToken = '<%= request.getSession().getAttribute("token") %>';
        //var sessionToken = ${sessionScope.token};
        // from localstorage
        console.log(sessionToken);
        var token = sessionStorage.getItem('token');
        alert(sessionToken);
        alert(token);
        alert(typeof token);
        if(token != sessionToken){
            window.location.replace("unauthorized.do");
        }
    </script>
  </head>
  <body>
    <div id="container"></div>
  </body>
  <script type="text/javascript" language="javascript" src="cms/public/bundle.js"></script>
</html>

The first line alerted null and the second alerted the right token key:

alert('<%= request.getSession() %>');
alert(token);

Any help is appreciated. Thanks a lot.

Java v Python for Web Scraping

I need to develop a project where in I would have to do web scraping. I was weighing my options and found that Java and Python have good libraries – Jsoup and Beautiful Soup, respectively – to help ease the process of development.
I want to know if using Python for web scraping has any advantages over Java. I would want to parse millions of pages, which would be better suited for this?

P.S.: I’m good at Java and a beginner in Python. I would not mind the learning curve if Python has advantages over Java.

Java JFrame render lagging

I’m trying to make a simple game in java using the swing engine. However currently I am having issues with lag. This simple code draws a circle and moves it from the top left corner of the frame to the bottom right corner, but it lags a lot. While my pc is somewhat old, i3 4gb ram, I think it should manage to perform this without lag?

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;

public class Game extends JPanel implements ActionListener {

  public Timer timer;
  int x = 0;
  int y = 0;

  public Game() {
    timer = new Timer(20, this);
    timer.start();
  }

  @Override
  public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.fillOval(x, y, 15, 15);
  }

  public void actionPerformed(ActionEvent e) {
    x++;
    y++;
    repaint();
  }

  public static void main(String[] args) throws InterruptedException {
    JFrame frame = new JFrame("test");
    Game game = new Game();
    frame.add(game);
    frame.setSize(600, 600);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   }
}

Get text from EditText and status of CheckBox then send these to a URL with HTTP POST

I have 1 Button, 1 EditText , 6 Checkbox and 1 TextView (in another activity)

I want these:
Firstly onClick the button, get text from EditText, save it to a variable and check if Checkbox are ticked or not, if checked generate a varibale and setText to TRUE else FALSE.

Secondly send 7 variables of checkbox and EditText to a URL via HTTP POST method. After that get server response and show it in TextView of another activity

This is my JAVA file but it doesn’t work, Would anyone correct these codes.

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import static com.royalrandhawa.untitled.R.id.mainSearch;

/**
 * Created by ROYAL on 10/11/2017.
 */

public class SurfAnony extends Activity {

    String one, two, three, four, five, six;
    CheckBox First, Second, Third, Fourth, Fifth, Sixth;
    TextView content;
    Button search = (Button) findViewById(R.id.surfNowBtn);
    EditText query = (EditText) findViewById(mainSearch);
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.surf_anony);

        First = (CheckBox) findViewById(R.id.eurlchb);
        Second = (CheckBox) findViewById(R.id.epagechb);
        Third = (CheckBox) findViewById(R.id.alckchb);
        Fourth = (CheckBox) findViewById(R.id.ftcchb);
        Fifth = (CheckBox) findViewById(R.id.djschb);
        Sixth = (CheckBox) findViewById(R.id.dsbchb);

        //First CheckBox
        First.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (First.isChecked()) {
                    one = "true";
                } else {
                    one = "false";
                }
            }
        });

        //Second CheckBox
        Second.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Second.isChecked()) {
                    two = "true";
                } else {
                    two = "false";
                }
            }
        });

        //Third CheckBox

        Third.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Third.isChecked()) {
                    three = "true";
                } else {
                    three = "false";
                }
            }
        });

        //Fourth CheckBox

        Fourth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Fourth.isChecked()) {
                    four = "true";
                } else {
                    four = "false";
                }
            }
        });

        //Fifth CheckBox

        Fifth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Fifth.isChecked()) {
                    five = "true";
                } else {
                    five = "false";
                }
            }
        });

        //Sixth CheckBox

        Sixth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Sixth.isChecked()) {
                    six = "true";
                } else {
                    six = "false";
                }
            }
        });


        search.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                try {
                    GetText();
                } catch (Exception ex) {
                    content.setText(" url exeption! ");
                }

            }
        });
}

    public void GetText() throws UnsupportedEncodingException {
        // Get user defined values
        String q = query.getText().toString();



        // Create data variable for sent values to server

        String data = URLEncoder.encode("q", "UTF-8")
                + "=" + URLEncoder.encode(q, "UTF-8");

        data += "&" + URLEncoder.encode("eurl", "UTF-8") + "="
                + URLEncoder.encode(one, "UTF-8");

        data += "&" + URLEncoder.encode("epage", "UTF-8")
                + "=" + URLEncoder.encode(two, "UTF-8");

        data += "&" + URLEncoder.encode("alck", "UTF-8")
                + "=" + URLEncoder.encode(three, "UTF-8");

        data += "&" + URLEncoder.encode("ftc", "UTF-8")
                + "=" + URLEncoder.encode(four, "UTF-8");

        data += "&" + URLEncoder.encode("djs", "UTF-8")
                + "=" + URLEncoder.encode(five, "UTF-8");

        data += "&" + URLEncoder.encode("dsb", "UTF-8")
                + "=" + URLEncoder.encode(six, "UTF-8");

        String text = "";
        BufferedReader reader = null;

        // Send data
        try {

            // Defined URL  where to send data
            URL url = new URL("my url here!");

            // Send POST data request

            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            // Get the server response

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while ((line = reader.readLine()) != null) {
                // Append server response in string
                sb.append(line + "n");
            }


            text = sb.toString();
        } catch (Exception ex) {

        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }

        // Show response on activity
        content.setText(text);

    }

}

Token SQL92 not supported

I have some troubles in my app using sqlRestriction method:

This is my movie class:

public class Movie {

    @Id
    @Column(name = "pk")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "movie_seq")
    @SequenceGenerator(name = "movie_seq", sequenceName = "movie_seq", allocationSize = 1, initialValue = 1)
    public long id;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    @Column(name = "name")
    public String str_name = "";

...

}

When i do something like that (dummy test):

List<Movie> movies = session.createCriteria(Movie.class)
        .add(Restrictions.sqlRestriction("1 in (1)"))
        .list();

It Works perfectly.

My second test (changing the Restriction):

.add(Restrictions.sqlRestriction("Movie.id in (166,171)"))

And my third test

add(Restrictions.sqlRestriction("{Movie}.id in (166,171)"))

Both of them fails in the same way:

ERROR: Token SQL92 no soportado en la posición: 345
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not extract ResultSet
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
    ...
Caused by: java.sql.SQLException: Token SQL92 no soportado en la posición: 345
    at oracle.jdbc.driver.OracleSql.handleODBC(OracleSql.java:1275)
    ...

What am I doing wrong?

Orientation change height

I have an activity with certain XML layout which contains image and a webview inside a scroll view.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layoutDirection="rtl"
    android:background="#241E33"
    tools:context="net.paymac.masra7masr.VideoActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/ad"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <ImageView
                    android:scaleType="fitStart"
                    android:adjustViewBounds="true"
                    android:id="@+id/imageViewAdVideo"
                    android:background="@android:drawable/dialog_holo_light_frame"
                    android:layout_width="match_parent"
                    android:layout_height="200dp" />
            </RelativeLayout>

            <FrameLayout
                android:id="@+id/fullScreen"
                android:layout_width="match_parent"
                android:layout_height="220dp">
                <WebView
                    android:background="#241E33"
                    android:id="@+id/webViewVideo"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"></WebView>
            </FrameLayout>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>

I am trying to hide the image and leave only the web view when orientation changes to landscape.

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

            ad.setVisibility(View.GONE);
            btnLn.setVisibility(View.GONE);
            getSupportActionBar().hide();
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){

            ad.setVisibility(View.VISIBLE);
            btnLn.setVisibility(View.VISIBLE);
            getSupportActionBar().show();

        }
    }

My question is how to change the frame layout height to match parent in landscape? I tried set layout parameters but app crashes.

Java multi threading thread.sleep()

I just started with the multi threading concepts of Java. I have written a small Java program but however I am really not able to understand its behavior.

public class Mythread implements Runnable{

    @Override
    public void run() {
        System.out.println("mythread: ");
        Thread t=new Thread(this,"thread1");

        for(int i=1;i<5;i++)
        {
            System.out.println("in for of myThread");

            try {
                t.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}


public class ThreadTest {

    public static void main(String[] args) {
        System.out.println("in main thread");
        Mythread mythread=new Mythread();
        Thread thread=new Thread(mythread,"thread0");
        thread.start();

        for(int i=1;i<5;i++)
        {
            System.out.println("main class: "+i);
            try {
                Thread.currentThread().sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

Now when I execute the above program I see that when thread1 goes to sleep thread0 also goes to sleep.

t.sleep(1000);

is thread1 and thread0 refers to same thread ?
Also I haven’t started thread1 anywhere in my code then why thread goes to sleep ?

I am just a beginner to multi threading and referring Java The Complete reference book.

Java – problematic Sieve of Eratosthenes

This is an assigment, so I’d prefer some hints over a already written code.

I am given a int array of size N (which is supposed to be a sieve of range [2,N]. I am supposed to write a class with two methods: first one checks if given number is prime and second one creates prime factorization of given number.

The problem is that my methods are supposed to work for all numbers up to max value of long, and range N of sieve i way, way smaller. It doesn’t even comes close to sqrt(Long.MAX_Value).
So, basically, I cannot create sieve large enough to solve my problem. Is there any way around that?