Code Bug Fix: How to use SynthLookAndFeel in a modular java application?

Original Source Link

I’m trying to use the SynthLookAndFeel class but cannot make it work in my modular application.

I went back to basics with the official Synth Application sample from the Java Tutorial page on The Synth Look And Feel, and just added a module-info.java file with the following contents:

module SynthApplication {
    requires java.desktop;
}

It builds OK, but when run, the console shows a NullPointerException stack trace pointing to java.desktop/sun.awt.SunToolkit.getImageFromHash(SunToolkit.java:653), and only a blank window is displayed.

The issue seems to lie in the resolution of the images (e.g. images/button.png) that are referenced in the buttonSkin.xml definition of the L&F: Image paths are converted to a pseudo-package name (lookandfeel.images) which is not exported to the java.desktop module.

I tried to add exports lookandfeel; to module-info.java => same error

I tried to add exports lookandfeel.images; to module-info.java => build error Error:(4, 24) java: package is empty or does not exist: lookandfeel.images

Is there a way to make the image resolution work or is SynthLookAndFeel purely incompatible with java modules ?

Thanks. Vicne.

Note: I’m using openJdk 14

OK, after more code digging in the JDK, I discovered that it tested if the module was “open” (aka open to introspection). So I tried to declare the module as “open” as follows:

open module SynthApplication {
    requires java.desktop;
}

And woo-hoo it worked.

OK, learned something: SynthLookAndFeel must be part of an open module to work.

Hope it can help others.

Tagged : / / / /

Code Bug Fix: Problem with rest api paths in Tomcat using springboot App

Original Source Link

I cant get to the rest apis path when deploying in tomcat. I can access my rest api when it’s local. but when I deploy my .war to tomcat it seems there is some configuration I should do. my app doesn’t have UI i’m just using swagger docs to try out my Rest APi

@RestController
@RequestMapping("/email") 
public class EmailController {

private final NotificationEmail email;

@Autowired
public EmailController(NotificationEmail email) {
    this.email = email;
}

@ApiOperation(value = "Send new Email")
@PostMapping(value = "")
public ResponseEntity<Status> sendEmail(@RequestBody NotifyRequest notifyRequest) throws UnknownException {
    this.email.sendEmail(notifyRequest);
    return new ResponseEntity<>(HttpStatus.OK);
}

Output

@RestController   //for spring to know the type of class it is
@RequestMapping("/email") 
public class EmailController {

private final NotificationEmail email;

@Autowired
public EmailController(NotificationEmail email) {
    this.email = email;
}

@ApiOperation(value = "Send new Email")
@PostMapping(value = "")
public ResponseEntity<Status> sendEmail(@RequestBody NotifyRequest notifyRequest) throws UnknownException {
    this.email.sendEmail(notifyRequest);
    return new ResponseEntity<>(HttpStatus.OK);
}

I guess you were missing, @RestController annotation, please try and let me know if above code works.

The problem was that the war file was not running and I got confused because the embedded swagger page was running even though the app wasn’t.

Tagged : / /

Code Bug Fix: Game Board with Java GUI Swing

Original Source Link

I try to do a game like scrabble with Java GUI. The game board should show like enter image description here. The user enters x-y inputs and the width of the board field is NxN. The user enters the number of colored squares and the colored squares are randomly distributed to the board. User should select squares and give entry on squares. Do you have any advice on which class to use for board?

Yes, I have advice: Don’t start with the GUI first. Build a game model that has all of the Scrabble logic: putting pieces down, add points to scores etc. Do this first, test it, make sure it works, then build a GUI around it.

… But to answer your question: If I was doing this, I’d just use a JPanel and draw the board / handle UI in one place.

Tagged : /

Code Bug Fix: how can i get single value from recylerview

Original Source Link

i have passed data from recyclerview adapter to main activity and then into other activity on click on image of recyclerview.
now i am getting multiple value from it and i just want single URL
here is the code of adapter

public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        Datum datum = datums.get(position);

        Glide.with(context).load(datums.get(position).getThumbnail()).into(holder.thumbnail);

        holder.title.setText(datum.getTitle());
        holder.artist.setText(datum.getArtist());
        holder.duration.setText(Integer.toString(datum.getDuration()));

        //imageview interface pass
        holder.thumbnail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onImageClickListener.onImageClick(datum.getUrl());
                onImageClickListener.onImageClick(datum.getThumbnail());
            }
        });
    }

onclick event in main recylerview main activity

 public void onImageClick(String imageData ) {

        Intent i = new Intent(MainActivity.this,exoplayer.class);
        i.putExtra("image", imageData);
        i.putExtra("url", imageData);
        startActivity(i);

    }

and here is the code of other activity

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exoplayer);

        thumb = findViewById(R.id.thumb);
        link = findViewById(R.id.link);

        String image = getIntent().getStringExtra("image");
        String url = getIntent().getStringExtra("url");


        link.setText(url);
        Glide.with(this).asBitmap().load(image).into(thumb);

    }

here are the screenshots of output

first output

enter image description here

i just want that bigger url i do not need other url which url of thumbnail.

Okay from what I tried to understand, is that the url is passed twice and you want it to be passed once:

Well if that is the case:

Update the method in the onImageClickListener interface:

 //make the method accept two parameters

 public void onImageClick(String imageData , String urlData);

Next update the method implemented in MainActivity:

 public void onImageClick(String imageData , String urlData) {

        Intent i = new Intent(MainActivity.this,exoplayer.class);
        i.putExtra("image", imageData);
        i.putExtra("url", urlData);
        startActivity(i);

    }

Finally when you click in the RecyclerView item, do this:

    //imageview interface pass
    holder.thumbnail.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onImageClickListener.onImageClick(datum.getThumbnail() , datum.getUrl());
        }
    });

Tagged : / /

Code Bug Fix: Scatter/Gather with timeout in RxJava

Original Source Link

I’m trying to use RxJava and AsyncHttpClient to call multiple web services in parallel and then process the results of each one. I need to limit the amount of time spent waiting for the services to return. The constraint I’m having trouble with is how to deal with the services that don’t finish in time. I’ve limited the network time in the AsyncHttpRequest itself, and in the Single.Merge() with take(), but how do I determine which Single did not return because they did not complete before the take() expired? Here is some code:

public List<Single<MyResponse>> fetchS(List<MyRequest> requestlist, final AsyncHttpClient ahc) {
        List<Single<MyResponse>> ret =
            requestlist.stream().map(req -> Single.fromCompletionStage(convert(req, ahc))).collect(
                Collectors.toList());
        return ret;
    }

var responsesS = new FetcherImpl().fetchS(requests, ahc);

Single<List<MyResponse>> merged =
           Single.merge(responsesS).take(500,TimeUnit.MILLISECONDS).toList();

merged.subscribeOn(Schedulers.computation()).subscribe( list -> { process(list);}) 

Basically, how do I deal with the items that did not finish in the 500ms time limit of take()?

TIA

This is how I would do it:

class MyResponse {
            String reponse;
            Throwable error;
        }

        List<Single<MyOriginalResponse>> singles =
                new ArrayList(Single.defer(() -> Single.just(new MyOriginalResponse()))
                        .timeout(500, TimeUnit.MILLISECONDS)
                        .map(myResponse -> new MyResponse(myResponse))
                        .onErrorReturn(throwable -> MyResponse(throwable)));

Basically you have a wrapper class that contains either a response or a throwable. There are solutions out there like https://github.com/eleventigers/rxeither that would give you a Either<Throwable, MyOriginalResponse> and then from there you can continue your flow depending on what you get.

Hope it helps

Tagged : / /

Code Bug Fix: Why am i getting groupingBy method error?

Original Source Link

So im reading OCP book there is a code that looks like this, and I’m typing all of this not needed info cause the stackoverflow says my post is mostly a code. and here i thought this a stackoverflow.
So the question
When I’m typing this code

Stream<String> ohMy = Stream.of("lions", "tigers", "bears");
Map<Integer, Optional<Character>> map = ohMy.collect(
    groupingBy(
        String::length,
        mapping(s -> s.charAt(0),
            minBy(Comparator.naturalOrder()))));
System.out.println(map); // {5=Optional[b], 6=Optional[t]}

I’m getting an error

Error:(25, 27) java: no suitable method found for groupingBy(String::length,java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Optional<T>>)
    method java.util.stream.Collectors.<T,K>groupingBy(java.util.function.Function<? super T,? extends K>) is not applicable
      (cannot infer type-variable(s) T,K
        (actual and formal argument lists differ in length))
    method java.util.stream.Collectors.<T,K,A,D>groupingBy(java.util.function.Function<? super T,? extends K>,java.util.stream.Collector<? super T,A,D>) is not applicable
      (inferred type does not conform to upper bound(s)
        inferred: java.lang.Object
        upper bound(s): T,java.lang.Comparable<? super T>,java.lang.Object)
    method java.util.stream.Collectors.<T,K,D,A,M>groupingBy(java.util.function.Function<? super T,? extends K>,java.util.function.Supplier<M>,java.util.stream.Collector<? super T,A,D>) is not applicable
      (cannot infer type-variable(s) T,K,D,A,M
        (actual and formal argument lists differ in length))

Cannot figure it out

Looks like it’s a problem connected to Intellij distribution.

See link to issue tracker:
https://youtrack.jetbrains.com/issue/IDEA-212740

To make it work from Intellij you need to specify Comparator type witness:

Stream<String> ohMy = Stream.of("lions", "tigers", "bears");
Map<Integer, Optional<Character>> map = ohMy
        .collect(
                groupingBy(
                        String::length, 
                        mapping(s -> s.charAt(0), minBy(Comparator.<Character>naturalOrder()))
                )
        );
System.out.println(map);

Tagged : /

Code Bug Fix: Using linked lists with boolean methods

Original Source Link

I need to create a PhoneBook using a linked list that contains multiple boolean methods.One of those is insert that is susposed to enter a new Person in the PhoneBook, if the Person already exists the method phonebook shouldnt change.I am having trouble implementing this method, particullarly at the part where I’m supposed to compare the name the user inputs, with the one that is already in the phonebook.This is my code

class PhoneBookList implements PhoneBook {
    private int size = 0;
    Node head;

    private static final class Node {
        final Person person;
        Node next;

        Node(Person person) {
            this.person = person;
        }
    }

    public boolean insert(Person person) {
        Node n = new Node(person); 
        Node p = head,prev = null;


        if(p == null) {
            head = n;
            size++;
            return true;
        }

        int comparison = p.name.compareTo(n.name);

        if(comparison < 0) {
            n.next = p;
            p = n;
            size++;// 
            return true;
        }

        if(comparison == 0) {
            return false;

        }

        Node current = p;
        while(current.next !=null && current.next.person < person) {
            current = current.next;
        }
        if(current.next !=null && current.next.person == person) {
            return false;

        }

        n.next = current.next;
    current.next = n;
        size++;
    return true;
    }
}

We have to explicitly use this compareTo method,and I cannot get it to work.Any guidance.Here are the errors:

PhoneBookList.java:25: error: cannot find symbol
                int comparison = p.name.compareTo(n.name);
                                                   ^
  symbol:   variable name
  location: variable n of type Node
PhoneBookList.java:25: error: cannot find symbol
                int comparison = p.name.compareTo(n.name);
                                  ^
  symbol:   variable name
  location: variable p of type Node
PhoneBookList.java:40: error: bad operand types for binary operator '<'
                while(current.next !=null && current.next.person < person) {
                                                                 ^
  first type:  Person
  second type: Person
                                                                 ^
  first type:  Person
  second type: Person

Thank you!

To check if person already exist in the list you need to loop through all the nodes in your list and comapre each person name in node with the name of the person you want to insert.

class PhoneBookList implements PhoneBook {
    private int size = 0;
    Node head = null;

    private static final class Node {
        final Person person;
        Node next;

        Node(Person person) {
            this.person = person;
        }
    }

    public boolean insert(Person person) {
        Node n = new Node(person); 
        Node p = head;

        if(p == null) {
            head = n;
            size++;
            return true;
        } else {

            Node temp = p;
            int comparison;
            while(temp.next != null) {
                comparison = temp.person.name.compareTo(person.name);
                if(comparison == 0){
                    return false;
                }
                temp = temp.next;
            }
            temp.next = n;
            size++;
            return true;
        }

    }
}

Some comments on your code:

  1. It has some if’s that should not be there, since they do not treat special cases.
  2. It uses am operator of comparison for the class Person that, if you really have implemented, then there has no sense to use the compareTo method.
  3. I leave you a new version much more concise, that only creates the new object when necessary.

If you have not implemented the comparison operator, then you should change a < b by a.name.compareTo(b.name) < 0.

class PhoneBookList implements PhoneBook {
    private int size = 0;
    Node head;

    private static final class Node {
        final Person person;
        Node next;

        Node(Person person) {
           this.person = person;
       }
    }

    public boolean insert(Person person) {
        Node p = head;
        while (p != null) {
            if (p.person > person) break;
            p = p.next;
        }
        if (p.person == person) return false;
        Node n = new Node(person);
        if (p != null) n.next = p.next;
        p.next = n;
        return true;
    }

Hope this helps.

So you do not have the comparison operator implemented. Then for helping you, I must know the Person class implementation. There, you have to put you operator.

Tagged :

Code Bug Fix: How to detect when user’s done entering the value to EditText in RecyclerView?

Original Source Link

enter image description here

I have a recyclerview which contains EditTexts. How can I get the value of each edittext only after the user is done from entering the amount in any of the edit texts so i can update the total amount.

What I’m trying to achieve is adding the values of the edittexts and send it to the Activity. In the Activity I have the Proceed button (where i will perform some validations on the total amount) and a total amount TextView (retrieved from the recyclerview adapter using a listener).

I tried to use setOnEditorActionListener but this will not help if the user clicked on back button instead of hitting the enter.

Also, I tried to use the focus change listener but the problem is that the EditText never loses focus even when clicking outside in the page.

And of course, the TextWatcher is not an ideal solution as it could be very expensive in OnBindViewHolder.

I need to ensure that whenever the user clicks on Proceed Button, the total amount is updated before.

Idea

Best way is to add two communications (via interfaces):

  • FIRST between Activity and Adapter

  • SECOND between Adapter and single ViewHolder

Affter adding such type of communication your can calculate sum “live”.

Solution

Step #1

Create FIRST interface, for example:

interface AdapterContentChanged {
    fun valuesChanged()
}

and implement it in your Activity or create new variable (as anonymous class).

Step #2

Pass your activity (or instance of above interface) when you are creating adapter, for example:

private val ownAdapter = OwnAdapter(
    items,    // elements inside list
    this      // interface implementation
)

Step 3

Create SECOND interface, for example:

interface OwnViewHolderTextChanged {
    fun onTextChanged(position: Int, newValue: Int)
}

and implement it in your adapter or create new variable (anonymous class) – same like in step #1.

Step 4

Pass your adapter (or variable) and position (of the item) when you are binding viewHolder, for example:

override fun onBindViewHolder(holder: OwnViewHolder, position: Int) {
    val number = list[position]
    holder.bind(number, position, this)
}

Step 5

In bind() method (from above example), add new TextWatcher to your EditText.

In afterTextChanged() method (from TextWatcher) call method from interface and pass new value. For example:

fun bind(
    // TODO - add here more information which you need,
    position: Int,
    listener: OwnViewHolderTextChanged
) {
    itemView.edit_text.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            // Get EditText content
            val newValue = getNumber()

            // Call method from interface
            listener.onTextChanged(position = position, newValue = newValue)
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            // Not used
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            // Not used
        }

    })
}

To calculate value from EditText you can use something like this:

private fun getNumber(): Int =
    try {
        itemView.edit_text.text.toString().toInt()
    } catch (e: Exception) {
        0
    }

Step 6

When text was changed inside method you have to:

  • update content of the list

  • notify adapter that “something was changed”

For example:

override fun onTextChanged(position: Int, newValue: Int) {
    list[position] = newValue
    listener.valuesChanged()
}

Step 7

When something changed (and Activty will know about that), you can calculate new sum:

override fun valuesChanged() {
    val sum: Int = ownAdapter.getCurrentSum()
    text_view.text = "Sum:  $sum"
}

Demo

demo

Tagged : / / /

Code Bug Fix: Cant Connect to MongoDB Atlas – Java Spring

Original Source Link

I am trying to create a simple REST API and have it connected to MongoDB Atlas. Whenever I run it and make a call I get a no SNI name error. I have tried looking online but I could not figure out what was wrong. this is what I currently have:

I keep getting the following error:

com.mongodb.MongoCommandException: Command failed with error 8000 (AtlasError): 'no SNI name sent, make sure using a MongoDB 3.4+ driver/shell.' on server cluster0-shard-00-01-ad9oa.mongodb.net:27017. The full response is {"ok": 0, "errmsg": "no SNI name sent, make sure using a MongoDB 3.4+ driver/shell.", "code": 8000, "codeName": "AtlasError"}
at com.mongodb.internal.connection.ProtocolHelper.getCommandFailureException(ProtocolHelper.java:175) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:303) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:259) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:105) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:62) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:129) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.UsageTrackingInternalConnection.open(UsageTrackingInternalConnection.java:50) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.DefaultConnectionPool$PooledConnection.open(DefaultConnectionPool.java:398) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:115) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.DefaultConnectionPool.get(DefaultConnectionPool.java:101) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.internal.connection.DefaultServer.getConnection(DefaultServer.java:92) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.getConnection(ClusterBinding.java:126) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.client.internal.ClientSessionBinding$SessionBindingConnectionSource.getConnection(ClientSessionBinding.java:136) ~[mongodb-driver-3.11.2.jar:na]
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:728) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.operation.FindOperation$1.call(FindOperation.java:725) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.operation.OperationHelper.withReadConnectionSource(OperationHelper.java:463) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.operation.FindOperation.execute(FindOperation.java:725) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.operation.FindOperation.execute(FindOperation.java:89) ~[mongodb-driver-core-3.11.2.jar:na]
at com.mongodb.client.internal.MongoClientDelegate$DelegateOperationExecutor.execute(MongoClientDelegate.java:189) ~[mongodb-driver-3.11.2.jar:na]
at com.mongodb.client.internal.MongoIterableImpl.execute(MongoIterableImpl.java:143) ~[mongodb-driver-3.11.2.jar:na]
at com.mongodb.client.internal.MongoIterableImpl.iterator(MongoIterableImpl.java:92) ~[mongodb-driver-3.11.2.jar:na]
at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:2793) ~[spring-data-mongodb-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:2532) ~[spring-data-mongodb-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:2515) ~[spring-data-mongodb-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:876) ~[spring-data-mongodb-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.findAll(SimpleMongoRepository.java:380) ~[spring-data-mongodb-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.findAll(SimpleMongoRepository.java:204) ~[spring-data-mongodb-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.mongodb.repository.support.SimpleMongoRepository.findAll(SimpleMongoRepository.java:54) ~[spring-data-mongodb-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:371) ~[spring-data-commons-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:204) ~[spring-data-commons-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:657) ~[spring-data-commons-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:621) ~[spring-data-commons-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:605) ~[spring-data-commons-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.2.7.RELEASE.jar:2.2.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.sun.proxy.$Proxy67.findAll(Unknown Source) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at com.sun.proxy.$Proxy67.findAll(Unknown Source) ~[na:na]
at com.example.demo.Service.PersonService.getAll(PersonService.java:23) ~[classes/:na]
at com.example.demo.Controller.PersonController.getAll(PersonController.java:30) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.34.jar:9.0.34]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

This is how my application properties looks like

spring.data.mongodb.uri=mongodb+srv://tayeb:<Password-Removed>@cluster0-ad9oa.mongodb.net/test?retryWrites=true&w=majority
spring.data.mongodb.database=Test

Controller:

package com.example.demo.Controller;

import com.example.demo.Service.PersonService;
import com.example.demo.models.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class PersonController {

    @Autowired
    private PersonService personService;

    @RequestMapping("/create")
    public String create(@RequestParam String firstName, @RequestParam String lastName, @RequestParam String age) {
        Person p = personService.create(firstName, lastName, age);
        return p.toString();
    }

    @RequestMapping("/get")
    public Person getPerson(@RequestParam String firstName) {
        return personService.getByFirstName(firstName);
    }
    @RequestMapping("/getAll")
    public List<Person> getAll(){
        return personService.getAll();
    }
    @RequestMapping("/update")
    public String update(@RequestParam String firstName, @RequestParam String lastName, @RequestParam String age) {
        Person p = personService.update(firstName, lastName, age);
        return p.toString();
    }
    @RequestMapping("/delete")
    public String delete(@RequestParam String firstName) {
        personService.delete(firstName);
        return "Deleted "+firstName;
    }
    @RequestMapping("/deleteAll")
    public String deleteAll() {
        personService.deleteAll();
        return "Deleted all records";
    }

}

Model

package com.example.demo.models;

import org.springframework.data.annotation.Id;

public class Person {

    @Id
    String id;
    String firstName;
    String lastName;
    String age;


    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }




    public Person(String firstName, String lastName, String age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }
}

Repository:

package com.example.demo.Repository;


import com.example.demo.models.Person;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface PersonRepository extends MongoRepository<Person, String>
{
    public Person findByFirstName(String firstName);
    public List<Person> findByAge(int age);
}

Service

package com.example.demo.Service;


import com.example.demo.Repository.PersonRepository;
import com.example.demo.models.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {

    @Autowired
    private PersonRepository personRepository;

    //Create operation
    public Person create(String firstName, String lastName, String age) {
        return personRepository.save(new Person(firstName, lastName, age));
    }
    //Retrieve operation
    public List<Person> getAll(){
        return personRepository.findAll();
    }
    public Person getByFirstName(String firstName) {
        return personRepository.findByFirstName(firstName);
    }
    //Update operation
    public Person update(String firstName, String lastName, String age) {
        Person p = personRepository.findByFirstName(firstName);
        p.setLastName(lastName);
        p.setAge(age);
        return personRepository.save(p);
    }
    //Delete operation
    public void deleteAll() {
        personRepository.deleteAll();
    }
    public void delete(String firstName) {
        Person p = personRepository.findByFirstName(firstName);
        personRepository.delete(p);
    }

}

main

 package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);

    }


}

These are all the files associated with my program. I would really appreciate any help

Tagged : / / /

Code Bug Fix: Elasticsearch: I get exception: ElasticsearchSecurityException[Cannot authenticate null]

Original Source Link

When I run my test and try to collect some logs via Elasticsearch I get the following error. The exception start appearing since upgraded to selenium:selenium-java:3.141.59 / FireFox version 75. What am I missing? My Elasticsearch and versions

org.elasticsearch:elasticsearch:5.6.4
org.elasticsearch.client:transport:5.6.4
com.floragunn:search-guard-ssl:5.6.4-23


   [2020-05-15 16:25:29.475]    
   ****************************************************************************************************
   [2020-05-15 16:25:29.476]   FAILED TO CAPTURE PRODUCTLOGS: ElasticsearchSecurityException[Cannot authenticate null]
   at com.floragunn.searchguard.transport.SearchGuardRequestHandler.messageReceivedDecorate(SearchGuardRequestHandler.java:228)
   at com.floragunn.searchguard.ssl.transport.SearchGuardSSLRequestHandler.messageReceived(SearchGuardSSLRequestHandler.java:142)
   at com.floragunn.searchguard.SearchGuardPlugin$7$1.messageReceived(SearchGuardPlugin.java:644)
   at org.elasticsearch.transport.RequestHandlerRegistry.processMessageReceived(RequestHandlerRegistry.java:66)
   at org.elasticsearch.transport.TcpTransport$RequestHandler.doRun(TcpTransport.java:1350)
   at org.elasticsearch.common.util.concurrent.AbstractRunnable.run(AbstractRunnable.java:37)
   at org.elasticsearch.common.util.concurrent.EsExecutors$1.execute(EsExecutors.java:135)
   at org.elasticsearch.transport.TcpTransport.handleRequest(TcpTransport.java:1308)
   at org.elasticsearch.transport.TcpTransport.messageReceived(TcpTransport.java:1172)
   at org.elasticsearch.transport.netty4.Netty4MessageChannelHandler.channelRead(Netty4MessageChannelHandler.java:65)
   at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
   at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)
   at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:340)
   at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:323)
   at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:310)
   at io.netty.handler.codec.ByteToMessageDecoder.callDecode(ByteToMessageDecoder.java:426)
   at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:278)
   at `enter code here`io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362)
   at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:348)

Tagged : / /