#StackBounty: #java #linux #spring-boot #log4j How to Extern log4j.properties file with Spring Boot Microservice and Run It As a Linux …

Bounty: 100

Have a Spring Boot (1.5.4.RELEASE) based microservice which I deploy a jar to an AWS EC Instance (Linux environment). Now, I am also deploying an external log4j.properties file so I have to start the microservice like this:

java -jar myapp.jar -Dlogging.config=/path/to/log4j.properties

How can I configure this Spring Boot Microservice as a Linux service where I can start and stop it using these flags:

sudo service myapp start | stop | status | restart

Thank you very much.


Get this bounty!!!

#StackBounty: #java #spring #transactions #transactional #spring-orm Spring Transactional slows down complete process

Bounty: 50

I am trying to analyze a situation where I have two classes. One class is ProcessImpl which is starting point and internally calls other child transactions.I dont know whats going wrong.
The processImpl is importing some stuff and writing related data to database.

Specs

Spring-orm version : 3.2.18.RELEASE.

JDK version : 1.8.

Db : H2 (on any db same performance is recorded).

Issue

If I remove @Transactional from ProcessImpl.processStage() the process takes ~ 50 seconds
If I keep @Transactional from ProcessImpl.processStage() the process takes ~ 15 minutes.
Dont know why this is happening.
I have been trying to solve this issue since long but no luck. Please have a look at code below.

Requirement:
The complete processStage() should complete or rollback completely, even if one of child transactions fail.

Fyi : I also get lot of messages like : “Participating in existing transaction”. Tried to get over this by adding propagation=Propagation.NESTED to processStage() but did not work.

ProcessImpl Class.

public class ProcessImpl {

    /*This is the big transaction that calls other transactional stuff from MyServiceImpl
    * This is starting point you can say for the process...
    * 
    * If we remove @Transactional from here the process is lightning fast 
    * With transactional : 15minutes
    * Without transactional : 50 seconds
    * */
    @Transactional
    public void processStage(){
        MyServiceImpl mp = new MyServiceImpl();
        //do some stuff
        mp.doWork1();

        //do more work
        mp.doWork2();

    }

}

MyServiceImpl Class

class MyServiceImpl{

    @Transactional
    public void doWork1(){
        Object o = doChildWork();
        // and more stuff
        //calls other class services and dao layers
    }

    @Transactional
    public void doWork2(){
        //some stuff
        doChildWork2();
        doChildWork();
        //more work
    }

    @Transactional
    public Object doChildWork(){
        return new Object(); //hypothetical, I am returning list and other collection stuff
    }

    @Transactional
    public Object doChildWork2(){
        return new Object(); //hypothetical, I am returning list and other collection stuff
    }

}

Also, here will I get self invocation issue, which is not advisable in Transactional?


Get this bounty!!!

#StackBounty: #java #jboss #jndi #hornetq Steps to make an existing JNDI HornetQ service as HA?

Bounty: 100

TL;DR

What are the steps to configure a HA-JNDI service with a HornetQ setup? I believe the documentation is a little scattered. I have read through the docs here but doesn’t seem to illustrate in detail.

Longer version:

So we have a HornetQ JMS setup along with JNDI. We have say 5 servers, that run the HornetQ JMS master instance with JNDI service on each. On each of these 5 servers, we also have a slave running for some other HornetQ master.

To illustrate:

Server A - HornetQa_master, JNDI, HornetQb_slave
Server B - HornetQb_master, JNDI, HornetQc_slave
Server C - HornetQc_master, JNDI, HornetQd_slave
Server D - HornetQd_master, JNDI, HornetQe_slave
Server E - HornetQe_master, JNDI, HornetQa_slave

Each of these HornetQ servers serve as middleware for our various backend needs, so that means 5 servers, 5 HornetQ master instances, 5 HornetQ slave instances and 5 JNDI servers. The problem, however, with this setup is that if a server host (not just the process, the host itself), say A goes down, ideally the service should fallback to the HornetQ running on server E which hosts A’s HornetQ slave. However, to resume as HornetQ master, the HornetQa_slave needs to talk to the JNDI process running on server A (I presume to replicate messages). Since the host A is itself down, the HornetQa_slave running on E has no way to talk to the JNDI on A, and thus, cannot resume as the master process.

Had the JNDI service been highly available, the slave HornetQ process could resume as master as expected. Could anyone kindly point to the docs or illustrate in simple steps how we could convert our existing setup to a HA-JNDI? For what it’s worth, I have read multiple sources, but it doesn’t seem to illustrate in much detail about how to get going with configuring a HA-JNDI. Please let me know if you need more info about our current setup.

Thanks


Get this bounty!!!

#StackBounty: #java #tomcat #cpu-usage #windows-server-2012-r2 #tomcat9 Standalone tomcat 9 spikes CPU to 50% every 10 seconds while my…

Bounty: 100

i am using Tomcat 9.0.0.M22 with jdk1.8.0_131 on windows server 2012 R2 and i have a sprinboot web application deployed on it, the issue is that every 10 seconds the commons daemon service runner spikes the cpu to 50% although my deployed web application is idle then decreases to 0% and this behavior continue to happen every 10 seconds.

in my application i don’t have any job that runs every 10 seconds, and also when i run my web application on tomcat from eclipse i didn’t notice the same behavior, so i am guessing that this is a tomcat built in thread, so i was wondering if any one has encountered this issue before can guide me to a solution.

please advise, thanks


Get this bounty!!!

#StackBounty: #javascript #java #android #firebase #firebase-cloud-messaging Firebase Cloud HTTP Message from Web

Bounty: 50

I have set up a webpage (home.html) that a user can sign into firebase using authentication. Once they authenticate, they are directed to a new page(test.html). Once they are here, I want to be able to send a notification or data message.

I am wondering if anyone can help me with the code to send a notification – any type of notification. I’ve been on this for 3 days and cannot send a notification from the web!! I can’t find any tutorials on this – only people using curls.

I have no idea how to handle the code below, which is supposed to be on how to send a notification to the devices subscribed to a topic. I am guessing that this is all JSON and needs to be put into a JSON object?

Please assume the Initialization is filled in, I removed all info – even though I think that information is supposed to be public.

enter image description here

Thanks for any info!

This is my service worker (so far): firebase-messaging.sw.js

  // Give the service worker access to Firebase Messaging.
  // Note that you can only use Firebase Messaging here, other Firebase libraries
  // are not available in the service worker.
  importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
  importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');  

  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

  const messaging = firebase.messaging();
  messaging.setBackgroundMessageHandler(function(payload){
    const title = "Hello World";
    const options = {
      body: payload.data.status
    };
    return self.registration.showNotification(title, options);
  });

This is the app.js file that goes to the test.html page

  // Initialize Firebase
  var config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
  firebase.initializeApp(config);

  // Retrieve Firebase Messaging object.
  const messaging = firebase.messaging();

  messaging.requestPermission()
  .then(function() {
    console.log('Notification permission granted.');
    return messaging.getToken();
  })
  .then(function(token){
    console.log(token);
  })
  .catch(function(err) {
    console.log('Unable to get permission to notify.', err);
  })

  messaging.onMessage(function(payload){
    console.log('onMessage:', payload);
  });

And the barebones test.html file

<!DOCTYPE html>

<html>
    <head>
        https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js
        https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js
    </head>
    <body> 
        /scripts/app.js
    </body>
</html>


Get this bounty!!!

#StackBounty: #java #spring How to load a properties file based on the server environment with spring so that the values can be injected?

Bounty: 50

To my surprise I have had a difficult time finding an answer to this question. I have Seen many examples where you can use @PropertySource to load a specific properties file for a class. I have also seen examples where you can easily add different property files in spring boot projects. But what I want to do is to do this for a spring project that is NOT spring boot and load a properties file so that the values of this file can be injected in classes annotated with @Component which is dependent on the server environment. So for example if I am on development server I want a particular properties file loaded and on production a different properties file. The reason that I am doing it like this is because my data and service layers are their own modules. These modules contain their own unit tests and can be imported as their own modules in other spring boot projects. I need properties files to be loaded to serve these modules which use spring but not spring boot. I have tried the following, but this does not work.

@Configuration
@Profile("test")
@EnableJpaRepositories("com.hi.repository")
@EnableTransactionManagement
@EnableScheduling
public class InfrastructureConfig  {
...
    @Bean
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        Map<String, String> env = System.getenv();
        String propertiesFile=null;

        String e = env.get("SERVER_ENV");

        if (e.equals("dev")) {
            propertiesFile = "environment/development.properties";
        } else if (e.equals("prod")) {
            propertiesFile = "environment/production.properties";
        }

        configurer.setLocation(new ClassPathResource(propertiesFile));


        return configurer;

    }

Then I have a test which looks like this

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/DealServiceTest-context.xml"})
@ActiveProfiles("test")
public class LogTest {

    private static final Logger log = LogManager.getLogger(LogTest.class);

    @Autowired
    PathsService pathsService;

    @Autowired
    Environment environment;


    @Test
    public void testBeans(){
        System.out.println("********** WASSUP from LogTest");
        System.out.println(environment.getProperty("imageBucket"));

    }

Although the test prints out null which indicates to me the properties file has not been loaded and prepared for its values to be injected. How can I achieve this?


Get this bounty!!!

#StackBounty: #java #xml #amazon-web-services #amazon-ec2 #aws-java-sdk Get EC2 Instance XML Description using AWS Java SDK?

Bounty: 150

We have a scenario in which we need to retrieve the description info for EC2 instances running on AWS. To accomplish this, we are using the AWS Java SDK. In 90% of our use case, the com.amazonaws.services.ec2.model.Instance class is exactly what we need. However, there is also a small use-case where it would be beneficial to get the raw XML describing the instance. That is, the XML data before it is converted into the Instance object. Is there any way to obtain both the Instance object and the XML string using the AWS Java SDK? Is there a way to manually convert from one to the other? Or, would we be forced to make a separate call using HttpClient or something similar to get the XML data?


Get this bounty!!!

#StackBounty: #java #multithreading #sqlite #javafx Managing threads accessing a database with Java

Bounty: 50

I am working on an app that accesses an SQLite database. The problem is the DB gets locked when there is a query to it. Most of the time this is not a problem because the flow of the app is quite linear.

However I have a very long calculation process which is triggered by the user. This process involves multiple calls to the database in between calculations.

I wanted the user to get some visual feedback so I have been using Javafx progressIndicator and a Service from the Javafx.Concurrency framework.
The problem is this leaves the user free to move around the app and potentially triggering other calls to the database.

This caused an exception that the database file is locked.
I would like a way to stop that thread from running when this case happens however I have not been able to find any clear examples online. Most of them are oversimplified and I would like a way which is scalable. I’ve tried using the cancel() method but this does not guarantee that the thread will be cancelled in time.

Because I am not able to check in all parts of the code for isCancelled sometimes there is a delay between the time the thread is canceled and the time it effectively stops.

So I thought of the following solution but I would like to know if there is a better way in terms of efficiency and avoiding race conditions and hanging.

    // Start service
    final CalculatorService calculatorService = new CalculatorService();

    // Register service with thread manager
    threadManager.registerService(CalculatorService);

    // Show the progress indicator only when the service is running
    progressIndicator.visibleProperty().bind(calculatorService.runningProperty());

calculatorService.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent workerStateEvent) {
            System.out.println("SUCCEEDED");
            calculatorService.setStopped(true);
        }
    });

    // If something goes wrong display message
    calculatorService.setOnFailed(new EventHandler<WorkerStateEvent>() {
        @Override
        public void handle(WorkerStateEvent workerStateEvent) {
            System.out.println("FAILED");
            calculatorService.setStopped(true);
        }
    });

    // Restart the service
    calculatorService.restart(); 

This is my service class which I have subclassed to include methods that can be used to set the state of the service (stopped or not stopped)

    public class CalculatorService extends Service implements CustomService {
    private AtomicBoolean stopped;
    private CalculatorService serviceInstance;

    public FindBundleService() {
        stopped = new AtomicBoolean(false);
        instance = this;
    }

    @Override
    protected Task<Results> createTask() {
        return new Task<Result>() {

            @Override
            protected Result call() throws Exception {
                try {
                    Result = calculationMethod(this, serviceInstance);
                    return Result;
                } catch (Exception ex) {
                    // If the thread is interrupted return
                    setStopped(true);
                    return null;
                }
            }
        };
    }

    @Override
    public boolean isStopped() {
        return stopped.get();
    }

    @Override
    public void setStopped(boolean stopped) {
        this.stopped.set(stopped);
    }
}

The service implements this interface which I defined

public interface CustomService {

    /**
     * Method to check if a service has been stopped
     * 
     * @return
     */
    public boolean isStopped();

    /**
     * Method to set a service as stopped
     * 
     * @param stopped
     */
    public void setStopped(boolean stopped);

}

All services must register themselves with the thread manager which is a singleton class.

public class ThreadManager {

    private ArrayList<CustomService> services;

    /**
     * Constructor
     */
    public ThreadManager() {
        services = new ArrayList<CustomService>();
    }

    /**
     * Method to cancel running services
     */
    public boolean cancelServices() {
        for(CustomService service : services) {
            if(service.isRunning()) {
                ((Service) service).cancel();
                while(!service.isStopped()) {
                    // Wait for it to stop
                }
            }
        }
        return true;
    }


    /**
     * Method to register a service
     */
    public void registerService(CustomService service) {
        services.add(service);
    }

    /**
     * Method to remove a service
     */
    public void removeService(CustomService service) {
        services.remove(service);
    }

}

In any place in the app if we want to stop the service we call cancelServices(). This will set the state to cancelled I’m checking for this in my calculationMethod() then setting the state to stopped just before returning (effectively ending the thread).

if(task.isCancelled()) {
        service.setStopped(true);
        return null;
}


Get this bounty!!!

#StackBounty: #java #android #annotations #dependencies #gson Use Gson in my generated classes (annotation processor)

Bounty: 50

I’m developing a library to generate classes using annotations and processors. The generated classes should use Gson library from google.

My question is : Where should I add the Gson dependency ? I’m currently adding it into the processor build.gradle but when the classes are generated, Gson is not found and Android Studio is suggesting to add it to the app module.

Also, I pushed a first version of the library to bintray before I noticed this problem (because I was already using Gson in my app module, so the error didn’t show up). When I included my library to another project, used the annotation and build the project, I got this message :

Error:Bad service configuration file, or exception thrown while
constructing Processor object: javax.annotation.processing.Processor:
Provider me.aflak.filter_processor.FilterProcessor could not be
instantiated: java.lang.NoClassDefFoundError:
com/squareup/javapoet/TypeName

Is it related to the way I add my dependencies ? Obviously I’m missing something…

This is the processor build.gradle :

apply plugin: 'java-library'

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':filter-annotation')

    implementation 'com.squareup:javapoet:1.9.0'
    implementation 'com.google.code.gson:gson:2.8.1'
    implementation 'com.google.auto.service:auto-service:1.0-rc3'
}

// bintray stuff here...

This is my app.module dependency :

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    implementation project(':filter-annotation')
    annotationProcessor project(':filter-processor')
}

Any help would be greatly appreciated, thanks!


Get this bounty!!!

#StackBounty: #java #servlets #swagger #resteasy #swagger-2.0 serve swagger.json from resource class

Bounty: 250

I user swagger for documenting endpoints of a resteasy API, and I serve the swagger.json description using a servlet with a method like this:

public void init(ServletConfig config) throws ServletException
    {
        super.init(config);
        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setHost("localhost:8080");       
        beanConfig.setBasePath("/api");
        beanConfig.setResourcePackage("my.rest.resources");
        beanConfig.setScan(true);       
    }

and I can access the swagger.json at localhost:8080/api/swagger.json.
However, my collaborators would like to avoid extra servlets other than the resteasy servlet, and I wonder if I can serve the swagger generated json from a method from a resource class, something like this:

    @GET
    @Path("/myswagger")
    @Produces("application/json")
    public String myswagger(@Context UriInfo uriInfo) 
    {
        Swagger swagger = new Swagger();
        // Do something to retrieve the Swagger Json as a string
        // ... 
        return(swaggerJsonString);
    }

and then access the swagger generated json via localhost:8080/api/myswagger. Is this possible?


Get this bounty!!!