问:
How to get value of a component to another component
I am creating a Project where I need to get value of a component state value to another component.

How can I get the value?

Information

Both are functional component.

I need to send data from A (state) to B(state).

A state data are set from react dropdown menu.Which is a button.

I don't use Link or Route to A dropdown that's why I can't get it with useParams()

I need to set value in B component which will fetch data with passing language.

I have import all needed things & don't have any warnings & error.

Code of component A

Send value from this language state to B

const A = () => {
    const [language, setLanguage] = useState('en');

    return (
        <Navbar expand="xl" bg='light' expand={false}>
            <Container>
                <DropdownButton id="dropdown-basic-button" title={<MdOutlineLanguage />}>
                    <Dropdown.Item as="button" onClick={() => setLanguage('en')}>English</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('ar')}>العربية</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('bn')}>বাংলা</Dropdown.Item>
                </DropdownButton>
            </Container>
        </Navbar>
    )
};

export default A
```
<h4>Code of Component B</h4>
<ol>
<li>I need to get here <code>A</code> state value & set it to <code>B</code> state. Then pass to <code>useGetDataQuery</code> & fetch data.</li>
</ol>
<pre class="lang-js prettyprint-override"><code>const B = () => {
    let [language, setLanguage] = useState('en')
    const { data } = useGetDataQuery({language })

    return (
        <>

        </>
    )
}
export default B
</code>```

Redux Section

I'm using readux & @reduxjs/toolkit to store fetch data. Can I store my language data to here. Than how can get to from anywhere of my component.

react-rotuer-dom v6

export default configureStore({
    reducer: {
        [dataOne.reducerPath]: dataOne.reducer,
        [data2.reducerPath]: dataTwo.reducer,
    },
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: false
        }).concat([dataOne.middleware, dataTwo.middleware]),

})
```

答:
Maybe instead of using useState, you can use a global state by using useContext because I think your language will be use on several places as request body and of course to edit the state value, you can combine it with useReducer.

// UPDATE

working code: https://codesandbox.io/s/sleepy-monad-21wnc

MyContext

```<code>import { useReducer, useContext, createContext } from "react";

const initialValue = {
  language: "id"
  // other: "value",
};

const AppContext = createContext(initialValue);

const AppReducer = (state, action) => {
  switch (action.type) {
    case "CHANGE_LANGUAGE":
      return {
        ...state,
        ...action.payload
      };
    default:
      return state;
  }
};

const MyContext = ({ children }) => {
  const [state, dispatch] = useReducer(AppReducer, initialValue);
  return (
    <AppContext.Provider value={[state, dispatch]}>
      {children}
    </AppContext.Provider>
  );
};

export const useAppContext = () => useContext(AppContext);
export default MyContext;
</code>```

this is the context and reducer component later on use in App.js

App.js

```<code>import A from "./A";
import B from "./B";
import MyContext from "./MyContext";
import "./styles.css";

export default function App() {
  return (
    <MyContext>
      <div className="App">
        <A />
        <B />
      </div>
    </MyContext>
  );
}
</code>```

A.js

```<code>import { useAppContext } from "./MyContext";

const A = () => {
  const [globalState, dispatch] = useAppContext();

  const onChange = (e) => {
    dispatch({
      type: "CHANGE_LANGUAGE",
      payload: {
        [e.target.name]: e.target.value
      }
    });
  };

  return (
    <>
      <p>Start Of Component A </p>
      <input value={globalState.language} name="language" onChange={onChange} />
      <p>End Of Component A </p>
    </>
  );
};

export default A;
</code>```

B.js

```<code>import { useAppContext } from "./MyContext";

const B = () => {
  const [globalState, dispatch] = useAppContext();

  return (
    <>
      <p>Start Of Component B </p>
      <h2>Language Val : {globalState.language}</h2>
      <p>End Of Component B </p>
    </>
  );
};

export default B;
</code>```

Body:
I am creating a Project where I need to get value of a component state value to another component.

How can I get the value?

Information

Both are functional component.

I need to send data from A (state) to B(state).

A state data are set from react dropdown menu.Which is a button.

I don't use Link or Route to A dropdown that's why I can't get it with useParams()

I need to set value in B component which will fetch data with passing language.

I have import all needed things & don't have any warnings & error.

Code of component A

Send value from this language state to B

const A = () => {
    const [language, setLanguage] = useState('en');

    return (
        <Navbar expand="xl" bg='light' expand={false}>
            <Container>
                <DropdownButton id="dropdown-basic-button" title={<MdOutlineLanguage />}>
                    <Dropdown.Item as="button" onClick={() => setLanguage('en')}>English</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('ar')}>العربية</Dropdown.Item>
                    <Dropdown.Item as="button" onClick={() => setLanguage('bn')}>বাংলা</Dropdown.Item>
                </DropdownButton>
            </Container>
        </Navbar>
    )
};

export default A

Code of Component B

I need to get here A state value & set it to B state. Then pass to useGetDataQuery & fetch data.

const B = () => {
    let [language, setLanguage] = useState('en')
    const { data } = useGetDataQuery({language })

    return (
        <>

        </>
    )
}
export default B

Redux Section

I'm using readux & @reduxjs/toolkit to store fetch data. Can I store my language data to here. Than how can get to from anywhere of my component.

react-rotuer-dom v6

export default configureStore({
    reducer: {
        [dataOne.reducerPath]: dataOne.reducer,
        [data2.reducerPath]: dataTwo.reducer,
    },
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware({
            serializableCheck: false
        }).concat([dataOne.middleware, dataTwo.middleware]),

})

Body:
Maybe instead of using useState, you can use a global state by using useContext because I think your language will be use on several places as request body and of course to edit the state value, you can combine it with useReducer.

// UPDATE

working code: https://codesandbox.io/s/sleepy-monad-21wnc

MyContext

import { useReducer, useContext, createContext } from "react";

const initialValue = {
  language: "id"
  // other: "value",
};

const AppContext = createContext(initialValue);

const AppReducer = (state, action) => {
  switch (action.type) {
    case "CHANGE_LANGUAGE":
      return {
        ...state,
        ...action.payload
      };
    default:
      return state;
  }
};

const MyContext = ({ children }) => {
  const [state, dispatch] = useReducer(AppReducer, initialValue);
  return (
    <AppContext.Provider value={[state, dispatch]}>
      {children}
    </AppContext.Provider>
  );
};

export const useAppContext = () => useContext(AppContext);
export default MyContext;

this is the context and reducer component later on use in App.js

App.js

import A from "./A";
import B from "./B";
import MyContext from "./MyContext";
import "./styles.css";

export default function App() {
  return (
    <MyContext>
      <div className="App">
        <A />
        <B />
      </div>
    </MyContext>
  );
}

A.js

import { useAppContext } from "./MyContext";

const A = () => {
  const [globalState, dispatch] = useAppContext();

  const onChange = (e) => {
    dispatch({
      type: "CHANGE_LANGUAGE",
      payload: {
        [e.target.name]: e.target.value
      }
    });
  };

  return (
    <>
      <p>Start Of Component A </p>
      <input value={globalState.language} name="language" onChange={onChange} />
      <p>End Of Component A </p>
    </>
  );
};

export default A;

B.js

import { useAppContext } from "./MyContext";

const B = () => {
  const [globalState, dispatch] = useAppContext();

  return (
    <>
      <p>Start Of Component B </p>
      <h2>Language Val : {globalState.language}</h2>
      <p>End Of Component B </p>
    </>
  );
};

export default B;


来源: stackexchange

问:
How to write loop in a Makefile?
I want to execute the following commands:

```<code>./a.out 1
./a.out 2
./a.out 3
./a.out 4
.
.
. and so on
</code>```

How to write this thing as a loop in a Makefile?

答:
Version

OS: WINDOWS_NT

GNU make 4.3

Code

files := $(wildcard ./*.txt ./**/*.go */**/*.js )

showFileFunc = echo "$(abspath ${1})\${2}"
delFileFunc = del "$(abspath ${1})\${2}"
cmdSplit = &
targetDisplay:
    $(foreach curFile, ${files}, ${call showFileFunc,${dir $(curFile)},${notdir $(curFile)}} ${cmdSplit})
targetDelete:
    $(foreach curFile, ${files}, ${call delFileFunc,${dir $(curFile)},${notdir $(curFile)}} ${cmdSplit})
```
<h3>Test Directory</h3>
```Makefile
1.txt
 myDir
   - foo.go
   - bar.go
   - subDir
     - qoo.js
```
<h3>Test CMD & output</h3>
```make showFile -s

output:
"C:/...\1.txt"
"C:/.../myDir\bar.go"
"C:/.../myDir\foo.go"          // since `.//**.js`
"C:/.../myDir/subDir\qoo.js"   // `.//**.js` can't but `*/**/*.js` is OK
```

Reference

wildcard

foreach

abspath, dir

call

ContentLicense: CC BY-SA 3.0

Title: How to write loop in a Makefile?

Body:
I want to execute the following commands:

./a.out 1
./a.out 2
./a.out 3
./a.out 4
.
.
. and so on

How to write this thing as a loop in a Makefile?

Body:
Version

OS: WINDOWS_NT

GNU make 4.3

Code

files := $(wildcard ./*.txt ./**/*.go */**/*.js )

showFileFunc = echo "$(abspath ${1})\${2}"
delFileFunc = del "$(abspath ${1})\${2}"
cmdSplit = &
targetDisplay:
    $(foreach curFile, ${files}, ${call showFileFunc,${dir $(curFile)},${notdir $(curFile)}} ${cmdSplit})
targetDelete:
    $(foreach curFile, ${files}, ${call delFileFunc,${dir $(curFile)},${notdir $(curFile)}} ${cmdSplit})

Test Directory

Makefile
1.txt
 myDir
   - foo.go
   - bar.go
   - subDir
     - qoo.js

Test CMD & output

make showFile -s

output:
"C:/...\1.txt"
"C:/.../myDir\bar.go"
"C:/.../myDir\foo.go"          // since `.//**.js`
"C:/.../myDir/subDir\qoo.js"   // `.//**.js` can't but `*/**/*.js` is OK

Reference

wildcard

foreach

abspath, dir

call

ContentLicense: CC BY-SA 4.0


问:
How to make a .lib file when have a .dll file and a header file
I am trying to create an application in visual studio that will be able to access a .dll file that already exists. I need the application to call up routines. I also have a header file that already exists.

I have been researching on the internet and have found that I need to create a .lib file. Looking at similar questions on here I found a link: http://support.microsoft.com/kb/131313
I cannot however follow the directions.

The information in the link says to make a DEF file ( I read elsewhere that this needs to be compiled as a DLL with the same name, but not sure what that name is, the same name as the .dll file?). But I do not understand the first direction, to 'Use DUMPBIN /EXPORTS'. I then need to 'stub out' functions, and then something to do with .OBJ files (I do not know what these files are).

Are there any step-by-step directions, similar to the link above, that are easy to follow?

答:
First type

#define YOURPROJECT_API _declspec(dllexport)

void yourf()

cpp

```<code>#include "pch.h"
#include "YOURPROJECT.H"
void yourf() {}
</code>```

then include them

linker->input->def file then inhert from parent or project default

compile

Body:
First type

#define YOURPROJECT_API _declspec(dllexport)

void yourf()

cpp

#include "pch.h"
#include "YOURPROJECT.H"
void yourf() {}

then include them

linker->input->def file then inhert from parent or project default

compile


问:
Copy a range of Cells inside a loop to Powerpoint
I have a data set that Im trying to tur into automatic PowerPoint slides.The number of rows changes weekly so the range has to be variable.
this is how my data looks like

So far i've been able to create a slide for each title, copy the headers as an image and add copy the value of the 16th cell to each slide, but now i want to copy the values of each row its looping as an image but only from columns B to O.
So that the First slide would have (B1:O1)
The second would have (B2:O2)
But i haven figured out how to do it.
I wanted to use "rowShape" as the name for the rows image
Here's my code so far:

Option Explicit
Sub Data_to_PowerPoint()

    Dim newPowerPoint As PowerPoint.Application
    Dim activeSlide As PowerPoint.Slide
    Dim ExcelRow As Range
    Dim CellRange As Range
    Dim SlideText As Variant
    Dim lr As Long
    Dim hdr As Range
    Dim myShape As Object
    Dim rowShape As Object

    'The first range of cells in the table.
    lr = Cells(Rows.Count, "A").End(xlUp).Row
    Set CellRange = Sheets("TicketSummary").Range("A1:A" & lr)

    'Determine header range.
    Set hdr = Sheets("TicketSummary").Range("B1:O1")

    'Look for existing powerpoint instance
    On Error Resume Next
    Set newPowerPoint = GetObject(, "PowerPoint.Application")
    On Error GoTo 0

    'Create a PowerPoint
    If newPowerPoint Is Nothing Then

        Set newPowerPoint = New PowerPoint.Application

    End If

    'Setup the presentation in PowerPoint
    If newPowerPoint.Presentations.Count = 0 Then

        newPowerPoint.Presentations.Add

    End If

    'Make PowerPoint visible
    newPowerPoint.Visible = True

    'Loop through each chart in the Excel worksheet and paste them into the PowerPoint
    For Each ExcelRow In CellRange

        'Add a new slide
        newPowerPoint.ActivePresentation.Slides.Add newPowerPoint.ActivePresentation.Slides.Count + 1, ppLayoutText
        newPowerPoint.ActiveWindow.View.GotoSlide newPowerPoint.ActivePresentation.Slides.Count
        Set activeSlide = newPowerPoint.ActivePresentation.Slides(newPowerPoint.ActivePresentation.Slides.Count)

        'Create the body text for the slide
        SlideText = Cells(ExcelRow.Row, 16)

        'Input the title of the slide
        activeSlide.Shapes(1).TextFrame.TextRange.Text = ExcelRow.Value

        'Input the body text for the slide
        activeSlide.Shapes(2).TextFrame.TextRange.Text = SlideText

        'Copy Header.
         hdr.Copy

        'Paste header to PowerPoint and position
        activeSlide.Shapes.PasteSpecial DataType:=2  '2 = ppPasteEnhancedMetafile
        Set myShape = activeSlide.Shapes(activeSlide.Shapes.Count)

       'Set position:
        myShape.Left = 60
        myShape.Top = 152

   Next

   Set activeSlide = Nothing
   Set newPowerPoint = Nothing

End Sub

```

答:
Option Explicit

Sub Data_to_PowerPoint()

    Dim pp As PowerPoint.Application, pps As PowerPoint.Slide
    Dim lr As Long, i As Long, n As Long

    'Look for existing powerpoint instance
    On Error Resume Next
    Set pp = GetObject(, "PowerPoint.Application")
    On Error GoTo 0

    'Create a PowerPoint
    If pp Is Nothing Then
        Set pp = New PowerPoint.Application
    End If
    'Setup the presentation in PowerPoint
    If pp.Presentations.Count = 0 Then
        pp.Presentations.Add
    End If
     'Make PowerPoint visible
    pp.Visible = True

    'The first range of cells in the table.
    With Sheets("TicketSummary")

        lr = .Cells(.Rows.Count, "A").End(xlUp).Row
        For i = 2 To lr
            ' create slide
            pp.ActivePresentation.Slides.Add i - 1, ppLayoutText
            pp.ActiveWindow.View.GotoSlide i - 1
            Set pps = pp.ActivePresentation.Slides(i - 1)

           'Input the title of the slide
            pps.Shapes(1).TextFrame.TextRange.Text = .Cells(i, "A")

            'Input the body text for the slide
            pps.Shapes(2).TextFrame.TextRange.Text = .Cells(i, "P") ' col 16

            ' copy header
            ' Paste to PowerPoint and position
            ' paste 2 = ppPasteEnhancedMetafile 3 ppPasteMetafilePicture
            n = pps.Shapes.Count
            .Range("B1:O1").Copy
            Application.Wait Now + TimeSerial(0, 0, 1) ' 1 second wait
            pps.Shapes.PasteSpecial DataType:=2

            ' wait for shape to be pasted
            Do
                DoEvents
            Loop Until pps.Shapes.Count > n
            Application.CutCopyMode = False

            'Set position:
            With pps.Shapes(n + 1)
                .Left = 60
                .Top = 182
            End With

            ' copy row
            n = pps.Shapes.Count
            .Range("B1:O1").Offset(i - 1).Copy
            Application.Wait Now + TimeSerial(0, 0, 1) ' 1 second wait
            pps.Shapes.PasteSpecial DataType:=2

            ' wait for shape to be pasted
            Do
                DoEvents
            Loop Until pps.Shapes.Count > n
            Application.CutCopyMode = False

            'Set position:
            With pps.Shapes(n + 1)
                .Left = 60
                .Top = 202
            End With

        Next
    End With
    MsgBox lr - 1 & " slides created"

End Sub
```


问:
View javascript object model in real time
Are there tools or techniques (other than repeated console.log() calls) to view the javascript object model used in a web page in real time? eg something like:

```<code>    firstUser (User)
    -- userName Joe Bloggs (String)
    -- userEmail joe.bloggs@gmail.com (String)
    -- userSelections (Array)
    ----[1,2,4]

    secondUser (User)
    -- userName John Doe (String)
    -- userEmail jogn.doe@gmail.com (String)
    -- userSelections (Array)
    ----[1,2,3]
</code>```

I know this can be achieved using console.log(firstUser) and console.log(secondUser) but it would be useful to be able to display the entire data model so that I can see variables being altered in real time.

答:
You can use the debugger of the development tools in Chrome or Firefox.
Just set a break point and view the state of all variables under the scope header.</p>

Body:
Are there tools or techniques (other than repeated console.log() calls) to view the javascript object model used in a web page in real time? eg something like:

    firstUser (User)
    -- userName Joe Bloggs (String)
    -- userEmail joe.bloggs@gmail.com (String)
    -- userSelections (Array)
    ----[1,2,4]

    secondUser (User)
    -- userName John Doe (String)
    -- userEmail jogn.doe@gmail.com (String)
    -- userSelections (Array)
    ----[1,2,3]

I know this can be achieved using console.log(firstUser) and console.log(secondUser) but it would be useful to be able to display the entire data model so that I can see variables being altered in real time.


问:
Why L1 regularization works in machine Learning
Well, in machine learning, one way to prevent overfitting is to add L2 regularization, and some says that L1 regularization is better, why is that? Also i know that L1 is used to ensure the sparsity of data, what is the theoretical support for this result?</p>

答:
L1 regularization: It adds an L1 penalty that is equal to the absolute value of the magnitude of coefficient, or simply restricting the size of coefficients. For example, Lasso regression implements this method.

L1 regularization is the preferred choice when having a high number of features as it provides sparse solutions. Even, we obtain the computational advantage because features with zero coefficients can be avoided.

you can read more this website


问:
How to identify server IP address in PHP
How can I identify the server IP address in PHP?</p>

答:
Here is one solution when the site is running behind a load-balancer, a reverse proxy server, or a CDN like CloudFront:</p>
```<code>$conn = curl_init();
curl_setopt($conn, CURLOPT_URL, 'any.valid.url');
curl_exec($conn);
$WebServerIP = curl_getinfo($conn)['local_ip'];
</code>```

Body:
Here is one solution when the site is running behind a load-balancer, a reverse proxy server, or a CDN like CloudFront:

$conn = curl_init();
curl_setopt($conn, CURLOPT_URL, 'any.valid.url');
curl_exec($conn);
$WebServerIP = curl_getinfo($conn)['local_ip'];


问:
Swift 5.5: Async @objc didPullToRefresh selector crashes app with error EXC_BAD_ACCESS
I have a table to which I've added a refreshControl and when I pull down to refresh the content, I reset the array that feeds the table with data and then immediately request new data through an API call.

Until now, I have used completion handlers and protocols to get the data into the table view but I want to move the logic to async/await because of the complexity needed by the network calls and the pyramid of nested closures.

Populating the view in viewDidLoad works fine but with pullToRefresh selector I get an error:

```<code>Thread 1: EXC_BAD_ACCESS (code=1, address=0xbcf917df8160)
</code>```

Implementation:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
    setupView()
    setupTableView()
    setupTableRefreshControl()
    Task {
      await getBalances() //async network call
      myTable.reloadData()
    }
  }
</code>```
```<code>func setupTableRefreshControl() {
    myTable.refreshControl = UIRefreshControl()
    myTable.refreshControl?.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged)
  }
</code>```

Code that crashes app:

```<code>   @objc func didPullToRefresh() async {
    balance.reset() // reset array to []
    Task {
      await getBalances() //async network call
      myTable.reloadData()
    }
  }
</code>```

答: I realized that didPullToRefresh does not need to be marked as async. Removing "async" from the function signature solves the problem</p>

Body:
I have a table to which I've added a refreshControl and when I pull down to refresh the content, I reset the array that feeds the table with data and then immediately request new data through an API call.

Until now, I have used completion handlers and protocols to get the data into the table view but I want to move the logic to async/await because of the complexity needed by the network calls and the pyramid of nested closures.

Populating the view in viewDidLoad works fine but with pullToRefresh selector I get an error:

Thread 1: EXC_BAD_ACCESS (code=1, address=0xbcf917df8160)

Implementation:

override func viewDidLoad() {
    super.viewDidLoad()
    setupView()
    setupTableView()
    setupTableRefreshControl()
    Task {
      await getBalances() //async network call
      myTable.reloadData()
    }
  }

func setupTableRefreshControl() {
    myTable.refreshControl = UIRefreshControl()
    myTable.refreshControl?.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged)
  }

Code that crashes app:

   @objc func didPullToRefresh() async {
    balance.reset() // reset array to []
    Task {
      await getBalances() //async network call
      myTable.reloadData()
    }
  }


问:
Manipulating data point in chart.js external tooltip
I'm using Chart.js to display some financial data in a pie chart, along with external tooltips. The data in the tooltip is displayed currently like this:

"Invoiceable: 1,202.5"

What I want is to firstly round the number to 1,200, and then add a '£' sign before the data point so it reads:

"Invoiceable: £1,200"

I'm struggling to work out how to do this in this code below. Can anyone help?

```<code> tooltip: {
            // Disable the on-canvas tooltip
            enabled: false,

            external: function(context) {
                // Tooltip Element
                let tooltipEl = document.getElementById('chartjs-tooltip');

                // Create element on first render
                if (!tooltipEl) {
                    tooltipEl = document.createElement('div');
                    tooltipEl.id = 'chartjs-tooltip';
                    tooltipEl.innerHTML = '<table></table>';
                    document.body.appendChild(tooltipEl);
                }

                // Hide if no tooltip
                const tooltipModel = context.tooltip;
                if (tooltipModel.opacity === 0) {
                    tooltipEl.style.opacity = 0;
                    return;
                }

                // Set caret Position
                tooltipEl.classList.remove('above', 'below', 'no-transform');
                if (tooltipModel.yAlign) {
                    tooltipEl.classList.add(tooltipModel.yAlign);
                } else {
                    tooltipEl.classList.add('no-transform');
                }

                function getBody(bodyItem) {
                     return bodyItem.lines;
                }

                // Set Text
                if (tooltipModel.body) {

                    const titleLines = tooltipModel.title || [];
                    const bodyLines = tooltipModel.body.map(getBody);

                    let innerHtml = '<thead>';

                    titleLines.forEach(function(title) {
                        innerHtml += '<tr><th>' + title + '</th></tr>';
                    });
                    innerHtml += '</thead><tbody>';

                    bodyLines.forEach(function(body, i) {
                        innerHtml += '<tr><td><div class="tooltip">'+ body + '</div></td></tr>';
                    });
                    innerHtml += '</tbody>';

                    let tableRoot = tooltipEl.querySelector('table');
                    tableRoot.innerHTML = innerHtml;
                }

                const position = context.chart.canvas.getBoundingClientRect();
                const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);

                // Display, position, and set styles for font
                tooltipEl.style.opacity = .8;
                tooltipEl.style.position = 'absolute';
                tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
                tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
                tooltipEl.style.font = bodyFont.string;
                tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
                tooltipEl.style.pointerEvents = 'none';
            }
        }
</code>```

FTR - I copied the above code from chart.js, which made it work, but I don't presume to understand it for a second!

答:
You can adjust the bodyLines.forEach loop to alter the value it shows like so:

bodyLines.forEach(function(body, i) {
    let [label, value] = body[0].split(': ');
    value = `£${value.split('.')[0]}`
    innerHtml += '

' + `${label}: ${value}` + '

';
});
```
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: 'Invoicable',
      data: [120000.5, 190000.7, 30000.2, 50000.3, 20000.9, 30000.1],
      borderColor: 'pink',
      backgroundColor: 'pink',
    }]
  },
  options: {
    locale: 'en-EN',
    plugins: {
      tooltip: {
        // Disable the on-canvas tooltip
        enabled: false,

        external: function(context) {
          // Tooltip Element
          let tooltipEl = document.getElementById('chartjs-tooltip');

          // Create element on first render
          if (!tooltipEl) {
            tooltipEl = document.createElement('div');
            tooltipEl.id = 'chartjs-tooltip';
            tooltipEl.innerHTML = '<table></table>';
            document.body.appendChild(tooltipEl);
          }

          // Hide if no tooltip
          const tooltipModel = context.tooltip;
          if (tooltipModel.opacity === 0) {
            tooltipEl.style.opacity = 0;
            return;
          }

          // Set caret Position
          tooltipEl.classList.remove('above', 'below', 'no-transform');
          if (tooltipModel.yAlign) {
            tooltipEl.classList.add(tooltipModel.yAlign);
          } else {
            tooltipEl.classList.add('no-transform');
          }

          function getBody(bodyItem) {
            return bodyItem.lines;
          }

          // Set Text
          if (tooltipModel.body) {

            const titleLines = tooltipModel.title || [];
            const bodyLines = tooltipModel.body.map(getBody);

            let innerHtml = '<thead>';

            titleLines.forEach(function(title) {
              innerHtml += '<tr><th>' + title + '</th></tr>';
            });
            innerHtml += '</thead><tbody>';

            bodyLines.forEach(function(body, i) {
              let [label, value] = body[0].split(': ');
              value = `£${value.split('.')[0]}`
              innerHtml += '<tr><td><div class="tooltip">' + `${label}: ${value}` + '</div></td></tr>';
            });
            innerHtml += '</tbody>';

            let tableRoot = tooltipEl.querySelector('table');
            tableRoot.innerHTML = innerHtml;
          }

          const position = context.chart.canvas.getBoundingClientRect();
          const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);

          // Display, position, and set styles for font
          tooltipEl.style.opacity = .8;
          tooltipEl.style.position = 'absolute';
          tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
          tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
          tooltipEl.style.font = bodyFont.string;
          tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
          tooltipEl.style.pointerEvents = 'none';
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);</code>```

  <canvas id="chartJSContainer" width="600" height="400"></canvas>

```

Body:
I'm using Chart.js to display some financial data in a pie chart, along with external tooltips. The data in the tooltip is displayed currently like this:

"Invoiceable: 1,202.5"

What I want is to firstly round the number to 1,200, and then add a '£' sign before the data point so it reads:

"Invoiceable: £1,200"

I'm struggling to work out how to do this in this code below. Can anyone help?

 tooltip: {
            // Disable the on-canvas tooltip
            enabled: false,

            external: function(context) {
                // Tooltip Element
                let tooltipEl = document.getElementById('chartjs-tooltip');

                // Create element on first render
                if (!tooltipEl) {
                    tooltipEl = document.createElement('div');
                    tooltipEl.id = 'chartjs-tooltip';
                    tooltipEl.innerHTML = '

';
                    document.body.appendChild(tooltipEl);
                }

                // Hide if no tooltip
                const tooltipModel = context.tooltip;
                if (tooltipModel.opacity === 0) {
                    tooltipEl.style.opacity = 0;
                    return;
                }

                // Set caret Position
                tooltipEl.classList.remove('above', 'below', 'no-transform');
                if (tooltipModel.yAlign) {
                    tooltipEl.classList.add(tooltipModel.yAlign);
                } else {
                    tooltipEl.classList.add('no-transform');
                }

                function getBody(bodyItem) {
                     return bodyItem.lines;
                }

                // Set Text
                if (tooltipModel.body) {

                    const titleLines = tooltipModel.title || [];
                    const bodyLines = tooltipModel.body.map(getBody);

                    let innerHtml = '
';

                    titleLines.forEach(function(title) {
                        innerHtml += '
' + title + '
';
                    });
                    innerHtml += '

';

                    bodyLines.forEach(function(body, i) {
                        innerHtml += '

'+ body + '

';
                    });
                    innerHtml += '
';

                    let tableRoot = tooltipEl.querySelector('table');
                    tableRoot.innerHTML = innerHtml;
                }

                const position = context.chart.canvas.getBoundingClientRect();
                const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);

                // Display, position, and set styles for font
                tooltipEl.style.opacity = .8;
                tooltipEl.style.position = 'absolute';
                tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
                tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
                tooltipEl.style.font = bodyFont.string;
                tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
                tooltipEl.style.pointerEvents = 'none';
            }
        }

FTR - I copied the above code from chart.js, which made it work, but I don't presume to understand it for a second!

Body:
You can adjust the bodyLines.forEach loop to alter the value it shows like so:

bodyLines.forEach(function(body, i) {
    let [label, value] = body[0].split(': ');
    value = `£${value.split('.')[0]}`
    innerHtml += '<tr><td><div class="tooltip">' + `${label}: ${value}` + '</div></td></tr>';
});

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
      label: 'Invoicable',
      data: [120000.5, 190000.7, 30000.2, 50000.3, 20000.9, 30000.1],
      borderColor: 'pink',
      backgroundColor: 'pink',
    }]
  },
  options: {
    locale: 'en-EN',
    plugins: {
      tooltip: {
        // Disable the on-canvas tooltip
        enabled: false,

        external: function(context) {
          // Tooltip Element
          let tooltipEl = document.getElementById('chartjs-tooltip');

          // Create element on first render
          if (!tooltipEl) {
            tooltipEl = document.createElement('div');
            tooltipEl.id = 'chartjs-tooltip';
            tooltipEl.innerHTML = '<table></table>';
            document.body.appendChild(tooltipEl);
          }

          // Hide if no tooltip
          const tooltipModel = context.tooltip;
          if (tooltipModel.opacity === 0) {
            tooltipEl.style.opacity = 0;
            return;
          }

          // Set caret Position
          tooltipEl.classList.remove('above', 'below', 'no-transform');
          if (tooltipModel.yAlign) {
            tooltipEl.classList.add(tooltipModel.yAlign);
          } else {
            tooltipEl.classList.add('no-transform');
          }

          function getBody(bodyItem) {
            return bodyItem.lines;
          }

          // Set Text
          if (tooltipModel.body) {

            const titleLines = tooltipModel.title || [];
            const bodyLines = tooltipModel.body.map(getBody);

            let innerHtml = '<thead>';

            titleLines.forEach(function(title) {
              innerHtml += '<tr><th>' + title + '</th></tr>';
            });
            innerHtml += '</thead><tbody>';

            bodyLines.forEach(function(body, i) {
              let [label, value] = body[0].split(': ');
              value = `£${value.split('.')[0]}`
              innerHtml += '<tr><td><div class="tooltip">' + `${label}: ${value}` + '</div></td></tr>';
            });
            innerHtml += '</tbody>';

            let tableRoot = tooltipEl.querySelector('table');
            tableRoot.innerHTML = innerHtml;
          }

          const position = context.chart.canvas.getBoundingClientRect();
          const bodyFont = Chart.helpers.toFont(tooltipModel.options.bodyFont);

          // Display, position, and set styles for font
          tooltipEl.style.opacity = .8;
          tooltipEl.style.position = 'absolute';
          tooltipEl.style.left = position.left + window.pageXOffset + tooltipModel.caretX + 'px';
          tooltipEl.style.top = position.top + window.pageYOffset + tooltipModel.caretY + 'px';
          tooltipEl.style.font = bodyFont.string;
          tooltipEl.style.padding = tooltipModel.padding + 'px ' + tooltipModel.padding + 'px';
          tooltipEl.style.pointerEvents = 'none';
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);

<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"></script>
</body>


问:
Create C# Class to fit XML file
I have this XML file, how can I make a C# Class to fit it, so I can Deserialize it to a C# object.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                  xmlns:siat="https://siat.in.com/">
    <soapenv:Header/>
    <soapenv:Body>
        <siat:cuis>
            <SolicitudCuis>
                <codigoAmbiente>2</codigoAmbiente>
                <codigoModalidad>2</codigoModalidad>
                <codigoPuntoVenta>1</codigoPuntoVenta>
                <codigoSistema>6D26B339E99593D9E6EE26F</codigoSistema>
                <codigoSucursal>0</codigoSucursal>
                <nit>6088511016</nit>
            </SolicitudCuis>
        </siat:cuis>
    </soapenv:Body>
</soapenv:Envelope>
```

答:
Try following :</p>
```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
            Envelope envelope = (Envelope)serializer.Deserialize(reader);
        }
    }
    [XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Envelope
    {
        public Header Header { get; set; }
        public Body Body { get; set; }
    }
    public class Header
    {

    }
    public class Body
    {
        [XmlArray("cuis", Namespace = "https://siat.in.com/")]
        [XmlArrayItem("SolicitudCuis", Namespace = "")]
        public List<Cuis> Cuis { get; set; }

    }
    public class Cuis
    {
        public int codigoAmbiente { get; set; }
        public int codigoModalidad { get; set; }
        public int codigoPuntoVenta { get; set; }
        public string codigoSistema { get; set; }
        public int acodigoSucursal { get; set; }
        public long nit { get; set; }

    }

}
</code>```

Title: Create C# Class to fit XML file

Body:
Try following :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApp1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);
            XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
            Envelope envelope = (Envelope)serializer.Deserialize(reader);
        }
    }
    [XmlRoot(ElementName = "Envelope", Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
    public class Envelope
    {
        public Header Header { get; set; }
        public Body Body { get; set; }
    }
    public class Header
    {

    }
    public class Body
    {
        [XmlArray("cuis", Namespace = "https://siat.in.com/")]
        [XmlArrayItem("SolicitudCuis", Namespace = "")]
        public List<Cuis> Cuis { get; set; }

    }
    public class Cuis
    {
        public int codigoAmbiente { get; set; }
        public int codigoModalidad { get; set; }
        public int codigoPuntoVenta { get; set; }
        public string codigoSistema { get; set; }
        public int acodigoSucursal { get; set; }
        public long nit { get; set; }

    }

}


问:
Drawing instances with WebGL2 - vertexAttribDivisor
I'm learning webgl2 from https://webgl2fundamentals.org. I'm learning about instancing right now. I can get the demo to work, where it draws many crosses, and I can get it to work with 500 instances.

But I cannot add anything else to the scene. I have a simple triangle that renders fine without the instancing, but with the crosses added the triangle disappears. I believe it has to do with gl.vertexAttribDivisor. I'm not sure when I need to call it, or if I need to undo it somehow.

If I omit calls to vertexAttribDivisor, the crosses don't render correctly, but the triangle is fine. If I replace the call to vertexAttribDivisor, the triangle disappears.

When do I call gl.vertexAttribDivisor? Do I have to undo the call to resume normal, non-instanced rendering? What does it really do?

答: The vertex attribute functions change a single global state. vertexAttribDivisor sets the divisor for a specified generic vertex attribute (one of the globally available ones), for every draw* call you want to setup the attributes using vertexAttribPointer and vertexAttribDivisor, if you changed the divisor for an attribute for one draw call but don't want to use the same divisor for your following draw call you need to reset it.


问:
RFC 1738: URL: Must the host contain a dot?
According to RFC 1738: Uniform Resource Locators (URL): 3.1. Common Internet Scheme Syntax, must the host component contain a dot, e.g., "example.com"? I.e., may it be composed of only one domain label?</p>

答:
No, the host doesn't have to contain a dot. I.e., yes, only one domain label is fine. Look at domain, subdomain and label ( https://www.rfc-editor.org/rfc/rfc1034#section-3.5 ):

```<code><domain> ::= <subdomain> | " "

<subdomain> ::= <label> | <subdomain> "." <label>

<label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]

<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>

<let-dig-hyp> ::= <let-dig> | "-"

<let-dig> ::= <letter> | <digit>

<letter> ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case

<digit> ::= any one of the ten digits 0 through 9
</code>```

This document is referenced from https://www.rfc-editor.org/rfc/rfc1738#section-3.1 to describe the host naming rules.

Body:
No, the host doesn't have to contain a dot. I.e., yes, only one domain label is fine. Look at domain, subdomain and label ( https://www.rfc-editor.org/rfc/rfc1034#section-3.5 ):

<domain> ::= <subdomain> | " "

<subdomain> ::= <label> | <subdomain> "." <label>

<label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]

<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>

<let-dig-hyp> ::= <let-dig> | "-"

<let-dig> ::= <letter> | <digit>

<letter> ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case

<digit> ::= any one of the ten digits 0 through 9

This document is referenced from https://www.rfc-editor.org/rfc/rfc1738#section-3.1 to describe the host naming rules.


问:
Group by using agg and count
I have the following group by in pandas

```<code>   df = df.groupby("pred_text1").agg({
        "rouge_score":"first","pred_text1":"first",
        "input_text":"first", "target_text":"first", "prefix":"first"})
</code>```

I want to have another columns which counts the number in each group (repetition of each pred_text)

I know that using transform('count') after groupby can add such a new column, but I still need agg function too.

答:
You can use pd.NamedAgg function. (Pandas 0.25+)

Code:

import pandas as pd

# A sample dataframe
df = pd.DataFrame({
        'pred_text1': [chr(ord('A')+i%3) for i in range(10)],
        'rouge_score': [chr(ord('A')+i%5) for i in range(10)],
        'input_text': [chr(ord('A')+i%7) for i in range(10)],
        'target_text': [chr(ord('A')+i%9) for i in range(10)],
        'prefix': [chr(ord('A')+i%11) for i in range(10)],
    })

# Aggregation
df = df.groupby("pred_text1").agg(
        rouge_score=pd.NamedAgg("rouge_score", "first"),
        pred_text1=pd.NamedAgg("pred_text1", "first"),
        input_text=pd.NamedAgg("input_text", "first"),
        target_text=pd.NamedAgg("target_text", "first"),
        prefix=pd.NamedAgg("prefix", "first"),
        pred_count=pd.NamedAgg("pred_text1", "count"),
    )
```

Input:

(index)
pred_text1
rouge_score
input_text
target_text
prefix

0
A
A
A
A
A

1
B
B
B
B
B

2
C
C
C
C
C

3
A
D
D
D
D

4
B
E
E
E
E

5
C
A
F
F
F

6
A
B
G
G
G

7
B
C
A
H
H

8
C
D
B
I
I

9
A
E
C
A
J

Output:

(index)
rouge_score
pred_text1
input_text
target_text
prefix
pred_count

A
A
A
A
A
A
4

B
B
B
B
B
B
3

C
C
C
C
C
C
3

Title: Group by using agg and count

Body:
I have the following group by in pandas

   df = df.groupby("pred_text1").agg({
        "rouge_score":"first","pred_text1":"first",
        "input_text":"first", "target_text":"first", "prefix":"first"})

I want to have another columns which counts the number in each group (repetition of each pred_text)

I know that using transform('count') after groupby can add such a new column, but I still need agg function too.

Body:
You can use pd.NamedAgg function. (Pandas 0.25+)

Code:

import pandas as pd

# A sample dataframe
df = pd.DataFrame({
        'pred_text1': [chr(ord('A')+i%3) for i in range(10)],
        'rouge_score': [chr(ord('A')+i%5) for i in range(10)],
        'input_text': [chr(ord('A')+i%7) for i in range(10)],
        'target_text': [chr(ord('A')+i%9) for i in range(10)],
        'prefix': [chr(ord('A')+i%11) for i in range(10)],
    })

# Aggregation
df = df.groupby("pred_text1").agg(
        rouge_score=pd.NamedAgg("rouge_score", "first"),
        pred_text1=pd.NamedAgg("pred_text1", "first"),
        input_text=pd.NamedAgg("input_text", "first"),
        target_text=pd.NamedAgg("target_text", "first"),
        prefix=pd.NamedAgg("prefix", "first"),
        pred_count=pd.NamedAgg("pred_text1", "count"),
    )

Input:

(index)
pred_text1
rouge_score
input_text
target_text
prefix

0
A
A
A
A
A

1
B
B
B
B
B

2
C
C
C
C
C

3
A
D
D
D
D

4
B
E
E
E
E

5
C
A
F
F
F

6
A
B
G
G
G

7
B
C
A
H
H

8
C
D
B
I
I

9
A
E
C
A
J

Output:

(index)
rouge_score
pred_text1
input_text
target_text
prefix
pred_count

A
A
A
A
A
A
4

B
B
B
B
B
B
3

C
C
C
C
C
C
3


问:
Demo Application to create Kafka Producer throws "Failed to construct kafka producer" error for java.lang.InstantiationException: null
I am writing a demo application to create a Kafka Producer. I created a topic and ran a producer and consumer on Kafka, it seems to be working. I am writing a spring application to create a producer.I'm passing the name as part of the call. When I go to "http://localhost:8080/kafka/publish/Peter",  I'm getting a whitelabel error "Failed to construct kafka producer". Please help.

The main application is:
SpringBootKafkaProducerApplication.java

```<code>package com.ranjana.demo.kafka.springbootkafkaproducer;

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

@SpringBootApplication
public class SpringBootKafkaProducerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootKafkaProducerApplication.class, args);
    }
}
</code>```

The model is :
User.java

```<code>package com.ranjana.demo.kafka.springbootkafkaproducer.model;

public class User {
    private String name;
    private String Department;
    private Long Salary;

    public User(String name, String department, Long salary) {
        this.name = name;
        Department = department;
        Salary = salary;
    }

    //Getters and setters

}

</code>```

The controller is UserResourse.java

```<code>package com.ranjana.demo.kafka.springbootkafkaproducer.resource;

import com.ranjana.demo.kafka.springbootkafkaproducer.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("kafka")
public class UserResource {
    @Autowired
    KafkaTemplate<String, User> kafkaTemplate;
    private static final String TOPIC = "demo_topic";

    @GetMapping("/publish/{name}")
    public String post(@PathVariable("name") final String name){
        kafkaTemplate.send(TOPIC, new User(name, "Technology", 12000L));
        return "Published Successfully";
    }
}

</code>```

There is also this configuration file:
KafkaConfiguration.java

```<code>package com.ranjana.demo.kafka.springbootkafkaproducer.config;

import com.ranjana.demo.kafka.springbootkafkaproducer.model.User;
import com.fasterxml.jackson.databind.JsonSerializer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaConfiguration {
    @Bean
    public ProducerFactory<String, User> producerFactory(){
        Map<String, Object> config = new HashMap<>();

        config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);

        return new DefaultKafkaProducerFactory<>(config);
    }

    @Bean
    public KafkaTemplate<String, User> kafkaTemplate(){
        return new KafkaTemplate<>(producerFactory());
    }
}

</code>```

My application.properties has:

```<code>server.port=8080
</code>```

The error on http://localhost:8080/kafka/publish/Peter is:

```<code>Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Aug 09 12:36:10 CDT 2019
There was an unexpected error (type=Internal Server Error, status=500).
Failed to construct kafka producer
</code>```

Also the console shows:

```"/Applications/IntelliJ IDEA.app/Contents/jbr/Contents/Home/bin/java" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=56874:/Applications/IntelliJ IDEA.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath /Users/ranjanasinha/ransinha/spring-boot-kafka-producer/target/classes:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter-web/2.1.7.RELEASE/spring-boot-starter-web-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter/2.1.7.RELEASE/spring-boot-starter-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot/2.1.7.RELEASE/spring-boot-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/2.1.7.RELEASE/spring-boot-autoconfigure-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter-logging/2.1.7.RELEASE/spring-boot-starter-logging-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar:/Users/ranjanasinha/.m2/repository/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar:/Users/ranjanasinha/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.11.2/log4j-to-slf4j-2.11.2.jar:/Users/ranjanasinha/.m2/repository/org/apache/logging/log4j/log4j-api/2.11.2/log4j-api-2.11.2.jar:/Users/ranjanasinha/.m2/repository/org/slf4j/jul-to-slf4j/1.7.26/jul-to-slf4j-1.7.26.jar:/Users/ranjanasinha/.m2/repository/javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1.3.2.jar:/Users/ranjanasinha/.m2/repository/org/yaml/snakeyaml/1.23/snakeyaml-1.23.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter-json/2.1.7.RELEASE/spring-boot-starter-json-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.9.9/jackson-databind-2.9.9.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.9.0/jackson-annotations-2.9.0.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.9.9/jackson-core-2.9.9.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.9.9/jackson-datatype-jdk8-2.9.9.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.9.9/jackson-datatype-jsr310-2.9.9.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/module/jackson-module-parameter-names/2.9.9/jackson-module-parameter-names-2.9.9.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/2.1.7.RELEASE/spring-boot-starter-tomcat-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.22/tomcat-embed-core-9.0.22.jar:/Users/ranjanasinha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/9.0.22/tomcat-embed-el-9.0.22.jar:/Users/ranjanasinha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/9.0.22/tomcat-embed-websocket-9.0.22.jar:/Users/ranjanasinha/.m2/repository/org/hibernate/validator/hibernate-validator/6.0.17.Final/hibernate-validator-6.0.17.Final.jar:/Users/ranjanasinha/.m2/repository/javax/validation/validation-api/2.0.1.Final/validation-api-2.0.1.Final.jar:/Users/ranjanasinha/.m2/repository/org/jboss/logging/jboss-logging/3.3.2.Final/jboss-logging-3.3.2.Final.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/classmate/1.4.0/classmate-1.4.0.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-web/5.1.9.RELEASE/spring-web-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-beans/5.1.9.RELEASE/spring-beans-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-webmvc/5.1.9.RELEASE/spring-webmvc-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-aop/5.1.9.RELEASE/spring-aop-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-expression/5.1.9.RELEASE/spring-expression-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/kafka/spring-kafka/2.2.8.RELEASE/spring-kafka-2.2.8.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-context/5.1.9.RELEASE/spring-context-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-messaging/5.1.9.RELEASE/spring-messaging-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-tx/5.1.9.RELEASE/spring-tx-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/retry/spring-retry/1.2.4.RELEASE/spring-retry-1.2.4.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/apache/kafka/kafka-clients/2.0.1/kafka-clients-2.0.1.jar:/Users/ranjanasinha/.m2/repository/org/lz4/lz4-java/1.4.1/lz4-java-1.4.1.jar:/Users/ranjanasinha/.m2/repository/org/xerial/snappy/snappy-java/1.1.7.1/snappy-java-1.1.7.1.jar:/Users/ranjanasinha/.m2/repository/org/slf4j/slf4j-api/1.7.26/slf4j-api-1.7.26.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-core/5.1.9.RELEASE/spring-core-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-jcl/5.1.9.RELEASE/spring-jcl-5.1.9.RELEASE.jar com.ranjana.demo.kafka.springbootkafkaproducer.SpringBootKafkaProducerApplication

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.7.RELEASE)

2019-08-09 12:50:39.250  INFO 14006 --- [           main] d.k.s.SpringBootKafkaProducerApplication : Starting SpringBootKafkaProducerApplication on Egens-MacBook-Pro.local with PID 14006 (/Users/ranjanasinha/ransinha/spring-boot-kafka-producer/target/classes started by ranjanasinha in /Users/ranjanasinha/ransinha/spring-boot-kafka-producer)
2019-08-09 12:50:39.252  INFO 14006 --- [           main] d.k.s.SpringBootKafkaProducerApplication : No active profile set, falling back to default profiles: default
2019-08-09 12:50:39.776  INFO 14006 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.kafka.annotation.KafkaBootstrapConfiguration' of type [org.springframework.kafka.annotation.KafkaBootstrapConfiguration$$EnhancerBySpringCGLIB$$62e8d338] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-08-09 12:50:39.964  INFO 14006 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-08-09 12:50:39.985  INFO 14006 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-08-09 12:50:39.985  INFO 14006 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-08-09 12:50:40.044  INFO 14006 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-08-09 12:50:40.044  INFO 14006 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 755 ms
2019-08-09 12:50:40.235  INFO 14006 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-08-09 12:50:40.410  INFO 14006 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-08-09 12:50:40.415  INFO 14006 --- [           main] d.k.s.SpringBootKafkaProducerApplication : Started SpringBootKafkaProducerApplication in 1.383 seconds (JVM running for 6.925)
2019-08-09 12:50:50.531  INFO 14006 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-08-09 12:50:50.531  INFO 14006 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-08-09 12:50:50.536  INFO 14006 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2019-08-09 12:50:50.565  INFO 14006 --- [nio-8080-exec-1] o.a.k.clients.producer.ProducerConfig    : ProducerConfig values:
    acks = 1
    batch.size = 16384
    bootstrap.servers = [127.0.0.1:9092]
    buffer.memory = 33554432
    client.id =
    compression.type = none
    connections.max.idle.ms = 540000
    enable.idempotence = false
    interceptor.classes = []
    key.serializer = class org.apache.kafka.common.serialization.StringSerializer
    linger.ms = 0
    max.block.ms = 60000
    max.in.flight.requests.per.connection = 5
    max.request.size = 1048576
    metadata.max.age.ms = 300000
    metric.reporters = []
    metrics.num.samples = 2
    metrics.recording.level = INFO
    metrics.sample.window.ms = 30000
    partitioner.class = class org.apache.kafka.clients.producer.internals.DefaultPartitioner
    receive.buffer.bytes = 32768
    reconnect.backoff.max.ms = 1000
    reconnect.backoff.ms = 50
    request.timeout.ms = 30000
    retries = 0
    retry.backoff.ms = 100
    sasl.client.callback.handler.class = null
    sasl.jaas.config = null
    sasl.kerberos.kinit.cmd = /usr/bin/kinit
    sasl.kerberos.min.time.before.relogin = 60000
    sasl.kerberos.service.name = null
    sasl.kerberos.ticket.renew.jitter = 0.05
    sasl.kerberos.ticket.renew.window.factor = 0.8
    sasl.login.callback.handler.class = null
    sasl.login.class = null
    sasl.login.refresh.buffer.seconds = 300
    sasl.login.refresh.min.period.seconds = 60
    sasl.login.refresh.window.factor = 0.8
    sasl.login.refresh.window.jitter = 0.05
    sasl.mechanism = GSSAPI
    security.protocol = PLAINTEXT
    send.buffer.bytes = 131072
    ssl.cipher.suites = null
    ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
    ssl.endpoint.identification.algorithm = https
    ssl.key.password = null
    ssl.keymanager.algorithm = SunX509
    ssl.keystore.location = null
    ssl.keystore.password = null
    ssl.keystore.type = JKS
    ssl.protocol = TLS
    ssl.provider = null
    ssl.secure.random.implementation = null
    ssl.trustmanager.algorithm = PKIX
    ssl.truststore.location = null
    ssl.truststore.password = null
    ssl.truststore.type = JKS
    transaction.timeout.ms = 60000
    transactional.id = null
    value.serializer = class com.fasterxml.jackson.databind.JsonSerializer

2019-08-09 12:50:50.572  INFO 14006 --- [nio-8080-exec-1] o.a.k.clients.producer.KafkaProducer     : [Producer clientId=producer-1] Closing the Kafka producer with timeoutMillis = 0 ms.
2019-08-09 12:50:50.581 ERROR 14006 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.kafka.common.KafkaException: Failed to construct kafka producer] with root cause

java.lang.InstantiationException: null
    at java.base/jdk.internal.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48) ~[na:na]
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) ~[na:na]
    at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:306) ~[kafka-clients-2.0.1.jar:na]
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:302) ~[kafka-clients-2.0.1.jar:na]
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:370) ~[kafka-clients-2.0.1.jar:na]
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:289) ~[kafka-clients-2.0.1.jar:na]
    at org.springframework.kafka.core.DefaultKafkaProducerFactory.createKafkaProducer(DefaultKafkaProducerFactory.java:318) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at org.springframework.kafka.core.DefaultKafkaProducerFactory.createProducer(DefaultKafkaProducerFactory.java:305) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at org.springframework.kafka.core.KafkaTemplate.getTheProducer(KafkaTemplate.java:448) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at org.springframework.kafka.core.KafkaTemplate.doSend(KafkaTemplate.java:378) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at org.springframework.kafka.core.KafkaTemplate.send(KafkaTemplate.java:193) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at com.ranjana.demo.kafka.springbootkafkaproducer.resource.UserResource.post(UserResource.java:32) ~[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.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    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.22.jar:9.0.22]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

```

<p>And the pom.xml is:</p>

```<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.egen.demo.kafka</groupId>
    <artifactId>spring-boot-kafka-producer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-kafka-producer</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

```

答:
I have gone through this issue once I started learning Kafka

What is the issue here:
Wrong JsonSerializer class has been imported by the IDE.

What to Do:
When ever you are constructing object ProducerFactory, make sure that you are importing correct class file. In this case, when you write JsonSerializer.class then by default IDE may pick wrong classes hence we need to correct JsonSerializer.class

so import of JsonSerializer.class in this as below config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);

and it must be  org.springframework.kafka.support.serializer.JsonSerializer instead of com.fasterxml.jackson.databind.JsonSerializer

Happy Coding!!

Body:
I am writing a demo application to create a Kafka Producer. I created a topic and ran a producer and consumer on Kafka, it seems to be working. I am writing a spring application to create a producer.I'm passing the name as part of the call. When I go to "http://localhost:8080/kafka/publish/Peter",  I'm getting a whitelabel error "Failed to construct kafka producer". Please help.

The main application is:
SpringBootKafkaProducerApplication.java

package com.ranjana.demo.kafka.springbootkafkaproducer;

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

@SpringBootApplication
public class SpringBootKafkaProducerApplication {

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

The model is :
User.java

package com.ranjana.demo.kafka.springbootkafkaproducer.model;

public class User {
    private String name;
    private String Department;
    private Long Salary;

    public User(String name, String department, Long salary) {
        this.name = name;
        Department = department;
        Salary = salary;
    }

    //Getters and setters

}

The controller is UserResourse.java

package com.ranjana.demo.kafka.springbootkafkaproducer.resource;

import com.ranjana.demo.kafka.springbootkafkaproducer.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("kafka")
public class UserResource {
    @Autowired
    KafkaTemplate<String, User> kafkaTemplate;
    private static final String TOPIC = "demo_topic";

    @GetMapping("/publish/{name}")
    public String post(@PathVariable("name") final String name){
        kafkaTemplate.send(TOPIC, new User(name, "Technology", 12000L));
        return "Published Successfully";
    }
}

There is also this configuration file:
KafkaConfiguration.java

package com.ranjana.demo.kafka.springbootkafkaproducer.config;

import com.ranjana.demo.kafka.springbootkafkaproducer.model.User;
import com.fasterxml.jackson.databind.JsonSerializer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class KafkaConfiguration {
    @Bean
    public ProducerFactory<String, User> producerFactory(){
        Map<String, Object> config = new HashMap<>();

        config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "127.0.0.1:9092");
        config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);

        return new DefaultKafkaProducerFactory<>(config);
    }

    @Bean
    public KafkaTemplate<String, User> kafkaTemplate(){
        return new KafkaTemplate<>(producerFactory());
    }
}

My application.properties has:

server.port=8080

The error on http://localhost:8080/kafka/publish/Peter is:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri Aug 09 12:36:10 CDT 2019
There was an unexpected error (type=Internal Server Error, status=500).
Failed to construct kafka producer

Also the console shows:

"/Applications/IntelliJ IDEA.app/Contents/jbr/Contents/Home/bin/java" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=56874:/Applications/IntelliJ IDEA.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath /Users/ranjanasinha/ransinha/spring-boot-kafka-producer/target/classes:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter-web/2.1.7.RELEASE/spring-boot-starter-web-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter/2.1.7.RELEASE/spring-boot-starter-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot/2.1.7.RELEASE/spring-boot-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-autoconfigure/2.1.7.RELEASE/spring-boot-autoconfigure-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter-logging/2.1.7.RELEASE/spring-boot-starter-logging-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/ch/qos/logback/logback-classic/1.2.3/logback-classic-1.2.3.jar:/Users/ranjanasinha/.m2/repository/ch/qos/logback/logback-core/1.2.3/logback-core-1.2.3.jar:/Users/ranjanasinha/.m2/repository/org/apache/logging/log4j/log4j-to-slf4j/2.11.2/log4j-to-slf4j-2.11.2.jar:/Users/ranjanasinha/.m2/repository/org/apache/logging/log4j/log4j-api/2.11.2/log4j-api-2.11.2.jar:/Users/ranjanasinha/.m2/repository/org/slf4j/jul-to-slf4j/1.7.26/jul-to-slf4j-1.7.26.jar:/Users/ranjanasinha/.m2/repository/javax/annotation/javax.annotation-api/1.3.2/javax.annotation-api-1.3.2.jar:/Users/ranjanasinha/.m2/repository/org/yaml/snakeyaml/1.23/snakeyaml-1.23.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter-json/2.1.7.RELEASE/spring-boot-starter-json-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.9.9/jackson-databind-2.9.9.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/core/jackson-annotations/2.9.0/jackson-annotations-2.9.0.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.9.9/jackson-core-2.9.9.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jdk8/2.9.9/jackson-datatype-jdk8-2.9.9.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/datatype/jackson-datatype-jsr310/2.9.9/jackson-datatype-jsr310-2.9.9.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/jackson/module/jackson-module-parameter-names/2.9.9/jackson-module-parameter-names-2.9.9.jar:/Users/ranjanasinha/.m2/repository/org/springframework/boot/spring-boot-starter-tomcat/2.1.7.RELEASE/spring-boot-starter-tomcat-2.1.7.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.22/tomcat-embed-core-9.0.22.jar:/Users/ranjanasinha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-el/9.0.22/tomcat-embed-el-9.0.22.jar:/Users/ranjanasinha/.m2/repository/org/apache/tomcat/embed/tomcat-embed-websocket/9.0.22/tomcat-embed-websocket-9.0.22.jar:/Users/ranjanasinha/.m2/repository/org/hibernate/validator/hibernate-validator/6.0.17.Final/hibernate-validator-6.0.17.Final.jar:/Users/ranjanasinha/.m2/repository/javax/validation/validation-api/2.0.1.Final/validation-api-2.0.1.Final.jar:/Users/ranjanasinha/.m2/repository/org/jboss/logging/jboss-logging/3.3.2.Final/jboss-logging-3.3.2.Final.jar:/Users/ranjanasinha/.m2/repository/com/fasterxml/classmate/1.4.0/classmate-1.4.0.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-web/5.1.9.RELEASE/spring-web-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-beans/5.1.9.RELEASE/spring-beans-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-webmvc/5.1.9.RELEASE/spring-webmvc-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-aop/5.1.9.RELEASE/spring-aop-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-expression/5.1.9.RELEASE/spring-expression-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/kafka/spring-kafka/2.2.8.RELEASE/spring-kafka-2.2.8.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-context/5.1.9.RELEASE/spring-context-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-messaging/5.1.9.RELEASE/spring-messaging-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-tx/5.1.9.RELEASE/spring-tx-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/retry/spring-retry/1.2.4.RELEASE/spring-retry-1.2.4.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/apache/kafka/kafka-clients/2.0.1/kafka-clients-2.0.1.jar:/Users/ranjanasinha/.m2/repository/org/lz4/lz4-java/1.4.1/lz4-java-1.4.1.jar:/Users/ranjanasinha/.m2/repository/org/xerial/snappy/snappy-java/1.1.7.1/snappy-java-1.1.7.1.jar:/Users/ranjanasinha/.m2/repository/org/slf4j/slf4j-api/1.7.26/slf4j-api-1.7.26.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-core/5.1.9.RELEASE/spring-core-5.1.9.RELEASE.jar:/Users/ranjanasinha/.m2/repository/org/springframework/spring-jcl/5.1.9.RELEASE/spring-jcl-5.1.9.RELEASE.jar com.ranjana.demo.kafka.springbootkafkaproducer.SpringBootKafkaProducerApplication

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.7.RELEASE)

2019-08-09 12:50:39.250  INFO 14006 --- [           main] d.k.s.SpringBootKafkaProducerApplication : Starting SpringBootKafkaProducerApplication on Egens-MacBook-Pro.local with PID 14006 (/Users/ranjanasinha/ransinha/spring-boot-kafka-producer/target/classes started by ranjanasinha in /Users/ranjanasinha/ransinha/spring-boot-kafka-producer)
2019-08-09 12:50:39.252  INFO 14006 --- [           main] d.k.s.SpringBootKafkaProducerApplication : No active profile set, falling back to default profiles: default
2019-08-09 12:50:39.776  INFO 14006 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.kafka.annotation.KafkaBootstrapConfiguration' of type [org.springframework.kafka.annotation.KafkaBootstrapConfiguration$$EnhancerBySpringCGLIB$$62e8d338] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-08-09 12:50:39.964  INFO 14006 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-08-09 12:50:39.985  INFO 14006 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-08-09 12:50:39.985  INFO 14006 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-08-09 12:50:40.044  INFO 14006 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-08-09 12:50:40.044  INFO 14006 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 755 ms
2019-08-09 12:50:40.235  INFO 14006 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-08-09 12:50:40.410  INFO 14006 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-08-09 12:50:40.415  INFO 14006 --- [           main] d.k.s.SpringBootKafkaProducerApplication : Started SpringBootKafkaProducerApplication in 1.383 seconds (JVM running for 6.925)
2019-08-09 12:50:50.531  INFO 14006 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2019-08-09 12:50:50.531  INFO 14006 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2019-08-09 12:50:50.536  INFO 14006 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 5 ms
2019-08-09 12:50:50.565  INFO 14006 --- [nio-8080-exec-1] o.a.k.clients.producer.ProducerConfig    : ProducerConfig values:
    acks = 1
    batch.size = 16384
    bootstrap.servers = [127.0.0.1:9092]
    buffer.memory = 33554432
    client.id =
    compression.type = none
    connections.max.idle.ms = 540000
    enable.idempotence = false
    interceptor.classes = []
    key.serializer = class org.apache.kafka.common.serialization.StringSerializer
    linger.ms = 0
    max.block.ms = 60000
    max.in.flight.requests.per.connection = 5
    max.request.size = 1048576
    metadata.max.age.ms = 300000
    metric.reporters = []
    metrics.num.samples = 2
    metrics.recording.level = INFO
    metrics.sample.window.ms = 30000
    partitioner.class = class org.apache.kafka.clients.producer.internals.DefaultPartitioner
    receive.buffer.bytes = 32768
    reconnect.backoff.max.ms = 1000
    reconnect.backoff.ms = 50
    request.timeout.ms = 30000
    retries = 0
    retry.backoff.ms = 100
    sasl.client.callback.handler.class = null
    sasl.jaas.config = null
    sasl.kerberos.kinit.cmd = /usr/bin/kinit
    sasl.kerberos.min.time.before.relogin = 60000
    sasl.kerberos.service.name = null
    sasl.kerberos.ticket.renew.jitter = 0.05
    sasl.kerberos.ticket.renew.window.factor = 0.8
    sasl.login.callback.handler.class = null
    sasl.login.class = null
    sasl.login.refresh.buffer.seconds = 300
    sasl.login.refresh.min.period.seconds = 60
    sasl.login.refresh.window.factor = 0.8
    sasl.login.refresh.window.jitter = 0.05
    sasl.mechanism = GSSAPI
    security.protocol = PLAINTEXT
    send.buffer.bytes = 131072
    ssl.cipher.suites = null
    ssl.enabled.protocols = [TLSv1.2, TLSv1.1, TLSv1]
    ssl.endpoint.identification.algorithm = https
    ssl.key.password = null
    ssl.keymanager.algorithm = SunX509
    ssl.keystore.location = null
    ssl.keystore.password = null
    ssl.keystore.type = JKS
    ssl.protocol = TLS
    ssl.provider = null
    ssl.secure.random.implementation = null
    ssl.trustmanager.algorithm = PKIX
    ssl.truststore.location = null
    ssl.truststore.password = null
    ssl.truststore.type = JKS
    transaction.timeout.ms = 60000
    transactional.id = null
    value.serializer = class com.fasterxml.jackson.databind.JsonSerializer

2019-08-09 12:50:50.572  INFO 14006 --- [nio-8080-exec-1] o.a.k.clients.producer.KafkaProducer     : [Producer clientId=producer-1] Closing the Kafka producer with timeoutMillis = 0 ms.
2019-08-09 12:50:50.581 ERROR 14006 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.apache.kafka.common.KafkaException: Failed to construct kafka producer] with root cause

java.lang.InstantiationException: null
    at java.base/jdk.internal.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:48) ~[na:na]
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) ~[na:na]
    at org.apache.kafka.common.utils.Utils.newInstance(Utils.java:306) ~[kafka-clients-2.0.1.jar:na]
    at org.apache.kafka.common.config.AbstractConfig.getConfiguredInstance(AbstractConfig.java:302) ~[kafka-clients-2.0.1.jar:na]
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:370) ~[kafka-clients-2.0.1.jar:na]
    at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:289) ~[kafka-clients-2.0.1.jar:na]
    at org.springframework.kafka.core.DefaultKafkaProducerFactory.createKafkaProducer(DefaultKafkaProducerFactory.java:318) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at org.springframework.kafka.core.DefaultKafkaProducerFactory.createProducer(DefaultKafkaProducerFactory.java:305) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at org.springframework.kafka.core.KafkaTemplate.getTheProducer(KafkaTemplate.java:448) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at org.springframework.kafka.core.KafkaTemplate.doSend(KafkaTemplate.java:378) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at org.springframework.kafka.core.KafkaTemplate.send(KafkaTemplate.java:193) ~[spring-kafka-2.2.8.RELEASE.jar:2.2.8.RELEASE]
    at com.ranjana.demo.kafka.springbootkafkaproducer.resource.UserResource.post(UserResource.java:32) ~[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.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) ~[spring-webmvc-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118) ~[spring-web-5.1.9.RELEASE.jar:5.1.9.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.22.jar:9.0.22]
    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.22.jar:9.0.22]
    at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]

And the pom.xml is:

<?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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.egen.demo.kafka</groupId>
    <artifactId>spring-boot-kafka-producer</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-kafka-producer</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>