#StackBounty: #java #rhel7 #openjdk-11 InetAddress.getLocalHost().getHostName() different behavior between JDK 11 and JDK 8

Bounty: 500

I wrote a simple java program to basically run:

System.out.println(InetAddress.getLocalHost().getHostName());

If I compile it and run it on Java 1.7.231 ir 1,8,221 On RHEL 7.7, it returns the FQDN (computer.domain.com), but ON THE SAME SERVER, compile it in RHEL JDK 11.0.2 it returns only the server name.

As I understand it should do a reverse DNS lookup (basically a hostname -f) but with JDK 11 the behavior is definitely different. Any idea why is this happening?


Get this bounty!!!

#StackBounty: #java #javafx #jar JavaFX .JAR file won't run on ubuntu 20.04 from terminal

Bounty: 50

I’m trying to build my javafx program into a .jar file. The program runs fine when i’m running it from intelliJ but won’t run from .jar file. I’m using intelliJ with java11 and javafx version 11. I followed all the instructions correctly to build the project into a .jar file but when i run my program i get some strange error (see below). I also checked javafx library in the .jar file and it’s there so i don’t know why i’m getting this error.

edit: I tried both on Windows and ubuntu but was still getting the error. I used to intelliJ to create the jar file using artefact feature. I made sure to attach javafx (external library) when building the artifact.

[Main.java]

package app;

import javafx.fxml.FXMLLoader;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import java.util.Objects;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("ui/index.fxml")));
        primaryStage.getIcons().add(new Image(Objects.requireNonNull(getClass().getResourceAsStream("data/NUIMLogoIcon.png"))));
        primaryStage.setScene(new Scene(root, 740, 600));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

[Launcher.java]

import app.Main;

public class Launcher {
    public static void main(String[] args) {
        Main.main(args);
    }
}

[index.fxml]

<ScrollPane focusTraversable="false"
            hbarPolicy="NEVER"
            maxHeight="-Infinity"
            maxWidth="720.0"
            minHeight="-Infinity"
            minWidth="-Infinity"
            prefHeight="1383.0"
            prefWidth="720.0"
            xmlns="http://javafx.com/javafx/11"
            xmlns:fx="http://javafx.com/fxml/1"
            fx:controller="app.ui.Controller"><!--   LINE 40-->
  <content>
    <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="1374.0" prefWidth="720.0">
         <children>
         

[ERROR]

ninja@ninja-lat5410:~/Desktop/MULECodeLab/out/artifacts/MULECodeLab_jar$ java -jar MULECodeLab.jar 
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: javafx.fxml.LoadException: 
file:/home/ninja/Desktop/MULECodeLab/out/artifacts/MULECodeLab_jar/MULECodeLab.jar!/app/ui/index.fxml:40

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2603)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3237)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3194)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3163)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3136)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3113)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:3106)
    at app.Main.start(Main.java:15)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
    at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
    at com.sun.glass.ui.gtk.GtkApplication.lambda$runLoop$11(GtkApplication.java:277)

[Controller]

Controller.java

[Project repo]
Github Repo


Get this bounty!!!

#StackBounty: #java #spring-boot #spring-data-rest Spring Data Rest with @Version from Parent-Entity

Bounty: 250

I set up a @Repository for an Entity with a @Version property and published it via @RepositoryRestResource which was pretty straight forward. The version is transfered to the and from the client in the Http Header as an ETag and it works perfectly.

In my current scenario I have a child Entity which doesn’t have a @Version-Tag itself, instead the @Version-Tag of its parent has to be used. That means, that every change of the child or the parent has to increment the parent version. Also the operation should fail, if the parent version is outdated. For this case EntityManager offers the LockModeType.OPTIMISTIC_FORCE_INCREMENT.

How do I customize Spring Data Rest to implement such behavior? Do I have to implement a @RestController from scratch?

—————– edit —————-

Here is a small example i set up which works for a simple entity

Application.java

@SpringBootApplication
public class Application
{
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class, args);
    }

    @Configuration
    @EnableJpaRepositories
    public static class ServerConfiguration
    {
        private EntityManagerFactory emf;
    
        @Bean
        public EntityManagerFactory entityManagerFactory()
        {
            if (emf == null)
            {
                Map<String, Object> properties = new HashMap<>();
                properties.put(AvailableSettings.CLASSLOADERS, Collections.singleton(Thread.currentThread().getContextClassLoader()));
                emf =  Persistence.createEntityManagerFactory("test", properties);
            }
            return emf;
        }

        @Bean
        public PlatformTransactionManager transactionManager()
        {
            JpaTransactionManager transactionManager = new JpaTransactionManager(entityManagerFactory());
            return transactionManager;
        }
    
        @Bean
        public ShallowEtagHeaderFilter shallowEtagHeaderFilter() 
        {
            return new ShallowEtagHeaderFilter();
        }
    }
}

SimpleRepository.java

@Repository
@RepositoryRestResource(collectionResourceRel = "simples", path = "simples")
public interface SimpleRepository  extends JpaRepository<Simple, Long>
{
}

Simple.java

@Data
@NoArgsConstructor
@Entity
@Table(name = "SIMPLE")
public class Simple
{
    @JsonCreator
    public Simple(@JsonProperty("changeable") String changeable)
    {
        this.changeable = changeable;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID")
    @SequenceGenerator(name = "ID", sequenceName = "ID", allocationSize = 1)
    @Column(name = "ID")
    private Long id;
    
    @Version
    @Column(name = "VERSION")
    private int version;
    
    @Column(name = "CHANGEABLE")
    private String changeable;
}

It works perfectly with just these three classes, I can interact with the exposed JPA repository via postman, the version number is shipped in the http header as an ETag.

Now I want to extend it for a parent-child-relationship where the version is only incremented in the parent entity.

Parent.java

@Data
@NoArgsConstructor
@Entity
@Table(name = "PARENT")
public class Parent
{
    @JsonCreator
    public Parent(@JsonProperty("changeable") String changeable)
    {
        this.changeable = changeable;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PARENT_ID")
    @SequenceGenerator(name = "PARENT_ID", sequenceName = "PARENT_ID", allocationSize = 1)
    @Column(name = "PARENT_ID")
    private Long id;
    
    @Version
    @Column(name = "VERSION")
    private int version;
    
    @OneToMany(mappedBy = "parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Collection<Child> children = new LinkedHashSet<>();
    
    @Column(name = "CHANGEABLE")
    private String changeable;
}

Child.java

@Data
@NoArgsConstructor
@Entity
@Table(name = "CHILD")
public class Child
{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "CHILD_ID")
    @SequenceGenerator(name = "CHILD_ID", sequenceName = "CHILD_ID", allocationSize = 1)
    @Column(name = "CHILD_ID")
    private Long id;
    
//  NO VERSION! Parent version should be incremented on change  
//  @Version
//  @Column(name = "VERSION")
//  private int version;
    
    @ManyToOne(optional = false)
    @JoinColumn(name = "PARENT_ID", referencedColumnName = "PARENT_ID")
    private Parent parent;
    
    @Column(name = "CHANGEABLE")
    private String changeable;
}

You can find the full example on http://github.com/Meini777/example

What is the best way to implement it? I could code a @RestController on my own instead of using the implicit one from @RepositoryRestResource, but in this case i have implement all the behavior including HATEOAS and ALPS.


Get this bounty!!!

#StackBounty: #java #android Querying Android ContentResolver for gallery files and determining image vs video

Bounty: 100

I’m trying to make a simple Android app for my own phone that looks at my Gallery, and for each image/video file:

  • creates a Bitmap thumbnail of the file
  • records the file’s absolute path on the phone

Essentially, I’ll have the following data model:

public class MediaFileModel {

  private Bitmap thumbnail;
  private String absPath;

  // ctor, getters and setters omitted for brevity
  
}

And I need something that looks at all the files in my Gallery and yields a List<MediaFileModel>. My best attempt is here:

public List<MediaFileModel> getAllGalleryMedia() {

  String[] projection = { MediaStore.MediaColumns.DATA };
  List<MediaFileModel> galleryMedia = new ArrayList<>();
  Cursor cursor = getActivity().getContentResolver().query(
    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
    projection,
    null,
    null,
    null);

  // I believe here I'm iterating over all the gallery files (???)
  while(cursor.moveToNext()) {
    MediaFileModel next = new MediaFileModel();

    // is this how I get the abs path of the current file?!?
    String absPath = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));

    Bitmap thumbnail = null;
    if (true /* ??? cursor is pointing to a media file that is an image/photo ??? */) {
      thumbnail = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(absPath), 64, 64);
    } else {
      // else we have a video (I assume???)
      thumbnail = ThumbnailUtils.createVideoThumbnail(absPath, MediaStore.Images.Thumbnails.MINI_KIND);
    }

    next.setThumbnail(thumbnail);
    next.setAbsPath(absPath);

    galleryMedia.add(next);
    
  }

  return galleryMedia;
  
}

However I’m not sure if my media query is setup correctly and I’m definitely not sure how to determine whether the file is an image/photo of a video, which I (believe I) need so that I can use the correct method for obtaining the thumbnail Bitmap.

Can anyone help nudge me over the finish line here?


Get this bounty!!!

#StackBounty: #java #javafx #tablet #multi-touch JavaFX no TouchEvents

Bounty: 200

On my (Windows) Surface Go 2 tablet I’m not able to retrieve any (multitouch) TouchEvents. I tried it with several Java/FX versions. Also with JavaFX 17 no TouchEvents events are generated only mouse events. Is there some sort of configuration parameter needed?

package fx;

import javafx.application.Application;
import javafx.collections.ListChangeListener;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TouchEvent;
import javafx.scene.layout.Pane;
import javafx.stage.PopupWindow;
import javafx.stage.Stage;
import javafx.stage.Window;

public class test {

    public static void main(String[] args) {
        Application.launch(JFXApp.class, args);
    }

    public static class JFXApp extends Application implements ListChangeListener<Window> {

        @Override
        public void start(Stage primaryStage) {
//            primaryStage.addEventFilter(TouchEvent.ANY, e -> System.out.println("touch event: " + e.getEventType()));
//            primaryStage.addEventFilter(MouseEvent.ANY, e -> System.out.println("mouse event: " + e.getEventType()));
            final ComboBox<String> comboBox = new ComboBox<>();
            comboBox.getItems().addAll("Test1", "Test2", "Test3");
            Scene scene = new Scene(new Pane(comboBox));
            scene.addEventFilter(TouchEvent.ANY, e -> System.out.println("scene touch event: " + e.getEventType()));
            scene.addEventFilter(MouseEvent.ANY, e -> System.out.println("scene mouse event: " + e.getEventType()));
            primaryStage.setScene(scene);
            primaryStage.setWidth(800);
            primaryStage.setHeight(800);
            primaryStage.show();
            Window.getWindows().addListener(this);
        }

        @Override
        public void onChanged(Change<? extends Window> c) {
            if (!c.next()) return;
            for (Window w : c.getAddedSubList()) {
                if (w instanceof PopupWindow) {
                    w.addEventFilter(TouchEvent.ANY,
                            e -> System.out.println("touch event (PopupWindow): " + e.getEventType()));
                    w.addEventFilter(MouseEvent.ANY,
                            e -> System.out.println("mouse event (PopupWindow): " + e.getEventType()));
                    Window.getWindows().removeListener(this);
                }
            }
        }
    }
}


Get this bounty!!!

#StackBounty: #java #android #flutter #android-studio Flutter doctor results with "cmdline-tools component is missing"

Bounty: 50

I have tried the answers at here & here to no avail.

After installing Android Studio & Flutter on Windows 10, when I run flutter doctor, I get the following:

[√] Flutter (Channel stable, 2.5.0, on Microsoft Windows [Version 10.0.19043.1202], locale en-US)
[X] Android toolchain - develop for Android devices
    X cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
[√] Chrome - develop for the web
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.60.0)
[√] Connected device (2 available)

Opening Android Studio > SDK Manager > Android SDK > SDK Tools uninstalling and re-installing Android SDK Command-line Tools (latest) has no effect.

I have also added <pathToSDK>toolsbin, <pathToSDK>platform-tools, and <pathToSDK>cmdline-toolslatestbin to the user PATH environment variables.

Following the flutter instructions and running <pathToSDKManager> --install "cmdline-tools;latest" (Which for me is located in <pathToSDK>cmdline-toolslatestbin) results with:

ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.

Please set the JAVA_HOME variable in your environment to match the
location of your Java installation.

I haven’t been able to find any documentation on this other than that I need to install some version on Java and add it to my path. The https://flutter.dev/docs/get-started/install/windows page mentions "Make sure that you have a version of Java 8 installed and that your JAVA_HOME environment variable is set to the JDK’s folder." and then states "Android Studio versions 2.2 and higher come with a JDK, so this should already be done." but doesn’t elaborate further.

Opening Android Studio and going to File > Project Structure > Project > Project SDK I can see that Android Studio already recognized several versions of Java installed:

enter image description here


Get this bounty!!!

#StackBounty: #java #jdbc #apache-camel How to safely generate SQL for Camel JDBC Component

Bounty: 50

I’m trying to make an insert with JDBC, and I’m looking at this example in the Camel docs: https://camel.apache.org/components/latest/jdbc-component.html#_using_named_parameters

But

.setBody("select * from projects where license = :?lic and id > :?min order by id")

Doesn’t compile.

The method setBody(Expression) in the type
ProcessorDefinition is not applicable for the
arguments (String)

You need to use simple() to shove a string into setBody(), but when I try that, the name parameters don’t work. We hit the ":" and it fails at runtime.

Am I misunderstanding how to specify these name parameters or is the doc wrong? How do we safely build an sql statement in Camel?


Get this bounty!!!

#StackBounty: #java #spring #spring-boot #mocking #integration-testing Spring Boot Integration Testing – Mocking @Service before Applic…

Bounty: 50

I have to create a integration test for a microservice X which downloads, processes and importing csv files from external sftp servers. The whole process is started by a spring boot scheduler task which starts a spring batch job for processing and importing the data. The import process is done by the spring batch writer, which is a restTemplate Repository (so it calls post requests to another microservice Y).

I already managed to mock the sftp server, putting a test file on it and the current integration test is downloading the file. (https://github.com/stefanbirkner/fake-sftp-server-rule/)

My problem is, that the task will be scheduled immediately when the application context starts so there is no trigger like a api call. To get the whole integration test working i have to mock the part where the external microservice Y is called through a restTemplate call. This repository is called in the spring batch writer and this repository is created by a repositoryFactory which is a @Service. The repositoryFactory is injected in the spring batch configuration class.

I already tried to use the @MockBean annotation in the test class as well as in a separate test configuration where i am mocking the create() function of the factory to deliver a repository mock. But at some point it does not work and it delivers still the original object which leads to interupt the import job.

I also tried to use the WireMock library, but also in this case it does not catched any api calls and at some point leads to interrupt the sftp socket. (?)

I hope someone could help me out.

The current test:

@NoArgsConstructor
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = {JsonHalConfig.class})
@TestPropertySource(locations = "classpath:application-test.properties")
@TestMethodOrder(MethodOrderer.MethodName.class)
public class ImportIT {

    @ClassRule
    public static final FakeSftpServerRule sftpServer = new FakeSftpServerRule();
    private static final String PASSWORD = "password";
    private static final String USER = "username";
    private static final int PORT = 14022;

    @BeforeClass
    public static void beforeClass() throws IOException {
        URL resource = getTestResource();
        if (resource != null) {
            sftpServer.setPort(PORT).addUser(USER, PASSWORD);
            sftpServer.createDirectories("/home/username/it-space/IMPORT", "/home/username/it-space/EXPORT");
            sftpServer.putFile("/home/username/it-space/IMPORT/INBOX/testFile.csv",
                    resource.openStream());
        } else {
            throw new IOException("Failed to get test resources");
        }
    }

    private static URL getTestResource() {
        return ImportIT.class.getClassLoader().getResource("testFile.csv");
    }

    @Test
    public void test_A_() throws IOException, RepositoryException {
        assertTrue(true);
    }
}

I tried following configuration classes

(included in @ContextConfiguration)

@Configuration/@TestConfiguration
public class RepositoryTestConfig {
    @Bean
    @Primary
    public IRepositoryFactory repositoryFactory() {
        IRepositoryFactory repositoryFactory = mock(IRepositoryFactory.class);
        IRepository repository = mock(IRepository.class);
        when(repositoryFactory.create(anyString())).thenReturn(repository);
        return repositoryFactory;
    }
}

(as static class in the test class)

    @TestConfiguration/@Configuration
    public static class RepositoryTestConfig {
        @MockBean
        private IRepositoryFactory repositoryFactory;

        @PostConstruct
        public void initMock(){
            IRepository repository = mock(IRepository.class);
            Mockito.when(repositoryFactory.create(anyString())).thenReturn(
                    repository
            );
        }
    }

UPDATE 27.08.2021
I have a RestConfig @Component where a new RestTemplateBuilder is created. I tried to @MockBean this component to deliver a RestTemplateBuilder Mock and injected a MockRestServiceServer object to catch outgoing api calls. But unfortunately it does not work as aspected. Am i missing something? I also tried to create a "TestRestController" to trigger the scheduling of the task but it never delivers the mock…


Get this bounty!!!

#StackBounty: #java #spring #spring-boot #spring-security #spring-security-oauth2 Lazy initialise spring security at runtime + reload s…

Bounty: 50

Spring usually eagerly loading the spring security configuration while starting the application. I’m using OAuth with Spring Security

I’m maintaining a configuration table for storing the SSO related values (like jwk-url, client_id, client_secret). This values will be populated by an admin user via CRUD in the same spring boot application.

Then only the jwk-url is available to be configure in the Spring security configuration (refer below code - jwkSetUri(...)). This would not available at the application startup.

So I wanted to initialise the spring security configuration after the value is loaded into the table, like a lazy loading (@Lazy) at runtime. I know how to do Lazy loading of a regular class/service.

  1. But still I’m not sure how to invoke the configure(HttpSecurity http) method at runtime and how to p
    ass the HttpSecurity parameter. When I just try invoke new ResourceServerConfiguration() like a lazy loading at runtime, I don’t see the configure() method is called. (Or) this class needs to be maintained as bean and lazy load whenever needed. But still not sure about how to call configure() in code.
  2. Another thing is how to refresh/reload the spring security configuration at runtime, if the JWK url is changed by admin. Then only the spring security configuration can take effect of the changes.
@Configuration
@EnableWebSecurity
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter {
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.cors()
                .and()
                .csrf().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2ResourceServer()
                .authenticationEntryPoint(oAuth2AuthenticationEntryPoint)
                .accessDeniedHandler(oAuth2AccessDeniedHandler)
                .jwt()
                 // Some Auth server URL which would be fetch from table
                .jwkSetUri(ssoConfigService.getActiveSSOCertificateURL()); 
                 // Eg. http://localhost:8090/auth/realms/demo-app/protocol/openid-connect/certs
    }
}

I have already referred these links. But it doesn’t help for my purpose. Any help would be appreciated.

How do I lazy load Spring Security?

How to reload the Configure method of WebSecurityConfigurerAdapter when the application is up and running

Modify Spring Security Config at Runtime

Configure Spring HTTP Security at Runtime


Get this bounty!!!