#StackBounty: #java Use bit masking to store application enabled features into DB

Bounty: 100

I want to store a lot of application features into database. I want to use one table row for this, so I want to use bit masking to store the enabled features. I tried this:

HashMap<String, Integer> map = new HashMap<String, Integer>();
int database_value = 0; 

public int setFeatureBitmask(int value) {
    int bitmask = 0;
    bitmask |= value;       
    return bitmask;
}

public static Set<String> processFeature(Integer bitmask) {
    HashMap<String, Integer> newMap = new HashMap<String, Integer>();

    return newMap.entrySet().stream().filter(e -> (e.getValue() & bitmask) == e.getValue()).map(e -> e.getKey())
            .collect(Collectors.toSet());
}

@BeforeAll
public void setupData() {
    System.out.println("Populating settings map");

    map.put("Type1", 1);
    map.put("Type2", 2);
    map.put("Type3", 4);
    map.put("Type4", 8);
    map.put("Type5", 16);
    map.put("Type6", 32);
    map.put("Type7", 64);
    map.put("Type8", 128);
    map.put("Type9", 256);
    map.put("Type10", 512);
    map.put("Type11", 1024);
    map.put("Type12", 2048);
    map.put("Type13", 4096);
    map.put("Type14", 8192);
    map.put("Type15", 16384);
    map.put("Type16", 32768);
    map.put("Type17", 65536);
    map.put("Type18", 131072);
    map.put("Type19", 262144);
}

@Test
public void writeData() {
    System.out.println("Converting Map using bitmasking");

    for(int i=0; i<map.size(); i++) {

        int number_value = map.get(i);                      
        int result = setFeatureBitmask(number_value);           
        database_value = database_value + result;
    }       
}

@AfterAll
public void databaseInsert() {
    System.out.println("Final resut to insert into Database " + database_value);

    System.out.println("Converting back values from database");

    // read here values from database_value variable and convert them into hash     
}

The first question is how to store the converted numbers as one big table value for example 15990793? Should I combine all converted numbers into one big number?
And also after I convert them how to translate them again so that I can use them?

Is there any working example? I found many bit mask examples but nothing complete working like my case. It’s totally unclear how to get the working result can you advice?


Get this bounty!!!

#StackBounty: #java #eclipse #debugging #jni #gdb Debugging OpenJDK source-code with eclipse

Bounty: 100

in my project i want to debug the C/C++ source code of the OpenJDK version 8 using eclipse. For this purpose I have done following:

  1. Compiled the OpenJDK8 with --with-debug-level=slowdebug using this readme.
  2. Imported the sources makefile project into eclipse
  3. Created an eclipse run configuration, executing gdb against the compiled OpenJDK’s java.exe and targeting a sample java program. Into this configuration I have attached the JDK source code directory path, so that eclipse is able to translate debug symbols to source-code lines and view them to me (obviously)

With this approach, I am able to debug through the code of files like java.c.

My problem is that somehow I still cannot debug through native code. Like for example java.lang.System.currentTimeMillis().

To me it looked like the libraries were not included into the eclipse gdb-run. I tried to run gdb manually, and it still didn’t work to debug through that code section.

Has anybody expirienced same behavior, or did ever try to debug the JDK source code? I guess I am missing something here… Maybe my approach is just not correct for the task? Would be glad to hear any proposal about how to debug the JDK source code propperly.

Thank you in advance.


Get this bounty!!!

#StackBounty: #java #spring-boot #jar #http-status-code-404 #embedded-tomcat-8 Spring boot web app with embedded tomcat giving 404 erro…

Bounty: 50

I am creating a Spring Boot web app (deployed as a JAR file) which contains an embedded Tomcat server. Everything works flawlessly on my dev machine but when i place the JAR file on a dedicated machine i get 404 errors no matter what i do. Here is the relevant code :

POM.XML

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.mdenis</groupId>
<artifactId>LEM2</artifactId>
<version>1.0-SNAPSHOT</version>

<name>Lab Equipment Manager</name>

<properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>

<dependencies>

     <!--JAVA-->
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>

    <!--TOMCAT-->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
    </dependency>

    <!--SPRING-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
    <exclusion>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-logging</artifactId>
    </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <!--<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>

    <!--MICROSOFT-->
    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
    </dependency>

    <!--HIBERNATE-->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.12.Final</version>
    </dependency>

    <!--LOMBOK-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>

    <!--JSTL-->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>

</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <compilerArguments>
                    <endorseddirs>${endorsed.dir}</endorseddirs>
                </compilerArguments>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>3.1.1</version>
            <executions>
                <execution>
                    <phase>validate</phase>
                    <goals>
                        <goal>copy</goal>
                    </goals>
                    <configuration>
                        <outputDirectory>${endorsed.dir}</outputDirectory>
                        <silent>true</silent>
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <finalName>LabEquipmentManager</finalName>
                <appendAssemblyId>false</appendAssemblyId>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

WebServerFactoryCustomizer bean :

@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() 
{
    return factory -> factory.setContextPath("/LEM2");
}

ViewResolver bean :

@Bean
public ViewResolver viewResolver() 
{
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setViewClass(JstlView.class);
    viewResolver.setPrefix("/WEB-INF/views/");
    viewResolver.setSuffix(".jsp");

    return viewResolver;
}

Part of the main controller (of course there is more to it, just including a part of it to show how the endpoints are built) :

@Controller
@RequestMapping("/")
public class MainController
{
    @Autowired
    private UserService userService;

    @RequestMapping(value = {"/", "/home"}, method = RequestMethod.GET)
    private String main(HttpServletRequest request) 
    {
        if (request.getSession().getAttribute("loggedInUser") != null)
        {
            return "home";
        }
        else
        {
            return "login";
        }
    }
}

Again, everything works perfectly on my dev machine by doing localhost:8080/LEM2. Any idea why it won’t work when deployed on another server?

Thanks!


Get this bounty!!!

#StackBounty: #java Implement Simulated Thread#sleep()

Bounty: 50

Background

I am designing my software so that I can easily perform unit tests. I have an IClock interface which, among other methods, has
IClock#wait(TimeUnit timeUnit, long duration). This method will halt the current thread for timeUnit duration (i.e. 1 second).

There are two implementations of the IClock interface:

  • SimulatedClock: has methods to manually increase the time stored in the clock
  • RealClock: time increases automatically by referencing System.currentTimeMillis()

This is the default method for IClock#wait(...):

/**
     * Locks current thread for specified time
     *
     * @param timeUnit
     * @param dt
     */
    default void wait(TimeUnit timeUnit, long dt)
    {
        Lock lock = new ReentrantLock();
        scheduleIn(timeUnit, dt, lock::unlock);
        lock.lock();
    }

Problem

The current way I want simulated unit tests to work is

  1. Start threads
  2. Wait until all threads are either done or in a blocked state (I am assuming if they are blocked, they have called IClock#wait(...))
  3. If all threads are finished, finish. Else, increase SimulatedClock time by one millisecond.

However, what is really happening is:

  1. Start threads
  2. Start increasing time even though threads have not called IClock#wait() for the first time.

So, what I need to do is to be able to determine when all threads are done or blocked. Although this can be done with Thread#getState(), I would rather employ a solution which is more elegant and works with ForkJoinPool.

Full Code

GitHub

SimulatedClock

package com.team2502.ezauton.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class SimulatedClock implements IClock
{

    private long time = 0;

    private List<Job> jobs = new ArrayList<>();

    public SimulatedClock() {}

    public void init()
    {
        init(System.currentTimeMillis());
    }

    public void init(long time)
    {
        setTime(time);
    }

    /**
     * Add time in milliseconds
     *
     * @param dt millisecond increase
     * @return The new time
     */
    public long addTime(long dt)
    {
        setTime(getTime() + dt);
        return getTime();
    }

    /**
     * Adds time with units
     *
     * @param timeUnit
     * @param value
     */
    public void addTime(TimeUnit timeUnit, long value)
    {
        addTime(timeUnit.toMillis(value));
    }

    /**
     * Add one millisecond and returns new value
     *
     * @return The new time
     */
    public long incAndGet()
    {
        return addTime(1);
    }

    /**
     * Increment a certain amount of times
     *
     * @param times
     */
    public void incTimes(long times, long dt)
    {
        long init = getTime();
        long totalDt = times * dt;
        for(int i = 0; i < times; i++)
        {
            if(!jobs.isEmpty())
            {
                addTime(dt);
            }
            else
            {
                break;
            }
        }
        setTime(init + totalDt);
    }

    /**
     * Increment a certain amount of times
     *
     * @param times
     * @return
     */
    public void incTimes(long times)
    {
        incTimes(times, 1);
    }

    @Override
    public long getTime()
    {
        return time;
    }

    public void setTime(long time)
    {
        jobs.removeIf(job -> {
            if(job.getMillis() < time)
            {
                job.getRunnable().run();
                return true;
            }
            return false;
        });

        this.time = time;
    }

    @Override
    public void scheduleAt(long millis, Runnable runnable)
    {
        if(millis < getTime())
        {
            throw new IllegalArgumentException("You are scheduling a task for before the current time!");
        }
        jobs.add(new Job(millis, runnable));
    }

    private static class Job
    {
        private final long millis;
        private final Runnable runnable;

        public Job(long millis, Runnable runnable)
        {
            this.millis = millis;
            this.runnable = runnable;
        }

        public long getMillis()
        {
            return millis;
        }

        public Runnable getRunnable()
        {
            return runnable;
        }
    }
}

Simulation

package com.team2502.ezauton.command;

import com.team2502.ezauton.utils.SimulatedClock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

public class Simulation
{

    private final SimulatedClock simulatedClock;
    private List<IAction> actions = new ArrayList<>();

    public Simulation()
    {
        simulatedClock = new SimulatedClock();
    }

    public SimulatedClock getSimulatedClock()
    {
        return simulatedClock;
    }

    public Simulation add(IAction action)
    {
        actions.add(action);
        return this;
    }

    /**
     * @param timeoutMillis Max millis
     */
    public void run(long timeoutMillis)
    {
        simulatedClock.init();

        actions.forEach(action -> new ThreadBuilder(action, simulatedClock).buildAndRun());

        simulatedClock.incTimes(timeoutMillis);

        // Need to wait until all threads are finished
        if(!ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.SECONDS))
        {
            throw new RuntimeException("Simulator did not finish in a second.");
        }

    }

    public void run(TimeUnit timeUnit, long value)
    {
        run(timeUnit.toMillis(value));
    }
}

Example Unit Test

@Test
public void testSimpleAction()
{
    AtomicBoolean atomicBoolean = new AtomicBoolean(false);
    Simulation simulation = new Simulation();
    simulation.add(new DealyedAction((TimeUnit.SECONDS, 5) -> atomicBoolean.set(true)));
    simulation.run(TimeUnit.SECONDS, 100);
    Assert.assertTrue(atomicBoolean.get());
}


Get this bounty!!!

#StackBounty: #java #windows #launch4j #winrar #izpack Unable to run self-extracting installer – Unable to access jarfile C:UsersRay…

Bounty: 100

I have a Java application, the Izpack installer is wrapped with launch4j64bit and then bundled as a self-extracting ZIP, created with WinRAR 5.20 using a method as described in an answer on How do I make a self extract and running installer?

It works, for me and most customers, but recently a few customers have reported errors like this:

Unable to access jarfile C:UsersRayAppDataLocalTempRarSFX0install.jar

I am unable to reproduce this error.

What could be causing this problem? Is it related to a Windows updates?

There is a only a problem with self-extracting version, a regular .zip file that users have to extract themselves works fine.

When I run the self-extracting archive it self-extracts correctly. So we have this folder structure:

  • a folder JVM64,
  • a file install.jar,
  • a file setup.exe and
  • a file setup.ico.

But for users having a problem it only extracts JVM64:

 Volume in drive C has no label.
 Volume Serial Number is A663-4CEF

 Directory of C:UsersgcdrAppDataLocalTemp

14/08/2018  21:40    <DIR>          .
14/08/2018  21:40    <DIR>          ..
14/08/2018  21:40    <DIR>          RarSFX0
               0 File(s)              0 bytes

 Directory of C:UsersgcdrAppDataLocalTempRarSFX0

14/08/2018  21:40    <DIR>          .
14/08/2018  21:40    <DIR>          ..
14/08/2018  21:40    <DIR>          JVM64
               0 File(s)              0 bytes

I found for one user that disabling Norton AntiVirus allowed installation.
Now I use to submit each new version to Norton whitelist, but that option has gone.

Why could this be? Could there be some restriction with files called install.jar?


Get this bounty!!!

#StackBounty: #java #windows #launch4j #winrar #izpack Unable to run self extracting installer – Unable to access jarfile C:UsersRay…

Bounty: 100

I have a Java Application, the Izpack installer is wrapped with launch4j64bit and then bundled as a self extracting zip with Winrar

It works, for me and most customers, but recently a few customers have reported errors like this

Unable to access jarfile C:UsersRayAppDataLocalTempRarSFX0install.jar

I am unable to replicate, what could be causing this problem, is it related to a Windows updates. There is a only a problem with self-extracting version, a regular .zip file that user has to extract themself works fine.

When I run the self extractor it self-extracts correctly so we have this folder structure, a JVM64 folder, an install.jar, aa setup.exe and a setup.ico.

enter image description here

But for users having a problem it only extracts JVM64

Volume in drive C has no label.
 Volume Serial Number is A663-4CEF

 Directory of C:UsersgcdrAppDataLocalTemp

14/08/2018  21:40    <DIR>          .
14/08/2018  21:40    <DIR>          ..
14/08/2018  21:40    <DIR>          RarSFX0
               0 File(s)              0 bytes

 Directory of C:UsersgcdrAppDataLocalTempRarSFX0

14/08/2018  21:40    <DIR>          .
14/08/2018  21:40    <DIR>          ..
14/08/2018  21:40    <DIR>          JVM64
               0 File(s)              0 bytes

why could this be ?


Get this bounty!!!

#StackBounty: #java #api #networking #socket #web-services Java Messenger data transmission

Bounty: 50

This is a very simple concern, could somebody take a look at a few lines of my code? I’m writing a simple Java multi-user messenger, it is structured in a desktop client with a Swing GUI, a java server based on plain sockets and a service library holding general utilities… At the moment I transmit messages through a ObjectOutputStream/ObjectInputStream with a custom Packet class…

package org.x1c1b.carrierpigeon.service.packet;

import java.io.Serializable;
import java.util.Objects;

public class Packet implements Serializable
{
    protected String source;
    protected String destination;

    protected int type;
    protected String payload;

    public Packet(String source, String destination, PacketType type, String payload)
    {
        this.source = source;
        this.destination = destination;

        this.type = type.getIdentifier();
        this.payload = payload;
    }

    public Packet(Packet packet)
    {
        this.source = packet.source;
        this.destination = packet.destination;

        this.type = packet.type;
        this.payload = packet.payload;
    }

    protected Packet(PacketBuilder builer)
    {
        this.source = builer.source;
        this.destination = builer.destination;

        this.type = builer.type;
        this.payload = builer.payload;
    }

    public String getSource()
    {
        return this.source;
    }

    public String getDestination()
    {
        return this.destination;
    }

    public PacketType getType()
    {
        return PacketType.getByIdentifier(this.type);
    }

    public String getPayload()
    {
        return this.payload;
    }

    @Override public boolean equals(Object object)
    {
        if(this == object)
        {
            return true;
        }

        if(object == null || getClass() != object.getClass())
        {
            return false;
        }

        Packet packet = (Packet) object;

        return type == packet.type && Objects.equals(source, packet.source) && Objects
                .equals(destination, packet.destination) && Objects.equals(payload, packet.payload);
    }

    @Override public int hashCode()
    {
        return Objects.hash(this.source, this.destination, this.type, this.payload);
    }
}

This is the Packet class used to transmit the message, for identifying the message purpose I uses a Enum defining different PacketType‘s…

package org.x1c1b.carrierpigeon.service.packet;

import java.util.NoSuchElementException;

public enum PacketType
{
    HANDSHAKE_REQUEST(1),
    HANDSHAKE_REPLY(2),
    HANDSHAKE_ERROR(3),
    AUTHENTICATION_REQUEST(4),
    AUTHENTICATION_REPLY(5),
    AUTHENTICATION_ERROR(6),
    CONNECTIVITY_ESTABLISHED(7),
    CONNECTIVITY_HALTED(8),
    CONNECTIVITY_STATUS(9),
    CONNECTIVITY_SETUP(10),
    CONNECTIVITY_ERROR(11),
    DATA_TRANSFER(12),
    DATA_TRANSFER_ERROR(13);

    private int identifier;

    private PacketType(int identifier)
    {
        this.identifier = identifier;
    }

    public int getIdentifier()
    {
        return this.identifier;
    }

    public static PacketType getByIdentifier(int identifier)
    {
        for(PacketType type : PacketType.values())
        {
            if(type.identifier == identifier)
            {
                return type;
            }
        }

        throw new NoSuchElementException("Identifier: " + identifier);
    }
}

Maybe for taking a look at the whole project:

I’m not that much expired in network development with java, so are there any improvements by transmission of messages? Is it common practice to use ObjectStream‘s with a custom “Protocol”/Packet to transmit data or should I use already existing protocols like HTTP instead? I tried to hold it simple without REST or huge webservers…

I will be glad about any improvements or tips for the data transmission…

EDIT

I also anticipate to write a basic API with the Remote Procedure Call pattern, here a basic example to illustrate what I mean:

public interface MessengerServiceAPI
{
    public abstract boolean login(String name);
}

Here the server-side implementation of the service API:

public class MessengerService implements MessengerServiceAPI
{
    @Override public boolean login(String name)
    {
        // Some login logic and database interaction on server-side
    }
}

Now I superior to call this server-side method with RPC through a ObjectStream:

// Method used on client-side to call remote method of service API

public Object call(String name, Object [] params) throws Exception
{
    try(Socket socket = new Socket(this.address, this.port);
            ObjectOutputStream sout = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream sin = new ObjectInputStream(socket.getInputStream()))
    {
        sout.writeObject(name);
        sout.writeObject(params);
        sout.flush();

        Object object = sin.readObject();

        if(object instanceof Exception)
        {
            throw (Exception) object;
        }

        return object;
    }
}

// The server-side handler to handle API requests, which execute the requested action on server-side and return the return value of it

@Override public void handle(Socket socket)
{
    try (ObjectInputStream sin = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream sout = new ObjectOutputStream(socket.getOutputStream()))
    {
        Object object;
        String name = (String) sin.readObject();
        Object [] params = (Object[]) sin.readObject();

        try
        {
            Class <?> [] paramTypes = null;

            if(null != params)
            {
                types = new Class[params.length];

                for(int index = 0; index < params.length; ++index)
                {
                    paramTypes[index] = params[index].getClass();
                }
            }

            Method method = this.service.getClass().getMethod(name, paramTypes);
            object = method.invoke(this.service, params);
        }
        catch(InvocationTargetException exc)
        {
            object = exc.getTargetException();
        }
        catch(Exception exc)
        {
            object = exc;
        }

        sout.writeObject(object);
        sout.flush();
    }
    catch(Exception exc)
    {
        exc.printStackTrace();
    }
}

This is one possible implementation of such a service handling, but is it recommended to write such a basic API and service? Or is it recommended to send a string or packet instead with a identifier and the server executes the action by parsing this identifier?

Sorry because it is also in big parts software design not just code review but I’m waiting for somebody who takes a look on my code to give tips or improvements…


Get this bounty!!!

#StackBounty: #pi-2 #java #pi4j #lcd #adafruit PI4J + Adafruit LCD with MCP23017

Bounty: 50

Got this device.

enter image description here

enter image description here

Python example char_lcd_plate.py is working perfect.

But I would like to manage it with Pi4J.

I copied bits from python example

LCD_PLATE_RS            = 15
LCD_PLATE_RW            = 14
LCD_PLATE_EN            = 13
LCD_PLATE_D4            = 12
LCD_PLATE_D5            = 11
LCD_PLATE_D6            = 10
LCD_PLATE_D7            = 9

Java:

LCD lcd = new I2CLcdDisplay(2, 16, 1, 0x20, 0, 15, 14, 13, 9, 10, 11, 12);
lcd.clear();
lcd.write(0, "111 ");
lcd.write(1, "222");

Init is fine but I have blue boxes on the screen and no any updates.
Any advice?


Get this bounty!!!

#StackBounty: #java #spring #vaadin Scoped Spring events possible?

Bounty: 50

The Spring event mechanism supports publishing application events and listening to these events within Spring components via the @EventListener annotation. However, I cannot find anything about sending events within a specific scope in the documentation. My specific need for Vaadin is:

  • in context of a user interaction, send an event (e.g. logged-in event)
  • this event should only be consumed by beans in same @UIScope, i.e. other user UIs shouldn’t be effected

Is that possible? NOTE: This is not really specific to Vaadin. I could also ask how it would be done with Spring web mvc request scope.


Get this bounty!!!

#StackBounty: #java #android #android-fragments #android-viewpager java.lang.IllegalStateException: Fragment not attached to a context

Bounty: 50

I have a tablayout with a viewpager in my MainActivity.

My PagerAdapter looks like this:

public class MainActivityPagerAdapter extends PagerAdapter {

    public MainActivityPagerAdapter(FragmentManager fm, int numOfTabs) {
        super(fm, numOfTabs);
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                return new StoresFragment();
            case 1:
                return new OrdersFragment();
            default:
                return null;
        }
    }
}

I am coming back from another activity like this:

Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish(); //finishAffinity();

But then I get an java.lang.IllegalStateException in one of my Fragments in the viewpager of the MainActivity.

I read many related questions and tried to solve this. It is said, that this happens when one keeps references to Fragments outside of the PagerAdapter. But I am not doing this, as you can see in my code.

Does anyone know what I am doing wrong?

Edit – Stacktrace

FATAL EXCEPTION: main
    Process: com.lifo.skipandgo, PID: 23665
    java.lang.IllegalStateException: Fragment OrdersFragment{42c2a740} not attached to a context.
    at android.support.v4.app.Fragment.requireContext(Fragment.java:614)
    at android.support.v4.app.Fragment.getResources(Fragment.java:678)
    at com.lifo.skipandgo.activities.fragments.OrdersFragment$1.results(OrdersFragment.java:111)
    at com.lifo.skipandgo.connectors.firestore.QueryResult.receivedResult(QueryResult.java:37)
    at com.lifo.skipandgo.controllers.UserController$2.onUpdate(UserController.java:88)
    at com.lifo.skipandgo.connectors.firestore.QuerySubscription.onEvent(QuerySubscription.java:59)
    at com.lifo.skipandgo.connectors.firestore.QuerySubscription.onEvent(QuerySubscription.java:18)
    at com.google.firebase.firestore.zzg.onEvent(Unknown Source)
    at com.google.firebase.firestore.g.zzh.zza(SourceFile:28)
    at com.google.firebase.firestore.g.zzi.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5653)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)

Edit:
Interesting is, that the view has defenitely loaded when the error occurs. Because the error occurs about 10-15 seconds later after the fragment is shown again. I this in my orderFragment, where the error occurs:

orders = new QueryResult<UserOrder>(UserOrder.class) {
            @Override
            public void results(List<UserOrder> results) { 
orderLoadingMessage.setBackgroundColor(getResources().getColor(R.color.green)); 
    }
}

I do this in onCreateView and this result comes about 10-15 seconds after the view loaded.


Get this bounty!!!