Filte JPA repository by multiple optional parameters

I have a simple REST service that returns user profile entity that has about 20 fields
I need to implement a functionality to filter the data where last name is required but all other fields(first name,age,city, state,zip, etc ) are optional.
Is there a way to do it using JpaRepository without creating a lot of if/else statements for every single combination of patamenters

Spark fails to bind http port

I am trying to bind port 80 to my Spark server :

import static spark.Spark.get;
import static spark.Spark.port;

public class Main {

    public static void main(String[] args) {
        port(80);
        get("/hello", (request, response) -> "hello world");
    }
}

But for some reason I getting the following error :

22:51:56.067 [Thread-0] ERROR spark.Spark - ignite failed
java.net.SocketException: Permission denied
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:433)
    at sun.nio.ch.Net.bind(Net.java:425)
    at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at org.eclipse.jetty.server.ServerConnector.open(ServerConnector.java:298)
    at org.eclipse.jetty.server.AbstractNetworkConnector.doStart(AbstractNetworkConnector.java:80)
    at org.eclipse.jetty.server.ServerConnector.doStart(ServerConnector.java:236)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.server.Server.doStart(Server.java:431)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at spark.embeddedserver.jetty.EmbeddedJettyServer.ignite(EmbeddedJettyServer.java:149)
    at spark.Service.lambda$init$2(Service.java:496)
    at java.lang.Thread.run(Thread.java:748)

I searched everywhere in my OS if there’s any connected bind to port 80, but i didn’t find .
there’s any solution?

minijava recursive descent parser

I need some guidelines/samplecode to write a recursive descent parser in order to determine whether a minijava program is syntactically correct.

Here is the parser code so far:

public class MiniJavaParser {

public static String readProgramConsole() {
    @SuppressWarnings("resource")
    Scanner sin = new Scanner(System.in);
    StringBuilder builder = new StringBuilder();
    while (true) {
        String nextLine = sin.nextLine();
        if (nextLine.equals("")) {
            nextLine = sin.nextLine();
            if (nextLine.equals("")) {
                break;
            }
        }
        if (nextLine.startsWith("//")) {
            continue;
        }

        builder.append(nextLine);
        builder.append('n');
    }
    return builder.toString();
}

public static String[] lex(String program) {
    return null; // Todo
}

public static int parseNumber(String[] program, int from) {
    return -1; // Todo
}

public static int parseName(String[] program, int from) {
    return -1; // Todo
}

public static int parseType(String[] program, int from) {
    return -1; // Todo
}

public static int parseDecl(String[] program, int from) {
    return -1; // Todo
}

public static int parseUnop(String[] program, int from) {
    return -1; // Todo
}

public static int parseBinop(String[] program, int from) {
    return -1; // Todo
}

public static int parseComp(String[] program, int from) {
    return -1; // Todo
}

public static int parseExpression(String[] program, int from) {
    return -1; // Todo
}

public static int parseBbinop(String[] program, int from) {
    return -1; // Todo
}

public static int parseBunop(String[] program, int from) {
    return -1; // Todo
}

public static int parseCondition(String[] program, int from) {
    return -1; // Todo
}

public static int parseStatement(String[] program, int from) {
    return -1; // Todo
}

public static int parseProgram(String[] program) {
    return -1; // Todo
}

public static void main(String[] args) { // Todo
}
}

Each of these methods expects an array existing of tokens as parameters as well as a starting index. A token is the logically associated unit of the input program, e.g. the word read. The method should parse the nonterminal and return the index of the next token after the nonterminal. If the parsing fails, a negative number should be returned.

Before a program can be parsed, it has to be split into tokens. In this case case a token is
• A bracket (round as well as curly) or a comma
• An operator
• A number or
• A name (also key words like e.g. read, write, int).

Spaces and line breaks will be discarded during the lex method. The MiniJava program:

int sum, n, I;
n = read();
while  (n < 0) {
  n = read();
}

will thus be split into the token array [int, sum, ,, n, ,, i, ;, n, =, read, (, ), ;, while, (, n, <, 0, ), {, n, =, read, (, ), ;, }].

Use the following approach in your implementation:

  1. Implementing the method String lex(String program), which converts a program into an array of tokens.
  2. Implement the remaining methods of the parser. It might be helpful to implement helping methods.
  3. Implementing main program that asks the user for a program and eventually dispenses whether the program could be parsed correctly. Using readProgramConsole() might help

Java Array Element Type

I want to know what kinds of reference can be array elements.

I know that there’re primitive types like:

String[] strs = new String[5];

But there is no

List<String>[] stringList; 

However, when I new a class, there is

Class Student{
     String name;
     List<String> courses;
}

Student[] students = new Student[5];

It says “The element type of an array may be any type, whether primitive or reference.”

I think Student is reference and List<> is also reference. What’s the difference between them?

Thanks.

Spring Jpa with PostgresSql ddl-auto=update is raising error

I am creating a security service using spring JPA annotation based.
in the datasource configuration of application.properties I have following configurations

spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto= update
.

I am getting the following errors

  Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider._createContainerEntityManagerFactorySpringHibernateJpaPersistenceProvider(SpringHibernateJpaPersistenceProvider.java:60) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:360) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:382) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:371) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:336) ~[spring-orm-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624) ~[spring-beans-4.3.13.RELEASE.jar:4.3.13.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.exception.SQLGrammarException: Error accessing column metadata: users
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.convertSQLException(InformationExtractorJdbcDatabaseMetaDataImpl.java:99) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getForeignKeys(InformationExtractorJdbcDatabaseMetaDataImpl.java:679) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.extract.internal.TableInformationImpl.foreignKeys(TableInformationImpl.java:88) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.extract.internal.TableInformationImpl.getForeignKey(TableInformationImpl.java:99) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.findMatchingForeignKey(SchemaMigratorImpl.java:398) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.applyForeignKeys(SchemaMigratorImpl.java:376) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:214) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:134) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:472) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879) ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]
    ... 24 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: column t1.tgconstrname does not exist
  Position: 113
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2103) ~[postgresql-9.1-901-1.jdbc4.jar:na]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1836) ~[postgresql-9.1-901-1.jdbc4.jar:na]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) ~[postgresql-9.1-901-1.jdbc4.jar:na]
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:512) ~[postgresql-9.1-901-1.jdbc4.jar:na]
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:374) ~[postgresql-9.1-901-1.jdbc4.jar:na]
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:254) ~[postgresql-9.1-901-1.jdbc4.jar:na]
    at org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData.getImportedExportedKeys(AbstractJdbc2DatabaseMetaData.java:3477) ~[postgresql-9.1-901-1.jdbc4.jar:na]
    at org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData.getImportedKeys(AbstractJdbc2DatabaseMetaData.java:3670) ~[postgresql-9.1-901-1.jdbc4.jar:na]
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getForeignKeys(InformationExtractorJdbcDatabaseMetaDataImpl.java:628) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
    ... 35 common frames omitted

I made sure that I dont have user table as it is a keyword in postgres sql.

And it is working fine and creating the schema when I am using
spring.jpa.hibernate.ddl-auto= create-drop.

But I am not using create-drop as the schema and data will be dropped as soon as the application is stopped and restarted which would be not desired in production.

Please help where I am missing it. I can add more details about the schema I am using and Entities I have in the application. Any help or source of information is appreciated.

Do I have to add any special dependencies while using postgres? I have the PostgresSQl driver dependency in the POM.

Android: Parallax activity background on Listview scroll

I was wondering if I could have some help with something I’ve spent the last 3 days trying and failing at creating.

I have an activity with a constraint layout that looks like the following:

App screen structure

Each element has a level of transparency to it that I want to use to show a background image behind it which scrolls upwards as the user scrolls down through the list view like this:

enter image description here

There is very little in the way of guides and tutorials on this kind of thing and the ones I can find don’t quite fit this situation or use external libraries which I want to avoid – I want to write this myself.

I have tried a lot of different ways e.g. listview headers, backgrounds etc. but the most successful way has been adding an imageview behind everything that is constrained at to all 4 sides of the screen and trying to update the position as the user scrolls.

The image position is changed with the following listener on the Listview:

LstVwPaintingsList.setOnScrollListener(new AbsListView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            int PixelsDown;
            int TotalHeight;
            float ScrollPercent = 0;

            int index = LstVwPaintingsList.getFirstVisiblePosition();
            View v = LstVwPaintingsList.getChildAt(0);

            if (v != null) {

                int top = v.getTop() - LstVwPaintingsList.getPaddingTop();

                PixelsDown = (index * v.getHeight()) - top;

                TotalHeight = (totalItemCount) * v.getHeight();

                ScrollPercent = ((float)PixelsDown / (float)TotalHeight);
            }

            int Position = (int)(ImageHome - ScrollPercent * 400);

            Imageview2.setTop(Position);
        }
    });

The issue with this though is if I rotate the device or resize the image by calling either:

Imageview.getLayoutParams().height() = //Integer height value;

or

Imageview.setLayoutParams( params ) // params is a ConstraintLayout.LayoutParams object with height and width specified

then the image just moves off center and looks bad, though it still moves upwards as desired.

I feel like this should be really simple to do but I’ve have been at this 3 days straight and am about ready to just give up and just apply a none-moving background to the layout and call it a day. I really hate giving up though so i’d really appreciate some help/advice figuring this out. Any ideas?

PreparedStatement.executeUpdate() not affecting database

I want to insert values into a database table. The table has two columns: id and image. The id is an auto-increment int and the image is a blob type. Here is my code:

try {
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection(url, userName, password);
    File imgfile = new File(request.getParameter("img"));
    InputStream fin = new FileInputStream(imgfile);
    PreparedStatement pre = con.prepareStatement("insert into pictures (image) values(?)");
    pre.setBinaryStream(1, fin, imgfile.length());
    int done=pre.executeUpdate();
} catch(SQLException | ClassNotFoundException e) {
    e.printStackTrace();
}

I check the database and nothing inserted. Server Output:

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for
column ‘image’ at row 1

How to configure logger level to FINEST for Wildfly Swarm

I have followed this guide for project*.yml.

I created two files under src/main/resources:

project-default.yml which contains:

logger:
  level: INFO
swarm:
  http:
    port: 80

and project-dev.yml which contains:

logger:
  level: FINEST
swarm:
  http:
    port: 8080

I have successfully switched between them by using the flagg -Dswarm.project.stage=dev, verifying that the port is actually changed.

By some reason when using the dev-profile the application refuses to logg anything logged with logger.finest(…) while when using logger.info(…) it is logged correctly.

Did I configure the logging levels incorrectly? In that case, how should they be configured?

Session limit configuration – Hibernate

In C API for database that I worked for, we configured number of database connections to limit to 64 or 128, through configuration.


An instance of SessionFactory is at application scope

As mentioned here, The most common pattern in a multi-user client/server application is session-per-request.


After deciding the safe limit for number of sessions for an application, does Hibernate allow to set the session limit in hibernate.cfg.xml?

How to prevent repeated actions from a key being held down? (Java FX)

I’m trying to make a simple action in a Java FX “game” in which an image of a pig ‘jumps’ upwards everytime the spacebar is pressed. Here is the code for the key event handlers and the Animation Timer that I’m using to actually carry out the action.

Key Handlers:

  ArrayList<String> in = new ArrayList<String>();

    s.setOnKeyPressed(
        new EventHandler<KeyEvent>()
           {

            public void handle(KeyEvent e)
            {
                String code = e.getCode().toString();

                 if ( !in.contains(code) ){
                 in.add( code );                          
                 }

            }
        });

      s.setOnKeyReleased(
        new EventHandler<KeyEvent>()
        {
            public void handle(KeyEvent e)
            {                   
                String code = e.getCode().toString();
                in.remove( code );
            }
        });

Animation timer:

   new AnimationTimer()
{
    double q = 200;
    public void handle(long currentNanoTime)
    {
        double t = (currentNanoTime - startNanoTime) / 4000000.0;    

       if(in.contains("SPACE")){

            q -= 20;

        }

        double y = q + t;

        if(y >= 520){
            gc.drawImage(background1, 0, 0, 1160, 740);
            gc.drawImage(pig, 90, 520, 125, 100);

        }else{
        gc.drawImage(background1, 0, 0, 1160, 740);
        gc.drawImage(pig, 90, y, 125, 100);
        }

    }
}.start();

So as you can see I’m having the animation timer simply cause the ‘pig’ to gradually fall down the y-axis, and when the spacebar is pressed, it is given a slight boost upwards.

The problem is that if the spacebar is held down, the pig just flies continuously upwards without stopping. I want this to be prevented so that the spacebar must be repeatedly tapped and not just held down. So I want only one ‘jump’ per spacebar press. Nothing that I’ve tried to workaround it has worked. If anyone has any suggestions it’d be greatly appreciated.