问:
Error while sending a post request with Postman with an Entity having foreign keys
I am getting an error while sending a post request through postman, I have researched about, i have changed a lot of thing with no result at the end.

This is my questions entity, which has 2 foreign keys (From Categorias (Categories) and subcategorias (Subcategories):

```<code>
@Entity
@Table(name="preguntas")
public class Preguntas implements Serializable{

    private static final long serialVersionUID = -4130402068975218733L;

    @Id
    @GeneratedValue( strategy=GenerationType.IDENTITY )
    private Long id;

    private String titulo;
    private String respuesta1;
    private String respuesta2;
    private String respuesta3;
    private String respuesta4;
    private String justificacion;

    @Column(name = "respuesta_correcta")
    private int respuestaCorrecta;

    @ManyToOne
    @JoinColumn(name="id_subcategoria")
    private Subcategorias subcategorias;

    @ManyToOne
    @JoinColumn(name="id_categoria")
    private Categorias categorias;

    public Preguntas() {
    }

    public Subcategorias getSubcategorias() {
        return subcategorias;
    }

    public void setSubcategorias(Subcategorias subcategorias) {
        this.subcategorias = subcategorias;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getRespuesta1() {
        return respuesta1;
    }

    public void setRespuesta1(String respuesta1) {
        this.respuesta1 = respuesta1;
    }

    public String getRespuesta2() {
        return respuesta2;
    }

    public void setRespuesta2(String respuesta2) {
        this.respuesta2 = respuesta2;
    }

    public String getRespuesta3() {
        return respuesta3;
    }

    public void setRespuesta3(String respuesta3) {
        this.respuesta3 = respuesta3;
    }

    public String getRespuesta4() {
        return respuesta4;
    }

    public void setRespuesta4(String respuesta4) {
        this.respuesta4 = respuesta4;
    }

    public String getJustificacion() {
        return justificacion;
    }

    public void setJustificacion(String justificacion) {
        this.justificacion = justificacion;
    }

    public int getRespuestaCorrecta() {
        return respuestaCorrecta;
    }

    public void setRespuestaCorrecta(int respuestaCorrecta) {
        this.respuestaCorrecta = respuestaCorrecta;
    }

    public Subcategorias getSubcategoria() {
        return subcategorias;
    }

    public void setSubcategoria(Subcategorias subcategoria) {
        this.subcategorias = subcategoria;
    }

    public Categorias getCategorias() {
        return categorias;
    }

    public void setCategorias(Categorias categorias) {
        this.categorias = categorias;
    }

}

</code>```

Categories Entity:

```<code>@Entity
@Table(name="categorias")
public class Categorias implements Serializable{

    private static final long serialVersionUID = -2567387680313546345L;
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique=true, nullable=false)
    private String nombre;

    @Column(name="role_usuario")
    private int roleUsuario;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(
            name = "cat_subcat",
            joinColumns = { @JoinColumn( name="id_categoria")},
            inverseJoinColumns = {@JoinColumn(name="id_subcategoria")}
    )
    private List<Subcategorias> subcategorias = new ArrayList<>();

    @OneToMany(cascade = CascadeType.ALL, mappedBy="categorias")
    private List<Preguntas> preguntas = new ArrayList<>();

    public Categorias() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public int getRoleUsuario() {
        return roleUsuario;
    }

    public void setRoleUsuario(int roleUsuario) {
        this.roleUsuario = roleUsuario;
    }

    public List<Subcategorias> getSubcategorias() {
        return subcategorias;
    }

    public void setSubcategorias(List<Subcategorias> subcategorias) {
        this.subcategorias = subcategorias;
    }

    public List<Preguntas> getPreguntas() {
        return preguntas;
    }

    public void setPreguntas(List<Preguntas> preguntas) {
        this.preguntas = preguntas;
    }

}

</code>```

Subcategories entity

```<code>
@Entity
@Table(name = "subcategorias")
public class Subcategorias implements Serializable{

    private static final long serialVersionUID = -4917888214737637470L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique=true, nullable=false)
    private String nombre;

    @ManyToMany(mappedBy="subcategorias")
    private List<Categorias> categorias = new ArrayList<>();

    @OneToMany( cascade = CascadeType.ALL, mappedBy="subcategorias" )
    private List<Preguntas> preguntas = new ArrayList<>();

    public Subcategorias() {
    }

    public List<Categorias> getCategorias() {
        return categorias;
    }

    public void setCategorias(List<Categorias> categorias) {
        this.categorias = categorias;
    }

    public List<Preguntas> getPreguntas() {
        return preguntas;
    }

    public void setPreguntas(List<Preguntas> preguntas) {
        this.preguntas = preguntas;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
}

</code>```

Controller "Preguntas"

```<code>@PostMapping
public ResponseEntity<String> CrearPreguntas( @RequestBody Preguntas preguntas) {

    preguntasService.save(preguntas);

    return new ResponseEntity<>("Pregunta creada correctamente.",HttpStatus.OK);

}
</code>```

This is the request (Through body, with json format) I am sending to localhost:8080/api/preguntas/

```<code>{
    "justificacion":"la justificacion",
    "respuesta1": "resp1",
    "respuesta2": "resp2",
    "respuesta3": "resp3",
    "respuesta4": "resp4",
    "respuestaCorrecta":"1",
    "titulo": "titulo1",
    "categorias":{
        "id_categoria":"1"
    },
    "subcategorias":{
        "id_subcategoria":"1"
    }
}

</code>```

Error I am getting:

```<code>"timestamp": "2022-12-20T08:52:23.788+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:270)\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)\r\n\tat org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:550)\r\n\tat org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:163)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:218)\r\n\tat jdk.proxy4/jdk.proxy4.$Proxy118.save(Unknown Source)\r\n\tat com.espina.services.PreguntasServiceImpl.save(PreguntasServiceImpl.java:45)\r\n\tat com.espina.controller.PreguntasController.CrearPreguntas(PreguntasController.java:29)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1003)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:906)\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:880)\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\nCaused by: org.hibernate.exception.ConstraintViolationException: could not execute statement\r\n\tat org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:60)\r\n\tat org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:56)\r\n\tat org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)\r\n\tat org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)\r\n\tat org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)\r\n\tat org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)\r\n\tat org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)\r\n\tat org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3288)\r\n\tat org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3898)\r\n\tat org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:80)\r\n\tat org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:653)\r\n\tat org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:283)\r\n\tat org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:264)\r\n\tat org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:322)\r\n\tat org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:340)\r\n\tat org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)\r\n\tat org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)\r\n\tat org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)\r\n\tat org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:184)\r\n\tat org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:129)\r\n\tat org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:53)\r\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\r\n\tat org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:735)\r\n\tat org.hibernate.internal.SessionImpl.persist(SessionImpl.java:719)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:360)\r\n\tat jdk.proxy4/jdk.proxy4.$Proxy110.persist(Unknown Source)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:307)\r\n\tat jdk.proxy4/jdk.proxy4.$Proxy110.persist(Unknown Source)\r\n\tat org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:610)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:288)\r\n\tat org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:136)\r\n\tat org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:120)\r\n\tat org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:516)\r\n\tat org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:628)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:168)\r\n\tat org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:143)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:77)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)\r\n\tat org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)\r\n\tat org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)\r\n\t... 59 more\r\nCaused by: java.sql.SQLIntegrityConstraintViolationException: Column 'id_categoria' cannot be null\r\n\tat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)\r\n\tat com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1009)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1320)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:994)\r\n\tat com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)\r\n\tat com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)\r\n\tat org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)\r\n\t... 112 more\r\n",
    "message": "could not execute statement; SQL [n/a]; constraint [null]",
    "path": "/api/preguntas/"

</code>```

I am doing a delete request in the same entity and it is working fine,

Body:
I am getting an error while sending a post request through postman, I have researched about, i have changed a lot of thing with no result at the end.

This is my questions entity, which has 2 foreign keys (From Categorias (Categories) and subcategorias (Subcategories):

@Entity
@Table(name="preguntas")
public class Preguntas implements Serializable{

    private static final long serialVersionUID = -4130402068975218733L;

    @Id
    @GeneratedValue( strategy=GenerationType.IDENTITY )
    private Long id;

    private String titulo;
    private String respuesta1;
    private String respuesta2;
    private String respuesta3;
    private String respuesta4;
    private String justificacion;

    @Column(name = "respuesta_correcta")
    private int respuestaCorrecta;

    @ManyToOne
    @JoinColumn(name="id_subcategoria")
    private Subcategorias subcategorias;

    @ManyToOne
    @JoinColumn(name="id_categoria")
    private Categorias categorias;

    public Preguntas() {
    }

    public Subcategorias getSubcategorias() {
        return subcategorias;
    }

    public void setSubcategorias(Subcategorias subcategorias) {
        this.subcategorias = subcategorias;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getRespuesta1() {
        return respuesta1;
    }

    public void setRespuesta1(String respuesta1) {
        this.respuesta1 = respuesta1;
    }

    public String getRespuesta2() {
        return respuesta2;
    }

    public void setRespuesta2(String respuesta2) {
        this.respuesta2 = respuesta2;
    }

    public String getRespuesta3() {
        return respuesta3;
    }

    public void setRespuesta3(String respuesta3) {
        this.respuesta3 = respuesta3;
    }

    public String getRespuesta4() {
        return respuesta4;
    }

    public void setRespuesta4(String respuesta4) {
        this.respuesta4 = respuesta4;
    }

    public String getJustificacion() {
        return justificacion;
    }

    public void setJustificacion(String justificacion) {
        this.justificacion = justificacion;
    }

    public int getRespuestaCorrecta() {
        return respuestaCorrecta;
    }

    public void setRespuestaCorrecta(int respuestaCorrecta) {
        this.respuestaCorrecta = respuestaCorrecta;
    }

    public Subcategorias getSubcategoria() {
        return subcategorias;
    }

    public void setSubcategoria(Subcategorias subcategoria) {
        this.subcategorias = subcategoria;
    }

    public Categorias getCategorias() {
        return categorias;
    }

    public void setCategorias(Categorias categorias) {
        this.categorias = categorias;
    }

}

Categories Entity:

@Entity
@Table(name="categorias")
public class Categorias implements Serializable{

    private static final long serialVersionUID = -2567387680313546345L;
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique=true, nullable=false)
    private String nombre;

    @Column(name="role_usuario")
    private int roleUsuario;

    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(
            name = "cat_subcat",
            joinColumns = { @JoinColumn( name="id_categoria")},
            inverseJoinColumns = {@JoinColumn(name="id_subcategoria")}
    )
    private List<Subcategorias> subcategorias = new ArrayList<>();

    @OneToMany(cascade = CascadeType.ALL, mappedBy="categorias")
    private List<Preguntas> preguntas = new ArrayList<>();

    public Categorias() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }

    public int getRoleUsuario() {
        return roleUsuario;
    }

    public void setRoleUsuario(int roleUsuario) {
        this.roleUsuario = roleUsuario;
    }

    public List<Subcategorias> getSubcategorias() {
        return subcategorias;
    }

    public void setSubcategorias(List<Subcategorias> subcategorias) {
        this.subcategorias = subcategorias;
    }

    public List<Preguntas> getPreguntas() {
        return preguntas;
    }

    public void setPreguntas(List<Preguntas> preguntas) {
        this.preguntas = preguntas;
    }

}

Subcategories entity

@Entity
@Table(name = "subcategorias")
public class Subcategorias implements Serializable{

    private static final long serialVersionUID = -4917888214737637470L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique=true, nullable=false)
    private String nombre;

    @ManyToMany(mappedBy="subcategorias")
    private List<Categorias> categorias = new ArrayList<>();

    @OneToMany( cascade = CascadeType.ALL, mappedBy="subcategorias" )
    private List<Preguntas> preguntas = new ArrayList<>();

    public Subcategorias() {
    }

    public List<Categorias> getCategorias() {
        return categorias;
    }

    public void setCategorias(List<Categorias> categorias) {
        this.categorias = categorias;
    }

    public List<Preguntas> getPreguntas() {
        return preguntas;
    }

    public void setPreguntas(List<Preguntas> preguntas) {
        this.preguntas = preguntas;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNombre() {
        return nombre;
    }

    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
}

Controller "Preguntas"

@PostMapping
public ResponseEntity<String> CrearPreguntas( @RequestBody Preguntas preguntas) {

    preguntasService.save(preguntas);

    return new ResponseEntity<>("Pregunta creada correctamente.",HttpStatus.OK);

}

This is the request (Through body, with json format) I am sending to localhost:8080/api/preguntas/

{
    "justificacion":"la justificacion",
    "respuesta1": "resp1",
    "respuesta2": "resp2",
    "respuesta3": "resp3",
    "respuesta4": "resp4",
    "respuestaCorrecta":"1",
    "titulo": "titulo1",
    "categorias":{
        "id_categoria":"1"
    },
    "subcategorias":{
        "id_subcategoria":"1"
    }
}

Error I am getting:

"timestamp": "2022-12-20T08:52:23.788+00:00",
    "status": 500,
    "error": "Internal Server Error",
    "trace": "org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:270)\r\n\tat org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233)\r\n\tat org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:550)\r\n\tat org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)\r\n\tat org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:163)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:218)\r\n\tat jdk.proxy4/jdk.proxy4.$Proxy118.save(Unknown Source)\r\n\tat com.espina.services.PreguntasServiceImpl.save(PreguntasServiceImpl.java:45)\r\n\tat com.espina.controller.PreguntasController.CrearPreguntas(PreguntasController.java:29)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1080)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1003)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:906)\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:731)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:880)\r\n\tat jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1739)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\nCaused by: org.hibernate.exception.ConstraintViolationException: could not execute statement\r\n\tat org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:60)\r\n\tat org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:56)\r\n\tat org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)\r\n\tat org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)\r\n\tat org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)\r\n\tat org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)\r\n\tat org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42)\r\n\tat org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3288)\r\n\tat org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3898)\r\n\tat org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:80)\r\n\tat org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:653)\r\n\tat org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:283)\r\n\tat org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:264)\r\n\tat org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:322)\r\n\tat org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:340)\r\n\tat org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:286)\r\n\tat org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:192)\r\n\tat org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:122)\r\n\tat org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:184)\r\n\tat org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:129)\r\n\tat org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:53)\r\n\tat org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)\r\n\tat org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:735)\r\n\tat org.hibernate.internal.SessionImpl.persist(SessionImpl.java:719)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:360)\r\n\tat jdk.proxy4/jdk.proxy4.$Proxy110.persist(Unknown Source)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:307)\r\n\tat jdk.proxy4/jdk.proxy4.$Proxy110.persist(Unknown Source)\r\n\tat org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:610)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.data.repository.core.support.RepositoryMethodInvoker$RepositoryFragmentMethodInvoker.lambda$new$0(RepositoryMethodInvoker.java:288)\r\n\tat org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:136)\r\n\tat org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:120)\r\n\tat org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:516)\r\n\tat org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:285)\r\n\tat org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:628)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:168)\r\n\tat org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:143)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:77)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123)\r\n\tat org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388)\r\n\tat org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119)\r\n\tat org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:184)\r\n\tat org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137)\r\n\t... 59 more\r\nCaused by: java.sql.SQLIntegrityConstraintViolationException: Column 'id_categoria' cannot be null\r\n\tat com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)\r\n\tat com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1009)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1320)\r\n\tat com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:994)\r\n\tat com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)\r\n\tat com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)\r\n\tat org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)\r\n\t... 112 more\r\n",
    "message": "could not execute statement; SQL [n/a]; constraint [null]",
    "path": "/api/preguntas/"

I am doing a delete request in the same entity and it is working fine,


来源: stackexchange

问:
React Native - use bottom sheet to navigate to screens in BottomTabNavigator
I want to make last Tab as Show More tab and when i clicked on it, bottom sheet open which has remaining tab. I can make bottom sheet, and it is working but how can i go to the screen on bottom sheet after clicking on it like by clicking on setting it take me to setting Screen.

Below is example that i need to achieve

ContentLicense: CC BY-SA 4.0


问:
with-nx.js: Octal escape sequences are not allowed in strict mode
I'm building my Next/NX application using an Azure build pipeline. The build is a success, but when starting the application, I get the following error:

```<code>SyntaxError: Octal escape sequences are not allowed in strict mode.
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (E:\xxx\dist\apps\launchpad-app\next.config.js:2:16)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)
</code>```

The problem is, that in the with-nx.js, the workspaceRoot is set incorrectly, as the path is not correctly escaped:

```<code>function getWithNxContext() {
return {
workspaceRoot: 'D:\a\1\s',
libsDir: 'libs'
}
</code>```

D:\a\1\s should have been D:\\a\\1\\s

How do I ensure that the workspaceroot is escaped correctly?

.yml build file is:

```<code>trigger:
- master

pool:
  vmImage: 'windows-2022'

steps:
- task: NodeTool@0
  inputs:
    versionSpec: '18.x'
  displayName: 'Install Node.js'

- powershell: |
    npm install
    npm ci
    npm run buildprod
  displayName: 'Build application'

</code>```

Buildprod is this command:

"buildprod": "nx run app:build:production --skip-nx-cache",

Body:
I'm building my Next/NX application using an Azure build pipeline. The build is a success, but when starting the application, I get the following error:

SyntaxError: Octal escape sequences are not allowed in strict mode.
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Module.require (node:internal/modules/cjs/loader:1061:19)
    at require (node:internal/modules/cjs/helpers:103:18)
    at Object.<anonymous> (E:\xxx\dist\apps\launchpad-app\next.config.js:2:16)
    at Module._compile (node:internal/modules/cjs/loader:1159:14)

The problem is, that in the with-nx.js, the workspaceRoot is set incorrectly, as the path is not correctly escaped:

function getWithNxContext() {
return {
workspaceRoot: 'D:\a\1\s',
libsDir: 'libs'
}

D:\a\1\s should have been D:\\a\\1\\s

How do I ensure that the workspaceroot is escaped correctly?

.yml build file is:

trigger:
- master

pool:
  vmImage: 'windows-2022'

steps:
- task: NodeTool@0
  inputs:
    versionSpec: '18.x'
  displayName: 'Install Node.js'

- powershell: |
    npm install
    npm ci
    npm run buildprod
  displayName: 'Build application'

Buildprod is this command:

"buildprod": "nx run app:build:production --skip-nx-cache",


问:
Why does my code update a random row instead of one I specified?
I'm working on a project and I'm stuck on a moment and I can maybe use some help from you guys.

I'm running a while loop and in the while loop I'm using a button. I want to update that specific row of the button.

But at my code now, it updates a row randomly.

This is my code:

<form name="faturalar" method="POST">

 Ödenmemiş Faturalarım

         #
         Ceza
         Miktar
         Ödeme

    <?php
        $count=1;
        $sel_query="SELECT * from billing WHERE identifier= '{$cid}';";
        $result = mysqli_query($svcon,$sel_query);
        while($row = mysqli_fetch_assoc($result)) {
        $fatMiktar = $row["amount"];
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            if (isset($_POST['odeme'])) {
                $yeniMiktar = $BankaAl - $fatMiktar;
                $yeniAccount = array("bank"=>$yeniMiktar, "money"=>$NakitAl, "black_money"=>$BlackAl);
                $bankEncode = json_encode($yeniAccount);

                $up = "UPDATE users set accounts = '$bankEncode' WHERE id = '{$cid}'";

                $upresult = $svcon->query($up);
                $uprow = mysqli_fetch_array($upresult);
                header("Refresh:0");
            }
        }

    ?>

<?php echo $count; ?>	<?php echo $row["label"]; ?>	<?php echo $row["amount"]; ?>	<input name="odeme" type="submit" value="Öde" class="btn btn-primary">

    <?php $count++; } ?>

</form>

```

I searched on stackoverflow but I didn't find any topic that I could use. What am I doing wrong?

Body:
I'm working on a project and I'm stuck on a moment and I can maybe use some help from you guys.

I'm running a while loop and in the while loop I'm using a button. I want to update that specific row of the button.

But at my code now, it updates a row randomly.

This is my code:

<form name="faturalar" method="POST">

 Ödenmemiş Faturalarım

         #
         Ceza
         Miktar
         Ödeme

    <?php
        $count=1;
        $sel_query="SELECT * from billing WHERE identifier= '{$cid}';";
        $result = mysqli_query($svcon,$sel_query);
        while($row = mysqli_fetch_assoc($result)) {
        $fatMiktar = $row["amount"];
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

            if (isset($_POST['odeme'])) {
                $yeniMiktar = $BankaAl - $fatMiktar;
                $yeniAccount = array("bank"=>$yeniMiktar, "money"=>$NakitAl, "black_money"=>$BlackAl);
                $bankEncode = json_encode($yeniAccount);

                $up = "UPDATE users set accounts = '$bankEncode' WHERE id = '{$cid}'";

                $upresult = $svcon->query($up);
                $uprow = mysqli_fetch_array($upresult);
                header("Refresh:0");
            }
        }

    ?>

<?php echo $count; ?>	<?php echo $row["label"]; ?>	<?php echo $row["amount"]; ?>	<input name="odeme" type="submit" value="Öde" class="btn btn-primary">

    <?php $count++; } ?>

</form>

I searched on stackoverflow but I didn't find any topic that I could use. What am I doing wrong?


问:
filter is not a function
```<code>const featureData = action.payload.filter((curElem) => {
  return`your text` curElem.featured === true;
});
</code>```

How it solved

Console show this

```<code>Uncaught TypeError: action.payload.filter is not a function
</code>```

Title: filter is not a function

Body:
const featureData = action.payload.filter((curElem) => {
  return`your text` curElem.featured === true;
});

How it solved

Console show this

Uncaught TypeError: action.payload.filter is not a function


问:
How does KSQL restore streams and their persistent queries?
Internally I can see it has a topic _confluent-ksql-_command_topic that has every command that I have run, but it is still not completely clear how KSQL restores the state of which persistent queries are running.</p>


问:
gqlgen websocket not close if initFunc returns an error
I'm using gqlgen for my GraphQL API and I have some subscription (websocket) in my API. But it's not working as expected:

When initFunc of the transport.Websocket{} return an error the websocket is not close but spam the init function.

I would have expected the websocket to be closed and only one request is made to the server.

How can I can properly close the websocket if the init function failed (for instance auth failed) ?

Here is an example of an init funct that have this issue. It is from the gqlgen websocket example. I just added a debug print to make things clear in the webSocketInit:

```<code>func webSocketInit(ctx context.Context, initPayload transport.InitPayload) (context.Context, error) {
    // Get the token from payload
    any := initPayload["authToken"]
    token, ok := any.(string)
    if !ok || token == "" {
        fmt.Println("error in init")
        return nil, errors.New("authToken not found in transport payload")
    }

    // Perform token verification and authentication...
    userId := "john.doe" // e.g. userId, err := GetUserFromAuthentication(token)

    // put it in context
    ctxNew := context.WithValue(ctx, "username", userId)

    return ctxNew, nil
}
</code>```

and then just run a query in the playground without any auth header:

```<code>subscription test {
  subscribe(subscriber:"jj")
}
</code>```

the browser will be hanging in a loading cycle and the server is looping in the init function:

```<code>➜  websocket_gqlgen ./server
2022/12/20 09:40:56 connect to http://localhost:8080/ for GraphQL playground
error in init
error in init
error in init
error in init
error in init
...
</code>```

The complete server and gql schema can be found in the gqlgen example repo but here is the main function copy paste for your convenience:

```<code>const defaultPort = "8080"

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = defaultPort
    }

    router := chi.NewRouter()

    // CORS setup, allow any for now
    // https://gqlgen.com/recipes/cors/
    c := cors.New(cors.Options{
        AllowedOrigins:   []string{"*"},
        AllowCredentials: true,
        Debug:            false,
    })

    srv := handler.New(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{}}))
    srv.AddTransport(transport.POST{})
    srv.AddTransport(transport.Websocket{
        KeepAlivePingInterval: 10 * time.Second,
        Upgrader: websocket.Upgrader{
            CheckOrigin: func(r *http.Request) bool {
                return true
            },
        },
        InitFunc: func(ctx context.Context, initPayload transport.InitPayload) (context.Context, error) {
            return webSocketInit(ctx, initPayload)
        },
    })
    srv.Use(extension.Introspection{})

    router.Handle("/", playground.Handler("My GraphQL App", "/app"))
    router.Handle("/app", c.Handler(srv))

    log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
    log.Fatal(http.ListenAndServe(":"+port, router))

}
</code>```

Body:
I'm using gqlgen for my GraphQL API and I have some subscription (websocket) in my API. But it's not working as expected:

When initFunc of the transport.Websocket{} return an error the websocket is not close but spam the init function.

I would have expected the websocket to be closed and only one request is made to the server.

How can I can properly close the websocket if the init function failed (for instance auth failed) ?

Here is an example of an init funct that have this issue. It is from the gqlgen websocket example. I just added a debug print to make things clear in the webSocketInit:

func webSocketInit(ctx context.Context, initPayload transport.InitPayload) (context.Context, error) {
    // Get the token from payload
    any := initPayload["authToken"]
    token, ok := any.(string)
    if !ok || token == "" {
        fmt.Println("error in init")
        return nil, errors.New("authToken not found in transport payload")
    }

    // Perform token verification and authentication...
    userId := "john.doe" // e.g. userId, err := GetUserFromAuthentication(token)

    // put it in context
    ctxNew := context.WithValue(ctx, "username", userId)

    return ctxNew, nil
}

and then just run a query in the playground without any auth header:

subscription test {
  subscribe(subscriber:"jj")
}

the browser will be hanging in a loading cycle and the server is looping in the init function:

➜  websocket_gqlgen ./server
2022/12/20 09:40:56 connect to http://localhost:8080/ for GraphQL playground
error in init
error in init
error in init
error in init
error in init
...

The complete server and gql schema can be found in the gqlgen example repo but here is the main function copy paste for your convenience:

const defaultPort = "8080"

func main() {
    port := os.Getenv("PORT")
    if port == "" {
        port = defaultPort
    }

    router := chi.NewRouter()

    // CORS setup, allow any for now
    // https://gqlgen.com/recipes/cors/
    c := cors.New(cors.Options{
        AllowedOrigins:   []string{"*"},
        AllowCredentials: true,
        Debug:            false,
    })

    srv := handler.New(graph.NewExecutableSchema(graph.Config{Resolvers: &graph.Resolver{}}))
    srv.AddTransport(transport.POST{})
    srv.AddTransport(transport.Websocket{
        KeepAlivePingInterval: 10 * time.Second,
        Upgrader: websocket.Upgrader{
            CheckOrigin: func(r *http.Request) bool {
                return true
            },
        },
        InitFunc: func(ctx context.Context, initPayload transport.InitPayload) (context.Context, error) {
            return webSocketInit(ctx, initPayload)
        },
    })
    srv.Use(extension.Introspection{})

    router.Handle("/", playground.Handler("My GraphQL App", "/app"))
    router.Handle("/app", c.Handler(srv))

    log.Printf("connect to http://localhost:%s/ for GraphQL playground", port)
    log.Fatal(http.ListenAndServe(":"+port, router))

}


问:
Automatic extension of user access when we modify objects in schema
I want to update the user access in PostgreSQL automatically when ever we make any changes (modify or create new table) in schema.

is there any way to automatic update of access when we make changes in schema

please advice, thank you


问:
Using stdarg.h in bare metal programming
I'm writing a small bootloader for a qemu virt using cortex a72.
I am able to write some text to the UART contrôler to display some text.
I want to write a light version of printf to have some flexibility when writing text but stdarg seems not to work.

The compilation has no errors but when calling a function with variadic arguments, qemu seems to stuck itself in an infinite loop. When debugging with gdb, it wont leave the function and freeze even when using 'step' instead of 'next'.

Any way to use stdarg in bare metal programming or is a kernel needed ?

EDIT:
I just tried to debug using assembly layout and it is even more weird. At the beginning of the function, there is a bunch of 'str' to save some registers to the stack, but when executing one of them, the program jumps to a random memory address...
Here is what I see:

```<code>>0x400808b4 <printf>     stp     x29, x30, [sp, #-272]!
│   0x400808b8 <printf+4>   mov     x29, sp
│   0x400808bc <printf+8>   str     x0, [sp, #24]
│   0x400808c0 <printf+12>  str     x1, [sp, #216]
│   0x400808c4 <printf+16>  str     x2, [sp, #224]
│   0x400808c8 <printf+20>  str     x3, [sp, #232]
│   0x400808cc <printf+24>  str     x4, [sp, #240]
│   0x400808d0 <printf+28>  str     x5, [sp, #248]
│   0x400808d4 <printf+32>  str     x6, [sp, #256]
│   0x400808d8 <printf+36>  str     x7, [sp, #264]
│   0x400808dc <printf+40>  str     q0, [sp, #80]
│   0x400808e0 <printf+44>  str     q1, [sp, #96]
│   0x400808e4 <printf+48>  str     q2, [sp, #112]
│   0x400808e8 <printf+52>  str     q3, [sp, #128]
│   0x400808ec <printf+56>  str     q4, [sp, #144]
│   0x400808f0 <printf+60>  str     q5, [sp, #160]
│   0x400808f4 <printf+64>  str     q6, [sp, #176]
│   0x400808f8 <printf+68>  str     q7, [sp, #192]
│   0x400808fc <printf+72>  add     x0, sp, #0x110
│   0x40080900 <printf+76>  str     x0, [sp, #40]
│   0x40080904 <printf+80>  add     x0, sp, #0x110
│   0x40080908 <printf+84>  str     x0, [sp, #48]
│   0x4008090c <printf+88>  add     x0, sp, #0xd0
│   0x40080910 <printf+92>  str     x0, [sp, #56]
│   0x40080914 <printf+96>  mov     w0, #0xffffffc8
│   0x40080918 <printf+100> str     w0, [sp, #64]
│   0x4008091c <printf+104> mov     w0, #0xffffff80
│   0x40080920 <printf+108> str     w0, [sp, #68]
│   0x40080924 <printf+112> str     wzr, [sp, #76]
│   0x40080928 <printf+116> str     wzr, [sp, #72]
</code>```

The program jumps at the str q1, [sp, #96] instruction.

EDIT2: As asked in the comments, here is a sample code that causes the bug. This code does nothing special, it just uses variadic arguments and the bug is still present.

```<code>int va_test(int arg1, ...) {
    va_list ap;
    int next;

    va_start(ap, arg1);
    while (arg1) {
        next = va_arg(ap, int);
        arg1--;
    }
    va_end(ap);
    return next;
}

int kmain() {
    va_test(1, 2);
    return 0;
}
</code>```

Body:
I'm writing a small bootloader for a qemu virt using cortex a72.
I am able to write some text to the UART contrôler to display some text.
I want to write a light version of printf to have some flexibility when writing text but stdarg seems not to work.

The compilation has no errors but when calling a function with variadic arguments, qemu seems to stuck itself in an infinite loop. When debugging with gdb, it wont leave the function and freeze even when using 'step' instead of 'next'.

Any way to use stdarg in bare metal programming or is a kernel needed ?

EDIT:
I just tried to debug using assembly layout and it is even more weird. At the beginning of the function, there is a bunch of 'str' to save some registers to the stack, but when executing one of them, the program jumps to a random memory address...
Here is what I see:

>0x400808b4 <printf>     stp     x29, x30, [sp, #-272]!
│   0x400808b8 <printf+4>   mov     x29, sp
│   0x400808bc <printf+8>   str     x0, [sp, #24]
│   0x400808c0 <printf+12>  str     x1, [sp, #216]
│   0x400808c4 <printf+16>  str     x2, [sp, #224]
│   0x400808c8 <printf+20>  str     x3, [sp, #232]
│   0x400808cc <printf+24>  str     x4, [sp, #240]
│   0x400808d0 <printf+28>  str     x5, [sp, #248]
│   0x400808d4 <printf+32>  str     x6, [sp, #256]
│   0x400808d8 <printf+36>  str     x7, [sp, #264]
│   0x400808dc <printf+40>  str     q0, [sp, #80]
│   0x400808e0 <printf+44>  str     q1, [sp, #96]
│   0x400808e4 <printf+48>  str     q2, [sp, #112]
│   0x400808e8 <printf+52>  str     q3, [sp, #128]
│   0x400808ec <printf+56>  str     q4, [sp, #144]
│   0x400808f0 <printf+60>  str     q5, [sp, #160]
│   0x400808f4 <printf+64>  str     q6, [sp, #176]
│   0x400808f8 <printf+68>  str     q7, [sp, #192]
│   0x400808fc <printf+72>  add     x0, sp, #0x110
│   0x40080900 <printf+76>  str     x0, [sp, #40]
│   0x40080904 <printf+80>  add     x0, sp, #0x110
│   0x40080908 <printf+84>  str     x0, [sp, #48]
│   0x4008090c <printf+88>  add     x0, sp, #0xd0
│   0x40080910 <printf+92>  str     x0, [sp, #56]
│   0x40080914 <printf+96>  mov     w0, #0xffffffc8
│   0x40080918 <printf+100> str     w0, [sp, #64]
│   0x4008091c <printf+104> mov     w0, #0xffffff80
│   0x40080920 <printf+108> str     w0, [sp, #68]
│   0x40080924 <printf+112> str     wzr, [sp, #76]
│   0x40080928 <printf+116> str     wzr, [sp, #72]

The program jumps at the str q1, [sp, #96] instruction.

EDIT2: As asked in the comments, here is a sample code that causes the bug. This code does nothing special, it just uses variadic arguments and the bug is still present.

int va_test(int arg1, ...) {
    va_list ap;
    int next;

    va_start(ap, arg1);
    while (arg1) {
        next = va_arg(ap, int);
        arg1--;
    }
    va_end(ap);
    return next;
}

int kmain() {
    va_test(1, 2);
    return 0;
}


问:
SQL date = like '%YYYY%' VS YEAR(Date) = 'YYYY'
When using SQL server, are there any benefits and what are the performances  of using = in a WHERE clause instead of LIKE?
e.g :  date = like '%YYYY%' VS  YEAR(Date) = 'YYYY'

THX

date = like '%YYYY%' VS  YEAR(Date) = 'YYYY'


问:
hls.js in react application
Currently, I'm using hls js in my react application, but I'm having trouble getting levels and qualities from the manifest
Actually, Hls.Events.MANIFEST_PARSED does not fire in Android browsers. On PC, it works fine; however, this issue only occurs in Android browsers. this is part of my code .</p>
```<code>const newHls = new Hls({
                enableWorker: false,
                ...hlsConfig,
            });

newHls.once(Hls.Events.MANIFEST_PARSED, (event, data) => {
                if (autoPlay) {
                    setIsPlaying(true)
                    playerRef?.current
                        ?.play()
                        .catch((e: any) => {
                                console.log(e)
                                setIsPlaying(false)
                            }

            });
</code>```

Title: hls.js in react application

Body:
Currently, I'm using hls js in my react application, but I'm having trouble getting levels and qualities from the manifest
Actually, Hls.Events.MANIFEST_PARSED does not fire in Android browsers. On PC, it works fine; however, this issue only occurs in Android browsers. this is part of my code .

const newHls = new Hls({
                enableWorker: false,
                ...hlsConfig,
            });

newHls.once(Hls.Events.MANIFEST_PARSED, (event, data) => {
                if (autoPlay) {
                    setIsPlaying(true)
                    playerRef?.current
                        ?.play()
                        .catch((e: any) => {
                                console.log(e)
                                setIsPlaying(false)
                            }

            });


问:
Adding up conditions in case clase without modifying where clause
I have a table with the following:

```<code>+---------+-------------+---------+
| revenue | bill_amount | invoice |
+=========+=============+=========+
| 2       | 1           | sad     |
+---------+-------------+---------+
| 2       | 5           | null    |
+---------+-------------+---------+
| 5       | 7           | null    |
+---------+-------------+---------+
| 5       | 2           | asdf    |
+---------+-------------+---------+
</code>```

and I have a query I want to do with a case condition (this is part of a bigger query so I can't modify the where clause of the condition, all the logic should be on the CASE)

I need to sum all revenue amounts and bill_amounts in which the invoice is not null, so from my example table, only first and last row. and from this, If the sum of revenue is higher than the sum of bill_amount (where invoice not null)  I have to do the sum(revenue) - sum(bill_amount)

I've tried to express it the following way:

```<code>SELECT SUM(CASE
               WHEN SUM(CASE
                            WHEN Invoice IS NOT NULL
                            THEN Revenue
                            ELSE 0
                        END) > SUM(CASE
                                       WHEN Invoice IS NOT NULL
                                       THEN Bill_Amount
                                       ELSE 0
                                   END)
               THEN(SUM(CASE
                            WHEN Invoice IS NOT NULL
                            THEN Revenue
                            ELSE 0
                        END) - SUM(CASE
                                       WHEN Invoice IS NOT NULL
                                       THEN Bill_Amount
                                       ELSE 0
                                   END))
               ELSE 0
           END) AS Total
FROM Table
Where Conditions
</code>```

but I'm getting and error saying  "nested group function without GROUP BY"
is there a way I can do this better?

I feel that my approach is dumb, but I'm not coming up with a better wayof achieving this calculation (the entire query has a lot of other case statements so I can't modify the where clause or will impact the other cases)

Body:
I have a table with the following:

+---------+-------------+---------+
| revenue | bill_amount | invoice |
+=========+=============+=========+
| 2       | 1           | sad     |
+---------+-------------+---------+
| 2       | 5           | null    |
+---------+-------------+---------+
| 5       | 7           | null    |
+---------+-------------+---------+
| 5       | 2           | asdf    |
+---------+-------------+---------+

and I have a query I want to do with a case condition (this is part of a bigger query so I can't modify the where clause of the condition, all the logic should be on the CASE)

I need to sum all revenue amounts and bill_amounts in which the invoice is not null, so from my example table, only first and last row. and from this, If the sum of revenue is higher than the sum of bill_amount (where invoice not null)  I have to do the sum(revenue) - sum(bill_amount)

I've tried to express it the following way:

SELECT SUM(CASE
               WHEN SUM(CASE
                            WHEN Invoice IS NOT NULL
                            THEN Revenue
                            ELSE 0
                        END) > SUM(CASE
                                       WHEN Invoice IS NOT NULL
                                       THEN Bill_Amount
                                       ELSE 0
                                   END)
               THEN(SUM(CASE
                            WHEN Invoice IS NOT NULL
                            THEN Revenue
                            ELSE 0
                        END) - SUM(CASE
                                       WHEN Invoice IS NOT NULL
                                       THEN Bill_Amount
                                       ELSE 0
                                   END))
               ELSE 0
           END) AS Total
FROM Table
Where Conditions

but I'm getting and error saying  "nested group function without GROUP BY"
is there a way I can do this better?

I feel that my approach is dumb, but I'm not coming up with a better wayof achieving this calculation (the entire query has a lot of other case statements so I can't modify the where clause or will impact the other cases)


问:
Is there an equivalent to `http_build_query` for `multipart/form-data` in PHP?
I need to respond to a HTTP request to a PHP script with a collection of files, multipart/form-data should be the perfect solution but I cannot find a way to serialize a PHP object/array into it.

In short: Does PHP have and equivalent to the FormData available in Javascript?


问:
User Defined Function for Looping through a DataFrame and Slicing it Based on Timewindows
I'm trying to write a user-defined function which gets a DataFrame as its input and accepts two additional arguments: start date and finish date. Then I would like to slice the Datframe based on a yearly interval. So dates are provided in a column:

enter image description here

While I was working on this DataFrame, I performed the mentioned operation based on this piece of code I've found:

```<code>start_date = '2022-01-01'
end_date = '2023-12-31'
# Select DataFrame rows between two dates
mask = (df['announced_on'] > start_date) & (df['announced_on'] <= end_date)
df1 = df.loc[mask]
</code>```

Basically, I'd like to have a function which receives the start and end date and iterate over all rows and create separate DataFrames. Normally, I'd write start and end dates manually and one by one but the DataFrame I'm working with now is pretty big and goes back to the 1970s so I would like to achieve the same results using a function.  I have a pretty difficult time writing this function, so I'd appreciate any hint or suggestion you have.

Cheers!

Body:
I'm trying to write a user-defined function which gets a DataFrame as its input and accepts two additional arguments: start date and finish date. Then I would like to slice the Datframe based on a yearly interval. So dates are provided in a column:

enter image description here

While I was working on this DataFrame, I performed the mentioned operation based on this piece of code I've found:

start_date = '2022-01-01'
end_date = '2023-12-31'
# Select DataFrame rows between two dates
mask = (df['announced_on'] > start_date) & (df['announced_on'] <= end_date)
df1 = df.loc[mask]

Basically, I'd like to have a function which receives the start and end date and iterate over all rows and create separate DataFrames. Normally, I'd write start and end dates manually and one by one but the DataFrame I'm working with now is pretty big and goes back to the 1970s so I would like to achieve the same results using a function.  I have a pretty difficult time writing this function, so I'd appreciate any hint or suggestion you have.

Cheers!


问:
Download doesn't work for a request from HTTP1.1 protocol to HTTP2.0 protocol
I have a PHP-FPM application served by Nginx enabled with HTTP 2.0 Protocol. The application is running on an Amazon EC2 instance. Everything works fine if I hit the instance IP(via CNAME).

Now I am transitioning my applications to K8s and deployed an Nginx Ingres controller with a k8s service Type Load Balancer(classic load balancer) in my K8s cluster.

I have created an external name service that points to this instance(I have connectivity from my K8s to this instance). This is a temporary solution until I move this application to the K8s cluster.

My Service file looks like this:

```<code>apiVersion: v1
kind: Service
metadata:
  name: cms-sample-external-name
  namespace: default
spec:
  externalName: 10.100.11.111
  type: ExternalName
</code>```

I have created an ingress that points to this service:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: ingress-nginx-internal
    nginx.ingress.kubernetes.io/backend-protocol: HTTPS
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
  name: cms-sample-ingress
  namespace: default
spec:
  rules:
  - host: cms-sample.abc.com
    http:
      paths:
      - backend:
          service:
            name: cms-sample-external-name
            port:
              number: 443
        path: /
        pathType: ImplementationSpecific
</code>```

Now when I hit my URL to download the file, it just hangs at 99% and retries multiple times before it fails.

I can see these logs in the ingress controller:

[nginx-ingress-controller-internal-7c6dbbd9c5-67spv] 2022/12/20
08:41:11 [error] 578#578: *29160000 upstream prematurely closed
connection while reading upstream, client: 10.72.2.255, server:
cms-sample.abc.com, request: "GET /test/com/pdf-download?page_id=test
HTTP/1.1", upstream:
"https://10.100.11.111:443/test/com/pdf-download?page_id=test", host:
"cms-sample.abc.com"

[nginx-ingress-controller-internal-7c6dbbd9c5-zqqx4] 10.72.20.257 - -
[20/Dec/2022:09:34:49 +0000] "GET
/test/com/pdf-download?page_id=test HTTP/1.1"
200 25264 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
867 10.901 [cms-sample-external-name-443] []
10.100.11.111:443 25264 10.900 200 df4a5dec5c31aadcf8934ee3d8c4eb8f

However, all other URIs work well.

I have tried creating an ALB manually and pointing it to a node port service like this and it worked.

```<code>---
apiVersion: v1
kind: Endpoints
metadata:
  name: cms-test-endpoint
  namespace: default
  labels:
    app.kubernetes.io/name: cms-test
subsets:
- addresses:
  - ip: 10.100.11.111
  ports:
  - name: https
    port: 443
    protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  name: cms-test-endpoint
  namespace: default
  labels:
    app.kubernetes.io/name: cms-test
spec:
  type: NodePort
  ports:
    - port: 80
      nodePort: 31080
      name: http
      targetPort: http
    - port: 443
      nodePort: 31443
      name: https
      targetPort: https
</code>```

Logs from Nginx PHP-FMP Instance -

Hit Directly the Instance IP(via CNAME)

{"log":"[20/Dec/2022:09:45:36 +0000] 10.72.2.255 - - - 1.487
"cms-sample.abc.com" "GET /test/com/pdf-download?page_id=test
HTTP/2.0" 200 25264 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0
Safari/537.36" "cms-site-live.tajawal.com" "0.0.0.0:9002" 0.000 -
1.488 - 1671529536.532\n","stream":"stdout","time":"2022-12-20T09:45:36.532473459Z"}

{"log":"[20/Dec/2022:09:45:39 +0000] 10.72.2.255 - - - 0.000
"cms-sample.abc.com" "GET /test/com/pdf-download?page_id=test
HTTP/2.0" 444 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_11_1) AppleWebKit/601.2.4 (KHTML, like Gecko) Version/9.0.1
Safari/601.2.4 facebookexternalhit/1.1 Facebot Twitterbot/1.0"
"cms-sample.abc.com" "-" - - - -
1671529539.150\n","stream":"stdout","time":"2022-12-20T09:45:39.151075446Z"}

Hit via ingress controller -

{"log":"[20/Dec/2022:09:45:56 +0000] 10.72.2.255 - - - 0.894
"cms-sample.abc.com" "GET /test/com/pdf-download?page_id=test
HTTP/1.1" 200 25264 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0
Safari/537.36" "cms-sample.abc.com" "0.0.0.0:9002" 0.000 - 0.896 - 1671529556.352\n","stream":"stdout","time":"2022-12-20T09:45:56.353093232Z"}

The only difference I have noticed is the protocol, in the case of accessing direct Instance IP, it is HTTP2 in the logs whereas in the case of Loadbalancer it is HTTP1.

I am not sure what I am missing in the ingress controller setup.

Body:
I have a PHP-FPM application served by Nginx enabled with HTTP 2.0 Protocol. The application is running on an Amazon EC2 instance. Everything works fine if I hit the instance IP(via CNAME).

Now I am transitioning my applications to K8s and deployed an Nginx Ingres controller with a k8s service Type Load Balancer(classic load balancer) in my K8s cluster.

I have created an external name service that points to this instance(I have connectivity from my K8s to this instance). This is a temporary solution until I move this application to the K8s cluster.

My Service file looks like this:

apiVersion: v1
kind: Service
metadata:
  name: cms-sample-external-name
  namespace: default
spec:
  externalName: 10.100.11.111
  type: ExternalName

I have created an ingress that points to this service:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: ingress-nginx-internal
    nginx.ingress.kubernetes.io/backend-protocol: HTTPS
    nginx.ingress.kubernetes.io/force-ssl-redirect: "true"
  name: cms-sample-ingress
  namespace: default
spec:
  rules:
  - host: cms-sample.abc.com
    http:
      paths:
      - backend:
          service:
            name: cms-sample-external-name
            port:
              number: 443
        path: /
        pathType: ImplementationSpecific

Now when I hit my URL to download the file, it just hangs at 99% and retries multiple times before it fails.

I can see these logs in the ingress controller:

[nginx-ingress-controller-internal-7c6dbbd9c5-67spv] 2022/12/20
08:41:11 [error] 578#578: *29160000 upstream prematurely closed
connection while reading upstream, client: 10.72.2.255, server:
cms-sample.abc.com, request: "GET /test/com/pdf-download?page_id=test
HTTP/1.1", upstream:
"https://10.100.11.111:443/test/com/pdf-download?page_id=test", host:
"cms-sample.abc.com"

[nginx-ingress-controller-internal-7c6dbbd9c5-zqqx4] 10.72.20.257 - -
[20/Dec/2022:09:34:49 +0000] "GET
/test/com/pdf-download?page_id=test HTTP/1.1"
200 25264 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"
867 10.901 [cms-sample-external-name-443] []
10.100.11.111:443 25264 10.900 200 df4a5dec5c31aadcf8934ee3d8c4eb8f

However, all other URIs work well.

I have tried creating an ALB manually and pointing it to a node port service like this and it worked.

---
apiVersion: v1
kind: Endpoints
metadata:
  name: cms-test-endpoint
  namespace: default
  labels:
    app.kubernetes.io/name: cms-test
subsets:
- addresses:
  - ip: 10.100.11.111
  ports:
  - name: https
    port: 443
    protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  name: cms-test-endpoint
  namespace: default
  labels:
    app.kubernetes.io/name: cms-test
spec:
  type: NodePort
  ports:
    - port: 80
      nodePort: 31080
      name: http
      targetPort: http
    - port: 443
      nodePort: 31443
      name: https
      targetPort: https

Logs from Nginx PHP-FMP Instance -

Hit Directly the Instance IP(via CNAME)

{"log":"[20/Dec/2022:09:45:36 +0000] 10.72.2.255 - - - 1.487
"cms-sample.abc.com" "GET /test/com/pdf-download?page_id=test
HTTP/2.0" 200 25264 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0
Safari/537.36" "cms-site-live.tajawal.com" "0.0.0.0:9002" 0.000 -
1.488 - 1671529536.532\n","stream":"stdout","time":"2022-12-20T09:45:36.532473459Z"}

{"log":"[20/Dec/2022:09:45:39 +0000] 10.72.2.255 - - - 0.000
"cms-sample.abc.com" "GET /test/com/pdf-download?page_id=test
HTTP/2.0" 444 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_11_1) AppleWebKit/601.2.4 (KHTML, like Gecko) Version/9.0.1
Safari/601.2.4 facebookexternalhit/1.1 Facebot Twitterbot/1.0"
"cms-sample.abc.com" "-" - - - -
1671529539.150\n","stream":"stdout","time":"2022-12-20T09:45:39.151075446Z"}

Hit via ingress controller -

{"log":"[20/Dec/2022:09:45:56 +0000] 10.72.2.255 - - - 0.894
"cms-sample.abc.com" "GET /test/com/pdf-download?page_id=test
HTTP/1.1" 200 25264 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X
10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0
Safari/537.36" "cms-sample.abc.com" "0.0.0.0:9002" 0.000 - 0.896 - 1671529556.352\n","stream":"stdout","time":"2022-12-20T09:45:56.353093232Z"}

The only difference I have noticed is the protocol, in the case of accessing direct Instance IP, it is HTTP2 in the logs whereas in the case of Loadbalancer it is HTTP1.

I am not sure what I am missing in the ingress controller setup.


问:
Verify duplicate files on upload on Angular JS
Am aploading a file and i wanna verify if the same file is already uploaded. The problem that am having is that it pass on my function right after clicking on upload it doesnt wait for me to choose the file to upload before passing by my function to verify the condition i made. i tried using ng-change and on change and none of em works.

Am using Angular JS to handle my front end. (Am a beginner)

```<code>function findFile(livrable) {

    return vm.livrables.find(function(livrablefichier) {// add an if here to check if the file is nulll
      if(livrablefichier == null) {
      return (
        livrablefichier.name         === livrable.name &&
        livrablefichier.lastModified === livrable.lastModified &&
        livrablefichier.size         === livrable.size &&
        livrablefichier.type         === livrable.type
      )
      }
    })
  }

  function verifyFiles(livrable){
    var livrableDejaExistant = false;
   livrable.dejaExistant  = false;
      if (findFile(livrable)) {
        livrableDejaExistant = true;
        livrable.dejaExistant = true;

      }
      else {
        livrableDejaExistant = false;
      }
</code>```

i tried using ng-change and on change and none of em works.

```<code>        <div class="col-xs-4 soumission-livrable">
              <form id="uploadForm" enctype="multipart/form-data">
                <div class="bouton-import-fichier debordementMasque">
                  <input type="file" id="{{livrable.fichier}}" name="{{livrable.fichier}}"
                         ng-disabled="!depotComposantCtrl.isAffichageBoutonMaj"
                         ng-change="depotComposantCtrl.verifyFiles(livrable)"
                         onchange="angular.element(this).scope().controleLivrableSansFichier()"
                         class="gererLongueurNomFichier">
                </div>
              </form>
            </div>
</code>```

Body:
Am aploading a file and i wanna verify if the same file is already uploaded. The problem that am having is that it pass on my function right after clicking on upload it doesnt wait for me to choose the file to upload before passing by my function to verify the condition i made. i tried using ng-change and on change and none of em works.

Am using Angular JS to handle my front end. (Am a beginner)

function findFile(livrable) {

    return vm.livrables.find(function(livrablefichier) {// add an if here to check if the file is nulll
      if(livrablefichier == null) {
      return (
        livrablefichier.name         === livrable.name &&
        livrablefichier.lastModified === livrable.lastModified &&
        livrablefichier.size         === livrable.size &&
        livrablefichier.type         === livrable.type
      )
      }
    })
  }

  function verifyFiles(livrable){
    var livrableDejaExistant = false;
   livrable.dejaExistant  = false;
      if (findFile(livrable)) {
        livrableDejaExistant = true;
        livrable.dejaExistant = true;

      }
      else {
        livrableDejaExistant = false;
      }

i tried using ng-change and on change and none of em works.

              <form id="uploadForm" enctype="multipart/form-data">

                  <input type="file" id="{{livrable.fichier}}" name="{{livrable.fichier}}"
                         ng-disabled="!depotComposantCtrl.isAffichageBoutonMaj"
                         ng-change="depotComposantCtrl.verifyFiles(livrable)"
                         onchange="angular.element(this).scope().controleLivrableSansFichier()"
                         class="gererLongueurNomFichier">

              </form>


问:
Cannot validate certificate with crypto/x509 and RSA SSA PSS
I'm trying to validate a certificate against a list of roots injected by hand into the chain (or "pool" as it is called in crypto/x509). No errors or anything here.

When I try to validate the certificate itself, I get the following error:

```<code>x509: certificate signed by unknown authority (possibly because of "x509: cannot verify signature: algorithm unimplemented" while trying to verify candidate authority certificate "Root CA 06/22/RSA")
</code>```

So far, this validation isn't failing due to "trust" issues, it's failing because the signature algorithm of the certificate isn't implemented and therefore cannot be validated. When I pop the certificate open in OpenSSL, I see the following details:

```<code>    Signature Algorithm: rsassaPss
         Hash Algorithm: sha512
         Mask Algorithm: mgf1 with sha512
          Salt Length: 0x01BE
</code>```

It seems that for some reason, RSA SSA PSS isn't implemented or -if it is- the certificate is having some sort of issue.

        payload, err := base64.StdEncoding.DecodeString(validationRequest.Certificate)
        if err != nil {
            log.WithFields(log.Fields{"route": req.RequestURI, "method": req.Method}).Warnf("could not decode base64: %s", validationRequest.Certificate)
            err := rend.JSON(writer, http.StatusBadRequest, map[string]string{"error": "payload is not valid base64"})
            if err != nil {
                log.Errorf("could not render response: %v", err)
            }
        } else {
            block, _ := pem.Decode(payload)
            if block == nil {
                err := rend.JSON(writer, http.StatusBadRequest, map[string]string{"error": "certificate is not a valid PEM"})
                if err != nil {
                    log.Errorf("could not render response: %v", err)
                }
            } else {
                certificate, err := cryptoX509.ParseCertificate(block.Bytes)
                if err != nil {
                    log.Errorf("failed to parse certificate: %v", err.Error())

                    err = rend.JSON(writer, http.StatusBadRequest, map[string]string{"error": fmt.Sprintf("certificate could not be parsed from bytes: %v", err.Error())})
                    if err != nil {
                        log.Errorf("could not render response: %v", err)
                    }
                } else {

                    _, ok := certificate.PublicKey.(*rsa.PublicKey)

                    // If weird or non-existing key
                    if !ok {
                        err = rend.JSON(writer, http.StatusNotAcceptable, map[string]string{"error": "certificate does not contain a valid key, or the key is missing"})
                        if err != nil {
                            log.Errorf("could not render response: %v", err)
                        }
                    } else {
if err = certificate.CheckSignature(certificate.SignatureAlgorithm, certificate.Raw, certificate.Signature); err != nil {
                            err = rend.JSON(writer, http.StatusNotAcceptable, map[string]string{"error": fmt.Sprintf("certificate is not valid: %v", err)})
                            if err != nil {
                                log.Errorf("could not render response: %v", err)
                            }
                        } else {
                            err = rend.JSON(writer, http.StatusOK, map[string]string{"status": "certificate is valid"})
                            if err != nil {
                                log.Errorf("could not render response: %v", err)
                            }
                        }
                    }

                }
            }
        }
```
<p>I've also attempted at using the <code>Verify</code> method:</p>
<pre class="lang-golang prettyprint-override"><code>opts := cryptoX509.VerifyOptions{
    Roots:     rootChain,
    KeyUsages: []cryptoX509.ExtKeyUsage{cryptoX509.ExtKeyUsageAny},
}

_, err := certificate.Verify(verifyOpts)

</code>```

But the message is the same one.

I would expect to both methods to pass successfully (verification given certain contraints or at least the basic signature verification).

Body:
I'm trying to validate a certificate against a list of roots injected by hand into the chain (or "pool" as it is called in crypto/x509). No errors or anything here.

When I try to validate the certificate itself, I get the following error:

x509: certificate signed by unknown authority (possibly because of "x509: cannot verify signature: algorithm unimplemented" while trying to verify candidate authority certificate "Root CA 06/22/RSA")

So far, this validation isn't failing due to "trust" issues, it's failing because the signature algorithm of the certificate isn't implemented and therefore cannot be validated. When I pop the certificate open in OpenSSL, I see the following details:

    Signature Algorithm: rsassaPss
         Hash Algorithm: sha512
         Mask Algorithm: mgf1 with sha512
          Salt Length: 0x01BE

It seems that for some reason, RSA SSA PSS isn't implemented or -if it is- the certificate is having some sort of issue.

        payload, err := base64.StdEncoding.DecodeString(validationRequest.Certificate)
        if err != nil {
            log.WithFields(log.Fields{"route": req.RequestURI, "method": req.Method}).Warnf("could not decode base64: %s", validationRequest.Certificate)
            err := rend.JSON(writer, http.StatusBadRequest, map[string]string{"error": "payload is not valid base64"})
            if err != nil {
                log.Errorf("could not render response: %v", err)
            }
        } else {
            block, _ := pem.Decode(payload)
            if block == nil {
                err := rend.JSON(writer, http.StatusBadRequest, map[string]string{"error": "certificate is not a valid PEM"})
                if err != nil {
                    log.Errorf("could not render response: %v", err)
                }
            } else {
                certificate, err := cryptoX509.ParseCertificate(block.Bytes)
                if err != nil {
                    log.Errorf("failed to parse certificate: %v", err.Error())

                    err = rend.JSON(writer, http.StatusBadRequest, map[string]string{"error": fmt.Sprintf("certificate could not be parsed from bytes: %v", err.Error())})
                    if err != nil {
                        log.Errorf("could not render response: %v", err)
                    }
                } else {

                    _, ok := certificate.PublicKey.(*rsa.PublicKey)

                    // If weird or non-existing key
                    if !ok {
                        err = rend.JSON(writer, http.StatusNotAcceptable, map[string]string{"error": "certificate does not contain a valid key, or the key is missing"})
                        if err != nil {
                            log.Errorf("could not render response: %v", err)
                        }
                    } else {
if err = certificate.CheckSignature(certificate.SignatureAlgorithm, certificate.Raw, certificate.Signature); err != nil {
                            err = rend.JSON(writer, http.StatusNotAcceptable, map[string]string{"error": fmt.Sprintf("certificate is not valid: %v", err)})
                            if err != nil {
                                log.Errorf("could not render response: %v", err)
                            }
                        } else {
                            err = rend.JSON(writer, http.StatusOK, map[string]string{"status": "certificate is valid"})
                            if err != nil {
                                log.Errorf("could not render response: %v", err)
                            }
                        }
                    }

                }
            }
        }

I've also attempted at using the Verify method:

opts := cryptoX509.VerifyOptions{
    Roots:     rootChain,
    KeyUsages: []cryptoX509.ExtKeyUsage{cryptoX509.ExtKeyUsageAny},
}

_, err := certificate.Verify(verifyOpts)

But the message is the same one.

I would expect to both methods to pass successfully (verification given certain contraints or at least the basic signature verification).


问:
How to display the Hyperlink Value in Interop Excel correctly?
I get data from a SQL Query which I fill into an Excel File. One Excel Column gets strings which are Hyperlinks, the strings I get look like this:

```<code>=HYPERLINK("www.example")
</code>```

at first the Hyperlinks just got this a normal string on which the function isn't working.

What I have tried is this:

Microsoft.Office.Interop.Excel.Range range = ws2.Columns[3];

foreach (Microsoft.Office.Interop.Excel.Range cell in range)
{
    object cellValue = cell.Value;
    string cellValueString = cellValue as string;
    cell.Hyperlinks.Add(cell, cellValueString);
}
```
<p>With this the string is now formatted as a Hyperlink but the Hyperlink in Excel got the whole formula with this part <code>=HYPERLINK</code>. Then I tried to make it as a formula with this code:</p>
<pre class="lang-cs prettyprint-override"><code>foreach (Microsoft.Office.Interop.Excel.Range cell in range)
{
    object cellValue = cell.Value;
    string cellValueString = cellValue as string;
    cell.Formula = cellValueString;
}
</code>```

But then the whole column is empty. How can I make the whole third column values show as hyperlinks and format them correctly?

Body:
I get data from a SQL Query which I fill into an Excel File. One Excel Column gets strings which are Hyperlinks, the strings I get look like this:

=HYPERLINK("www.example")

at first the Hyperlinks just got this a normal string on which the function isn't working.

What I have tried is this:

Microsoft.Office.Interop.Excel.Range range = ws2.Columns[3];

foreach (Microsoft.Office.Interop.Excel.Range cell in range)
{
    object cellValue = cell.Value;
    string cellValueString = cellValue as string;
    cell.Hyperlinks.Add(cell, cellValueString);
}

With this the string is now formatted as a Hyperlink but the Hyperlink in Excel got the whole formula with this part =HYPERLINK. Then I tried to make it as a formula with this code:

foreach (Microsoft.Office.Interop.Excel.Range cell in range)
{
    object cellValue = cell.Value;
    string cellValueString = cellValue as string;
    cell.Formula = cellValueString;
}

But then the whole column is empty. How can I make the whole third column values show as hyperlinks and format them correctly?


问:
How to seperate the multiple Requests into a file in SoapUI
I am need to process the 100 requests which are in single file as a Soap request. I'm unable to write the groovy Script for one by one request to take and Proccess it.

I have created the test suites and test cases for multiple requests. But I'm unable to load the requests from a file.

I was attached the file and test it in SoapUI. but it doesn't work. Bcoz it takes the whole file at a time. But I want to read the one by one request which has the soap envelope and body.
Please find the Attached Script. I have tried this script to read the file and process it.


问:
Test contents of incoming @RequestBody with Spring MockMvc
Is there a way of testing the contents of an incoming @RequestBody with Spring MockMvc?

Example, where I want to check the contents of fooRequestBody in my test if my configuration-setup (JSON-lib/converter/etc) is working as expected.

Controller

```<code>@PostMapping(path = "/foo", consumes = "application/json", produces = "application/json")
public FooResponse foo(@RequestBody final FooRequestBody fooRequestBody) {
  // ... do something
  return new FooResponse();
}
</code>```

Test

```<code>@Test
void testFoo() throws Exception {
  mockMvc.perform(MockMvcRequestBuilders.post("/foo")
        .content(asJsonString(new FooRequestBody("fooRequest"))).accept(MediaType.APPLICATION_JSON)) //
        .andExpect(status().isOk()) //
        .andExpect(MockMvcResultMatchers.jsonPath("$.fooResponse").value("ok"))
        // here or somewhere else goes my test for the contents of fooRequestBody
        ;
}
</code>```

Body:
Is there a way of testing the contents of an incoming @RequestBody with Spring MockMvc?

Example, where I want to check the contents of fooRequestBody in my test if my configuration-setup (JSON-lib/converter/etc) is working as expected.

Controller

@PostMapping(path = "/foo", consumes = "application/json", produces = "application/json")
public FooResponse foo(@RequestBody final FooRequestBody fooRequestBody) {
  // ... do something
  return new FooResponse();
}

Test

@Test
void testFoo() throws Exception {
  mockMvc.perform(MockMvcRequestBuilders.post("/foo")
        .content(asJsonString(new FooRequestBody("fooRequest"))).accept(MediaType.APPLICATION_JSON)) //
        .andExpect(status().isOk()) //
        .andExpect(MockMvcResultMatchers.jsonPath("$.fooResponse").value("ok"))
        // here or somewhere else goes my test for the contents of fooRequestBody
        ;
}