mardi 31 décembre 2019

Struts2.5 JSONInterceptor is not populating the Action class:

I am building a CRUD application using embers as client and struts2 as server. The post request to create a record from ember looks like,

Accept: application/json, text/javascript, /; q=0.01 Accept-Encoding: gzip, deflate, br Accept-Language: en-GB,en-US;q=0.9,en;q=0.8 Connection: keep-alive Content-Length: 54 Content-Type: application/json; charset=UTF-8 Host: localhost:8080 Origin: http://localhost:4200 Referer: http://localhost:4200/create Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36 {product: "{"name":"iamironman","price":3000}"} product: "{"name":"iamironman","price":3000}"

ember request payload

Struts.xml :

    <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.default.parent.package" value="default"/>
    <constant name="struts.convention.package.locators" value="controller"/>
    <constant name="struts.rest.content.restrictToGET" value="false"/>

   <package name="default" namespace="/" extends="rest-default,json-default">
        <interceptors>
            <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
            <interceptor-stack name="myStack">
                <interceptor-ref name="json">
                    <param name="jsonContentType">application/json</param>
                </interceptor-ref>
                <interceptor-ref name="defaultStack" />
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="myStack" />
        <global-allowed-methods>index,show,create,update,destroy</global-allowed-methods>
        <action name="products/*" class="controller.ProductsController">
            <interceptor-ref name="myStack" />
            <result name="index" type="json"></result>
        </action>
   </package>
</struts>

Action class :

package controller;
import java.util.List;
//import javax.servlet.http.HttpServletRequest;
import dao.Productdao;
import model.product;
//import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
import com.opensymphony.xwork2.ModelDriven;

//@InterceptorRef(value="json")
public class ProductsController implements ModelDriven<Object>{
    //private static final Logger log = LogManager.getLogger(ProductsController.class);
    product p=new product();
    Productdao dao=new Productdao();
    private List<product> productlist=dao.getAllProduct();
    private int id;
    private String name;
    private double price;
    //private HttpServletRequest request;
    //private JSONObject Object;

    public HttpHeaders show()
    {
        System.out.println("Showing");
        p=dao.getProduct(id);
        return new DefaultHttpHeaders("show");
    }

    public HttpHeaders index() {
        System.out.println("i am inside index");
        return new DefaultHttpHeaders("index").disableCaching();
    }

    public String create()
    {
        System.out.println("order creation : "+name+price);
        boolean result=dao.createProduct(name,price);
        if(result)
        {
            System.out.println("product created successfully");
            return "success";
        }
        else
        {
            System.out.println("product Not created");
            return "increated";
        }
    }

    public String update()
    {
        System.out.println("inside update"+id+name+price);
        p.setId(id);
        p.setName(name);
        p.setPrice(price);
        boolean result=dao.updateProduct(p);
        if(result)
        {
            System.out.println("product updated successfully");
            return "success";
        }
        else
        {
            System.out.println("product not updated");
            return "inupdated";
        }
    }
    public String destroy()
    {
        System.out.println("inside destroy"+id);
        boolean result=dao.deleteProduct(id);
        if(result) {
            System.out.println("deleted successfully");
            return "success";
        }
        else
        {
            System.out.println("Not deleted");
            return "indeleted";
        }
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    /*public JSONObject getObject() {
        return Object;
    }

    public void setObject(JSONObject object) {
        Object = object;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }*/

    @Override
    public Object getModel() {
        System.out.println("getting model");
        return productlist;
    }

}

Error :

java.sql.SQLIntegrityConstraintViolationException: Column 'name' cannot be null
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
    at dao.Productdao.createProduct(Productdao.java:40)
    at controller.ProductsController.create(ProductsController.java:38)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at ognl.OgnlRuntime.invokeMethodInsideSandbox(OgnlRuntime.java:1226)
    at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:1211)
    at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1920)
    at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethodWithDebugInfo(XWorkMethodAccessor.java:98)
    at com.opensymphony.xwork2.ognl.accessor.XWorkMethodAccessor.callMethod(XWorkMethodAccessor.java:90)
    at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1996)
    at ognl.ASTMethod.getValueBody(ASTMethod.java:91)
    at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
    at ognl.SimpleNode.getValue(SimpleNode.java:258)
    at ognl.Ognl.getValue(Ognl.java:537)
    at ognl.Ognl.getValue(Ognl.java:501)
    at com.opensymphony.xwork2.ognl.OgnlUtil$3.execute(OgnlUtil.java:492)
    at com.opensymphony.xwork2.ognl.OgnlUtil.compileAndExecuteMethod(OgnlUtil.java:544)
    at com.opensymphony.xwork2.ognl.OgnlUtil.callMethod(OgnlUtil.java:490)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:438)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:293)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:254)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:250)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:179)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:263)
    at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:49)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:142)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:137)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:137)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:201)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:67)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:133)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:89)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:243)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:101)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:142)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:160)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:175)
    at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:99)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:121)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:167)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:203)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:196)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at org.apache.struts2.json.JSONInterceptor.intercept(JSONInterceptor.java:185)
    at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:249)
    at org.apache.struts2.rest.RestActionInvocation.invoke(RestActionInvocation.java:130)
    at com.opensymphony.xwork2.DefaultActionProxy.execute(DefaultActionProxy.java:157)
    at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:574)
    at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:79)
    at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:141)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.filters.CorsFilter.handleSimpleCORS(CorsFilter.java:259)
    at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:163)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

What am I doing wrong. Thanks in advance..!




lundi 30 décembre 2019

Error while trying to build a CRUD application using Struts2.5 (server-side) and Emberjs(client-side)

Error number 1 POST request: order creation : null0.0 java.sql.SQLIntegrityConstraintViolationException: Column 'name' cannot be null

JSONInterceptor isn't working.

Error number 2 PUT request: freemarker.log._JULLoggerFactory$JULLogger error SEVERE: Error executing FreeMarker template FreeMarker template error: The following has evaluated to null or missing: ==> rootloc.URI [in template "org/apache/struts2/dispatcher/error.ftl" at line 84, column 15]


Tip: It's the step after the last dot that caused this error, not those before it.

Tip: If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??


FTL stack trace ("~" means nesting-related):

- Failed at: ${rootloc.URI} [in template "org/apache/struts2/dispatcher/error.ftl" at line 84, column 13]

Java stack trace (for programmers):

freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134) at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:467) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:389) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:358) at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:100) at freemarker.core.DollarVariable.accept(DollarVariable.java:63) at freemarker.core.Environment.visit(Environment.java:330) at freemarker.core.Environment.visit(Environment.java:336) at freemarker.core.Environment.visit(Environment.java:336) at freemarker.core.Environment.process(Environment.java:309) at freemarker.template.Template.process(Template.java:384) at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleErrorInDevMode(DefaultDispatcherErrorHandler.java:118) at org.apache.struts2.dispatcher.DefaultDispatcherErrorHandler.handleError(DefaultDispatcherErrorHandler.java:76) at org.apache.struts2.dispatcher.Dispatcher.sendError(Dispatcher.java:912) at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:589) at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:79) at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:141) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.filters.CorsFilter.handleSimpleCORS(CorsFilter.java:259) at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:163) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1598) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745)

Error number 3 Delete Request : "Error: Ember Data Request DELETE http://localhost:8080/crud_ember_struts2/products/8 returned a 403 Payload (text/plain)

at ErrorClass.EmberError [as constructor] (http://localhost:4200/assets/vendor.js:41679:23)
at ErrorClass.AdapterError (http://localhost:4200/assets/vendor.js:69485:17)
at new ErrorClass (http://localhost:4200/assets/vendor.js:69503:24)
at Class.handleResponse (http://localhost:4200/assets/vendor.js:79151:18)
at ajaxError (http://localhost:4200/assets/vendor.js:79440:25)
at ajaxErrorHandler (http://localhost:4200/assets/vendor.js:79486:12)
at Class.hash.error (http://localhost:4200/assets/vendor.js:79231:23)
at fire (http://localhost:4200/assets/vendor.js:3632:31)
at Object.fireWith [as rejectWith] (http://localhost:4200/assets/vendor.js:3762:7)
at done (http://localhost:4200/assets/vendor.js:9876:14)"

Attached my codes below:

web.xml

    ```<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
  <display-name>crud_ember_struts2</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
     <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>http://localhost:4200</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Access-Control-Allow-Origin</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>1800</param-value>
  </init-param>
   </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <url-pattern>/**</url-pattern>
    </filter-mapping>
  <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>```

struts.xml

``` <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
    <constant name="struts.devMode" value="true" />
    <constant name="struts.convention.action.suffix" value="Controller"/>
    <constant name="struts.convention.action.mapAllMatches" value="true"/>
    <constant name="struts.convention.default.parent.package" value="rest-default"/>
    <constant name="struts.convention.package.locators" value="controller"/>
    <constant name="struts.rest.content.restrictToGET" value="false"/>

   <package name="default" namespace="/" extends="rest-default,json-default">
        <interceptors>
            <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/>
            <interceptor-stack name="myStack">
            <interceptor-ref name="json">
                <param name="contentType">application/json</param>
            </interceptor-ref>
            <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>
        <default-interceptor-ref name="myStack" />
        <global-allowed-methods>index,show,create,update,edit,editnew,deleteConfirm,destroy</global-allowed-methods>
        <action name="products/*" class="controller.ProductsController">
            <result name="index" type="json"></result>
        </action>
   </package>
</struts>```

ProductsController.java:

```package controller;
import java.util.List;
//import javax.servlet.http.HttpServletRequest;
import dao.Productdao;
import model.product;
//import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;
import com.opensymphony.xwork2.ModelDriven;
//import org.json.simple.*;
/*import org.apache.struts2.convention.annotation.Results;
import org.apache.struts2.convention.annotation.Result;


@Results({
    @Result(name="index", type="json", params = {"actionName" , "product"})
})*/
public class ProductsController implements ModelDriven<Object>{
    //private static final Logger log = LogManager.getLogger(ProductsController.class);
    product p=new product();
    Productdao dao=new Productdao();
    private List<product> productlist=dao.getAllProduct();
    private int id;
    private String name;
    private double price;
    //private HttpServletRequest request;
    //private JSONObject Object;

    public HttpHeaders show()
    {
        System.out.println("Showing");
        p=dao.getProduct(id);
        return new DefaultHttpHeaders("show");
    }

    public HttpHeaders index() {
        System.out.println("i am inside index");
        return new DefaultHttpHeaders("index").disableCaching();
    }

    public String edit()
    {
        System.out.println("came for editing");
        return "edit";
    }

    public String editNew()
    {
        System.out.println("here in edit new");
        return "editNew";
    }

    public String create()
    {
        System.out.println("order creation : "+name+price);
        boolean result=dao.createProduct(name,price);
        if(result)
        {
            System.out.println("product created successfully");
            return "success";
        }
        else
        {
            System.out.println("product Not created");
            return "increated";
        }
    }

    public String update()
    {
        System.out.println("inside update");
        p.setId(id);
        p.setName(name);
        p.setPrice(price);
        boolean result=dao.updateProduct(p);
        if(result)
        {
            System.out.println("product updated successfully");
            return "success";
        }
        else
        {
            System.out.println("product not updated");
            return "inupdated";
        }
    }
    public String destroy()
    {
        System.out.println("inside destroy");
        boolean result=dao.deleteProduct(id);
        if(result) {
            System.out.println("deleted successfully");
            return "success";
        }
        else
        {
            System.out.println("Not deleted");
            return "indeleted";
        }
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    /*public JSONObject getObject() {
        return Object;
    }

    public void setObject(JSONObject object) {
        Object = object;
    }

    public HttpServletRequest getRequest() {
        return request;
    }

    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }*/

    @Override
    public Object getModel() {
        System.out.println("getting model");
        return productlist;
    }

}
```

product.java:

```package model;

public class product {
    private int id;
    private String name;
    private double price;
    public product() {

    }

    public product(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        System.out.println("to stringing");
        return "{\nid: " + id + ",\nname: " + name + ",\nprice: " + price + "\n}";
    }
}
```

productdao.java :

```package dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.product;
import util.DBConnect;

public class Productdao {
    public List<product> getAllProduct()
    {
        List<product> list=new ArrayList<>();
        String query="select * from demotable";
        try {
            ResultSet rs=DBConnect.getConnection().createStatement().executeQuery(query);
            while(rs.next())
            {
                list.add(new product(rs.getInt("id"),rs.getString("name"),rs.getDouble("price")));
            }
            rs.close();
            return list;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public boolean createProduct(String name,double price)
    {
        String query="insert into demotable(name,price) values(?,?)";
        try {
            PreparedStatement pst=DBConnect.getConnection().prepareStatement(query);
            System.out.println(name);
            System.out.println(price);
            pst.setString(1,name);
            pst.setDouble(2,price);
            int bool=pst.executeUpdate();
            pst.close();
            if(bool>0)
                return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("i am caught help me");
            e.printStackTrace();
        }
        return false;
    }

    public boolean updateProduct(product p)
    {
        String query="update table demotable set name=? price=? where id=?";
        try {
            PreparedStatement pst=DBConnect.getConnection().prepareStatement(query);
            pst.setInt(1,p.getId());
            pst.setString(2,p.getName());
            pst.setDouble(3,p.getPrice());
            int bool=pst.executeUpdate();
            pst.close();
            if(bool>0)
                return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteProduct(int id)
    {
        String query="delete from demotable where id=?";
        try {
            PreparedStatement pst=DBConnect.getConnection().prepareStatement(query);
            pst.setInt(1,id);
            int bool=pst.executeUpdate();
            pst.close();
            if(bool>0)
                return true;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    public product getProduct(int id)
    {
        product p=new product();
        String query="select * from demotable where id="+id;
        try {
            ResultSet rs=DBConnect.getConnection().createStatement().executeQuery(query);
            if(rs.next())
            {
                p.setId(rs.getInt("id"));
                p.setName(rs.getString("name"));
                p.setPrice(rs.getDouble("price"));
            }
            rs.close();
            return p;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}```

app.js :

```import DS from 'ember-data';

export default DS.RESTAdapter.extend({
  host : "http://localhost:8080",
  namespace : "crud_ember_struts2",
  defaultSerializer: '-json-api'
});```

product.js

```import DS from 'ember-data';

export default DS.Model.extend({
  name : DS.attr('string'),
  price : DS.attr('number')
});```

routes:

create:

```import Route from '@ember/routing/route';

export default Route.extend({
  model()
  {
    //return this.store.createRecord('product');
  },
  actions:{
    create(record)
    {
      let post = this.store.createRecord('product',{
        name: record.nameInput,
        price:record.priceInput
      });
      post.save();
      post.rollbackAttributes();
    }
  }
});```

edit:

```import Route from '@ember/routing/route';

export default Route.extend({
  model(param)
  {
    idFixed: param.product_id;
    return this.store.findRecord('product',param.product_id);
  },
  actions:{
    edit(record)
    {
      console.log(record.idFixed);
      console.log(record.nameInput);
      console.log(record.priceInput);
      this.store.findRecord('product',record.idFixed).then(function(product){
        product.set('name',record.nameInput);
        product.set('price',record.priceInput);
        product.save();
      })
    }
  }
});```

delete:

```import Route from '@ember/routing/route';

export default Route.extend({
  model(param)
  {
    return this.store.findRecord('product',param.product_id,{backgroundReload: false}).then(function(product){
      product.destroyRecord();
    });
  }
});```

read:

```import Route from '@ember/routing/route';

export default Route.extend({
  model()
  {
    return this.store.findAll("product");
  }
});```

router.js

```import EmberRouter from '@ember/routing/router';
import config from './config/environment';

const Router = EmberRouter.extend({
  location: config.locationType,
  rootURL: config.rootURL
});

Router.map(function() {
  this.route('products');
  this.route('create');
  this.route('edit',{path:'products/:product_id'});
  this.route('delete',{path:'products/del/:product_id'});
});

export default Router;```



How do I understand this custom use of Promise in code

I use some Promise code used in my application as below;

import { Promise, resolve, all } from 'rsvp';


someAction: function(secId, fld, callback) {
    var self = this;
    var section = self.findSection(self.get('allSecs'), secId);
    var myPendingPromise = section.myPendingPromise || resolve();
    myPendingPromise = myPendingPromise.then(function(){
        return self.myCustomPromise(secId, fld, callback);
    });
    set(section, 'myPendingPromise', myPendingPromise);
},


myCustomPromise: function(secId, fld, callback){
    var self = this;
    return new Promise(function(resolve, reject){
        var deferred = self.myCustomRule(someFlds); //Makes an API call
        deferred.then(function(response) {
            resolve(response);
        }, function(){
            resolve(true);
        });
    });
},

Now, I am a bit confused why the following lines are added specifically;

var myPendingPromise = section.myPendingPromise || resolve();
myPendingPromise = myPendingPromise.then(function(){
    return self.myCustomPromise(secId, fld, callback);
});
set(section, 'myPendingPromise', myPendingPromise); 

Also, I did not find "myPendingPromise" used anywhere else apart from this function. Is there some pattern which I need to be aware of to be able to understand this code? It would be great to understand just the usage of these 3 lines of code above.




vendredi 27 décembre 2019

How do I turn off Percy snapshots for branches and most ember-try scenarios?

I am using Percy in the tests for an Ember Addon, but the Percy snapshots run 12 times for every pushed commit. I only want them to run for Pull Requests and the main version of my addon.

Here is why they run 12 times right now: - Once for every ember try scenario (6 times) - This is repeated for both PRs and branches pushed to GitHub

I am using Travis CI. How do I cut down the number of times that Percy snapshots run?




jeudi 26 décembre 2019

Nested Array to Query Params for Filters in Searching

I have:

[
    {
        id:
            eq: '1234'
    },
    {
        description:
            like: 'desc'
    }
]

How to transform it to query parameters to:

?filter[id][eq]=1234&filter[description][like]=desc

since the API needed the format like so for the filters?




How to populate an array of objects dynamically?

let products = [
  {
    name: "a",
    inventory: 1
  },
  {
    name: "b",
    inventory: 2
  },
  {
    name: "c",
    inventory: 3
  }
];

How can I go about creating these objects in an array like this dynamically ? Here is what I have been trying to do.

choicesHolder = [{name: '', inventory: ''}];
for(i; element.length<0; i--){
 
choicesHolder.push({"name": element.value, "inventory": element.selected});

element holds the data from the JSON.




mardi 24 décembre 2019

Ember Data. How to sent to the server attributes which are not defined in model?

If I receive extra attributes (which not defined in a model) from the server I will not store them in ember model. Thus on PUT or POST I will not send them to the server.

Is there a way to keep these extra attributes as "cashed data" and send them back to the server?




lundi 23 décembre 2019

Why is EmberJS adapter requesting content over HTTP When I've specified HTTPS?

In my set up currently, I have a certain model retrieving data from an azure serverless function. This function is served at

https://my-microservice.azurewebsites.net/api

For the adapter I have

...

export default DS.RESTAdapter.extend({
  ...

  host: config.serviceUrl,
  coalesceFindRequests: true,

  ...

});

and for the environment.js file, I have this line:

...

ENV.serviceUrl = 'https://my-microservice.azurewebsites.net/api';

...

Now, the odd part is that I have specifically set the URL for this service to be "https://" , but only some of my users are claiming that they get this error:

Mixed Content: The page at 'https://mywebsite.io' (index):1#/my-route/d1 was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://my-microservice.azurewebsites.net/api/<modelName>'. This request has been blocked; the content must be served over HTTPS.

What I don't understand is why this is happening in the first place - why am I getting a mixed content error when I am specifically asking Ember to use an https:// url for this adapter?

Additional info: 1. the data is being loaded via Ember-data, via an Ember model. The Ember model is told to use the given custom adapter. 2. Only some of my users are reporting this. When I try it myself, there are no such issues, which leads me to believe that there is some




dimanche 22 décembre 2019

Is there any "ember-moment-shim" alternative for dayJS?

ember-moment-shim is an ember addon that generates the locales conditionally based on Moment.js and Moment-Timezone.

Any tools or processes to accomplish the same with just DayJs instead.

Ref: https://github.com/jasonmit/ember-cli-moment-shim




samedi 21 décembre 2019

EmberJS: Emit event from Service to Route?

I'd like to be able to emit an event from a service, and setup my application Route to listen and act on that event.

app/services/service-action.js:

export default Ember.Service.extend({
  actionA() {
    this.trigger('actionA');
  }
});

app/routes/application.js:

export default Route.extend({
  serviceAction: service(),

  on('serviceAction.actionA', ()=>{
    console.log('actionA fired from serviceAction');
  })
});

Is this possible? Or is there an alternate design pattern I should use to solve this?




vendredi 20 décembre 2019

Is EmberData supports "ETag" caching?

Do I need to do something special to send "If-None-Match" header with appropriate ETag with each request in Ember application with EmberData? Assuming, that API returns valid ETag each time?




jeudi 19 décembre 2019

Return sum of expense on current month in Ember JS

I want to get my expenses sum, but filtered by the current month.

expenses: computed('transactions.length', 'transactions.@each.amount', function() {
  return this.get('transactions').filterBy('typeOfT','expense').sortBy('date')
}),

filteredExpenses: computed('expenses.length', 'expenses.@each.amount', function() {
    let thisMonth = new Date().getFullYear()+'-'+(new Date().getMonth()+1)
return this.get('expenses').filterBy('date', 'thisMonth').mapBy('amount').reduce((a, b) => a + b, 0)
}),

So trying the filterBy('date', 'thisMonth') function didn't work. I thought this would be way easier, but it isn't. Using mapBy('amount') and reduce((a, b) => a + b, 0)I can get the array of all expenses and by using the function I calculate the sum.




mercredi 18 décembre 2019

Dark mode feature, changing img src in init() does not work

In the controller I have

  init(){
    this._super(...arguments);
    document.body.classList.add("darkMode");
    document.getElementById('mode').src = 'assets/images/logo-white'
  }

and in the handlebars:

<img id="mode" src="assets/images/logo-black.png" alt="white-theme" width="188px" height="56px">

While trying to apply a dark-theme to my project, I successfully added the class to it, but when I tried changing the logo img src by finding its id, it crashes (as in nothing is showing anymore), this is probably because the init() does everything before loading the actual image and cannot take the id from img. I have no solution to this yet, so any idea would be awesome.

I am doing it this way just to test, later I will add an if clause to test whether the user wants to have dark-mode on or not




Better fix than globally disabling prototype extension to use external library in app?

I am using PDF.js in my Ember app.

Sometime, I am getting an error, which seems to be caused by Ember extending array prototype and making them enumerable, as describe here

It seems that the problem is caused by Ember, since it's adding a number of methods on Arrays, but for some reason they are all enumerable which is the cause of the problem. When adding methods on e.g. Arrays and Objects, they should be set to enumerable = false, just like the native methods are.

One proposed solution to this that do work is to globally set the array extension to false like this

//config/environment.js

EmberENV: {
    EXTEND_PROTOTYPES: {
        String: true,
        Array: false,
        Function: true
    }
}

But this seems incredibly inefficient, as our app is already quite big and going back everywhere that there are array and transforming them into Ember arrays would be very tedious work.

Is there a better way to deal with this issue?

At first I was thinking it might be a polyfill issue with babel because of this

Found the issue - we are polyfilling Array.prototype.find.

But removing babel's polyfill does not fix the problem.

I don't understand how Ember is able to modify an external library method to extend it and then cause an error. I am kind of lost where to look at for a solution that does not involve globally modifying ember array's extension.

Any help would be greatly appreciated.

Thanks.




mardi 17 décembre 2019

Images are not loading that are referenced in CSS

images in are loading properly when I am running the application locally but even though images are appearing in the folder on Server but not being loaded in the Sources when I see them, in the same folder structure when ran locally they are being loaded - any help why would that happen? When even the folder contains the images. Here are 2 images I am posting - can somebody please suggest me something why doesn't it load - thank you - the below image is taken from url of the app hosted on the server. enter image description here

Here is the image from local url enter image description here

Here is the folder that shows the images are in the folder - any help please. Basically they are there but not showing in the browser or in sources when we debug the browser - any help would be very very appreciated - please - thank you. enter image description here




What are the difference between `property.[]` and `property` in computed properties

With ember.js, using computed properties, I can use either this:

myProp: computed('properties', function () { /* do stuff. */ });

Or this:

myProp: computed('properties.[]', function () { /* do stuff. */ });

What are the difference between these two approach? Which one should I use in what situation?




Setting raised = true to an ember button when on current page/template

   <div class="flex">
      <div class="layout-row layout-align-end-center">
        Overview
        Incomes
        Expenses
        Settings
      </div>
    </div>

So I am trying to set the raised=true whenever I am on certain page/template. The above code is from my application template. Is there any way of doing this using JS/Ember or should I just do it manually in each of my templates?




lundi 16 décembre 2019

Ember Fastboot redirect to external URL

I'm looking to 301 redirect to an external URL from within an Ember Route in Fastboot (based on the data returned by model()).

A solution, would be to access Express.js response object from within Ember, so I can call something like:

res.redirect(301, 'http://external-domain.com')?

However, I'm not entirely sure how res object can be accessed from within Ember. Fastboot exposes a response object, but it's not the same as the Express res.




Displaying Javascript variable into multiline in a div

I am getting dynamic variable from webservice. I want to add the empty space or breaktag tag in the javascript variable.

For eg:

let myVal = "myname 123456789 NZD".

when displaying in the UI I want to display the names like below in a single div

myname 
123456789
NZD

The variable name all are dynamic. I am using word-wrap: break-word.

But few text cut of eg:

firstname last
name 123456789.

How to achieve like below :

myname 
123456789 
NZD

I am using below css:

div{
    position: relative;
    top: 5px;
    left: 10px;
    width: 46%;
    min-height: 22px;
    height: auto;
    font-family: "Montserrat-SemiBold";
    font-size: 15px;
    font-weight: 600;
    font-stretch: normal;
    font-style: normal;
    line-height: 1.47;
    letter-spacing: normal;
    color: #000000;
    padding-bottom: 11px;
    word-wrap: break-word;
}



How to adapt createRecord().save() to expect empty response?

When persisting a record to the backend via createRecord('record-name').save(), my backend responds with a 200 and an empty body. The empty body causes the flow to break rasing an error.

How can I adapt on that situation w/o changing the backend?




samedi 14 décembre 2019

In Ember, how can I access the custom inflector defined in my initializers?

I'm defining custom inflector rules in app/initializers/custom-inflector-rules like so:

// app/initializers/custom-inflector-rules

import Inflector from 'ember-inflector';

export function initialize(/* application */) {
  const inflector = Inflector.inflector;

  // Tell the inflector that the plural of "campus" is "campuses"
  inflector.irregular('campus', 'campuses');
}

export default {
  name: 'custom-inflector-rules',
  initialize
};

How can I access my initialized inflector with these custom rules within my application?

For example, in a serializer file, I want to be able to call pluralize like so:

import ??? as Inflector from ???

Inflector.inflector.pluralize("campus"); // campuses



jeudi 12 décembre 2019

How to create a dynamic chart using ember-vega

Im trying to create a vega chart in an ember octane app but in doing so im able to render the chart once, but from then on, even if the values change, the chart doesn't get rerendered

the code im using is

component.ts

@tracked
  model!: any;

get chartData() {
    const data = this.model.data;
    return {
      table: data.map((datum: any) => {
        return {
          ...datum
        };
      })
    };
  }

chart.hbs


why isn't it not working, but at the same time doing set(this,"dataSource",this.model.data) works

dataSource: computed(function() {
    return emberArray([
        {"category": "A", "amount": 28},
        {"category": "B", "amount": 55},
        {"category": "C", "amount": 43},
        {"category": "D", "amount": 91},
        {"category": "E", "amount": 81},
        {"category": "F", "amount": 53},
        {"category": "G", "amount": 19},
        {"category": "H", "amount": 87}
    ]);
}),

data: computed('dataSource.{[],@each.amount}', function () {
    const dataSource = get(this, 'dataSource');
    return {
        table: dataSource.map((datum) => {
            // return a copy because Vega Vis will mutate the dataset.
            return {
                ...datum
            };
        })
    };
})



I want to create a ember table component whose value is updated dynamically [Ember.js]

when i bind a tracked variable to the ember table, this is the error that i get

Error: Assertion Failed: You attempted to update rows on <(unknown):ember472>, but it had already been used previously in the same computation. Attempting to update a value after using it in a computation can cause logical errors, infinite revalidation bugs, and performance issues, and is not supported.

rows was first used:

So how do i go about creating a table which changes the value according to the value in the tracked variable




mercredi 11 décembre 2019

Systematically submitting ember.js form in Vault UI not appending X-Vault-Token header

I'm trying to simplify logging into the Hashicorp Vault UI (https://learn.hashicorp.com/vault/getting-started/ui) when using Google Chrome.

I created a simple Chrome extension that uses chrome.identity.getAuthToken, signs a JWT claim against the service account I want to use, and auth's against the vault GCP auth method to get an access token. I'd like to redirect to the Vault UI and populate the token field with the token and click the Submit button for the user automatically.

However, when I click on the Submit field automatically I receive a permission denied, because I'm not sending the X-Vault-Token header with the automated click.

If I go through the flow, populate the token field and have the user click on the token field and then click on Submit, the relevant header is added to the form submission.

It's not immediately clear to me where the X-Vault-Token header is getting added and if this is a vault or ember.js interaction, and if this can be overcome systematically. Is this possible?




mardi 10 décembre 2019

Attempted to register a view with an id already in use: 2 - EmberJs

I am getting this following error when I am running an Ember application

Attempted to register a view with an id already in use: 2
  • can somebody please help me in finding what would be the reasons for this error and how to fix them - any help would be very very helpful as I am new to Ember - thanks a lot



Ember network call payload behind one call

I am sending a network call using ember.js

The event is triggered by a check box click that adds or removes an item from an array called features.

Currently if I click on the checkbox to add "edit users" to the array, the features array is updated and the update method in my account_owner model is triggered.

The users object is passed in to the update method and when I log user.features the array has all three items including the one that was just added.

before sending to the network I create a payload object that looks like:

payload: { features: ["employee advocacy", "other", "edit_users"]}

Here is my update method

  update(user) {
      var payload = {
        features: user.features
      };
      console.log("@@@payload", payload)
      console.log("@@@this.accountID", this.accountID)
      const url = `/api/accounts/${this.id}/account_owners/${this.id}`;
      return put(url, payload).then(() => this);
    },

When this sends to the network only 2 of the three features are sent. the paylod looks like:

payload: { features: ["employee advocacy", "other"]}

The thing is if I click the edit users check box again, edit_users is removed from the features array as well as the payload in the method when I log it but when the call is sent to the network all three items including edit_users show up in the payload. like this:

payload: { features: ["employee advocacy", "other", "edit_users"]}

It seems like data in the network call is behind one click but I can not figure out why this is working this way.




How to pass only model[0] to a component from the template in Ember?

I want to pass only the model[0] (first data element) to a component from the template. I have a route file as follows:

/order.js
export default Route.extend({

  firstIndex: computed('data', {
    get(){
    return Ember.get(this,'data[0]');
    }
  }),

  model(params) {
    return fetch(`/api/salesrowmodel/${params.order_id}`)
    .then(resp => resp.json())
    .then(function(data) {
      return {
        data,
      };
    });
  },
}); 

FirstIndex is a computed property to return first index data of the array. Now in the template, I want to pass the first index data to a component:

/order.hbs

<div class="Revenue-values"></div>

My sample model data is as follows:

[{
"OrderId": "406-5309498-5972326",
"revenueHeader": {
"Principal": 982.14,
"Product Tax": 117.86,
"Total": 1100
}},
{
"OrderId": "506-5234568-5934567",
"revenueHeader": {
"Principal": 382.54,
"Product Tax": 34.46,
"Total": 234
}}]

It shows the null or undefined object is being passed to order-details. Please help me with this error.




Regarding custom builds in Ember

How do I extend my custom environment (and build), for example, "staging" from production?

Ultimately I want to do ember build --environment=staging, reap the goodness and optimization provided by "production" build + want to provide some custom config.




jeudi 5 décembre 2019

Can't run ember test

After many successful times running ember test and ember test -s, I can't run either of them on a specific project. The only thing I can think of that happened since it last ran successfully is that Terminal.app crashed while ember test -s was running.

Now when I run ember test -s on that project, I always get this error:

Global error: Error: Assertion Failed: The initializer 'container-debug-adapter' has 
already been registered at http://localhost:7357/assets/vendor.js, line 38210


Global error: Error: Assertion Failed: The tests file was not loaded. Make sure your 
tests index.html includes "assets/tests.js". at http://localhost:7357/assets/vendor.js, line 38210


Error: Assertion Failed: The initializer 'container-debug-adapter' has already been 
registered at http://localhost:7357/assets/vendor.js, line 38210
Error: Assertion Failed: The tests file was not loaded. Make sure your tests 
index.html includes "assets/tests.js". at http://localhost:7357/assets/vendor.js, line 38210

If I try running ember test -s on a different project, it works fine. So it seems to me that there must be something untracked by git that is sitting somewhere in the project folder that causes this problem.

  • Ember: 3.14.1
  • Ember CLI:



How can I keep the state of radio buttons intact when looping through in ember?

I have a json file of questions in my public folder. I parsed that in my router and send it to my questionnaire template as theQuestions I want to loop through all the questionnaires on next and previous click. However I want the value to be highlighted when the user press previous button. I am storing the values on in an array storedValues when the user press next button.

This is my component-class

@tracked incrementQuestion = -1;
@tracked choicesHolder;
@tracked marked;
@tracked storedValues;


@action change(event) {
  this.marked = event.target.value;
}

//on Next Button Click
@action next() {
  if (this.incrementQuestion < this.args.theQuestions.length - 1) {
    this.choicesHolder = [];
    this.incrementQuestion++;

    this.args.theQuestions[this.incrementQuestion].choices.forEach(element => {
      this.choicesHolder.push(element.value);
    });
    this.storedValues[this.incrementQuestion] = this.marked;
    this.marked = null;
  }
}

//On Previous Button Click
@action previous() {
  if (this.incrementQuestion > 0) {
    this.choicesHolder = [];
    this.incrementQuestion--;

    this.args.theQuestions[this.incrementQuestion].choices.forEach(element => {
      this.choicesHolder.push(element.value);
    });

  }
}

This is my template


<Input id="admin" @name="choices" @value= @type="radio"  />
<label for="admin"></label> 


<button onclick=>Previous</button>
<button onclick=>Next</button>

this.args.theQuestions is coming from route




Ember Inspector doesn't detect ember-cli app

I'm running an ember-cli app. The Inspector (Chrome) says This webpage is not running Ember.js.

Looking at the source view on the browser, it includes

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">    
...
<script src="/ember-cli-live-reload.js" type="text/javascript"></script>

How can I get the Inspector to recognize it?




How to display nested JSON object in the next row of mdc-layout-grid in Ember?

I want to display a nested JSON object in the next row of the grid. I am using Ember and mdc-layout-grid.

My JSON data is as follows:

data = [{
"amzOrderId": "403-8957866-2673902",
"financialEventType": "SHIPMENT",
"timestamp": 1570025882722,
"numOfItems": 1,
"nested": [{
"amzOrderId": "405-3430902-0842748",
"financialEventType": "SHIPMENT",
"timestamp": 1570025882722,
"numOfItems": 1}]},
{
"amzOrderId": "171-9021455-7043516",
"financialEventType": "SHIPMENT",
"timestamp": 15700258888722,
"numOfItems": 1,
"nested":null,
}]

My hbs file to render:

<li class="sales-list-row">
  
    
      
        <h3 class="bought__value"></h3>
      
      
        <span class="purchased__text">Purchased</span>
        <h3 class="purchased__value"></h3>
      
      
        <h4 class="id__value"></h4>
              
    
  
</li>

Now I want to render "nested" object values just in the next row if it is present (move to next data[element] in case nested is null). How do I approach this problem? I have tried a few methods but they are not working.




mercredi 4 décembre 2019

Using parentView inside an Ember component

Inside an Ember component, what does using "parentView" as shown below represent ?

targetObject: alias('parentView')



Same resource for multiple routes - EmberJS

I would like use routes like:

/seller
/seller/
/seller/123
/seller/456

I define my route-setup like this:

this.route('seller', { path: '/seller' });
this.route('seller', { path: '/seller/:sellerId' });

In other words, I would like to use the same controller for these two routes, this works fine when I call route directly in browser but when I call

get(this,'router').transitionTo('seller', id);

Ocurrs a warning(I will update the question with the error that occurs), probaly because is the same name of controller.... What I can do?




lundi 2 décembre 2019

PDFJS: error on Text rendering for the PDF

Recently the PDF rendering get a messed up text layer where text gets duplicated with the grey colored overlay. No idea about how to fix it as when i remove textLayerFactory: new pdfjsViewer.DefaultTextLayerFactory() it works fine. but need this as if not is render as images which takes a lot of time for large documents

Im using pdfjsViewer.PDFPageView

my code as follows

 getPdf() {

    var pdfDocument;

    if ( this._state !== 'inDOM' ) return false;

    pdfjsLib.disableRange = true;
    pdfjsLib.disableStream = true;

    let self = this;
    pdfDocument = pdfjsLib.getDocument(this.src);
    pdfDocument.promise.then(function(pdf) {
      self.set( 'pdfDocument', pdf );
      self.set( 'maxNumPages',  pdf.numPages );
      self.set( 'prevBtnDisabled', true );
      self.set( 'documentRendered', true );

      self.setViewportWidth();
      self.renderPdf();
    });

    return pdfDocument;
  },

  renderPdf() {

    var pdf = this.pdfDocument,
        maxNumPages,
        pagePromise;

    if ( !pdf ) return false;

    maxNumPages  = this.maxNumPages;

    pagePromise = this.getAndRenderPage( pdf, 1 );

    Array.apply( null, new Array( maxNumPages - 1 ) ).forEach( ( value, index ) => {

      pagePromise = pagePromise.then( () => this.getAndRenderPage( pdf, index + 2 ) );
    } );
  },

  getAndRenderPage( pdf, index ) {

    return pdf.getPage( index ).then( page => this.renderPage( page, index ) );
  },


  renderPage( pdfPage, pageNum ) {

    var parentWidth       = this.$().parent().width(),
        pageViewportScale = ( parentWidth >= this.get( 'breakpoints.mobile' ) ) ? 1.5 : 1.3,
        viewport          = pdfPage.getViewport( { scale: parentWidth / pdfPage.getViewport( { scale: pageViewportScale } ).width } ),
        container         = this.$().find( '.pdf_viewer--container' )[ 0 ],
        pdfPageView;

    pdfPageView = new pdfjsViewer.PDFPageView( {
      container: container,
      id: pageNum,
      scale: viewport.scale,
      defaultViewport: viewport,
     textLayerFactory: new pdfjsViewer.DefaultTextLayerFactory()

    } );
    var pages = this.get('pages');
    // Associates the actual page with the view, and drawing it
     pages.push( pdfPageView );
    this.set( 'pages', pages );
    this.set( 'scale', viewport.scale );z

    pdfPageView.setPdfPage( pdfPage );

    return pdfPageView.draw();
  },

i have seen same kind of questioned asked and its for angular Im importing his image as for the reference in here to give a more explanation about the issue

enter image description here

Reported Issue PDFJS: Text layer rendering twice




dimanche 1 décembre 2019

Possible problem between heroku and parse server

I'm working on a application which uses parse server as api, i deployed both on heroku. When i try to save a user on my database i get this error: ParseError { code: 107, message: 'Received an error with invalid JSON from Parse: Cannot POST /classes/_User\n' }




How can i found the application id of my heroku application?

I have an ember project deployed on heroku and also an api to make graphs calculation. I have to set an appid to my api application, and i can't figure out where to find it. The api is a parse-server api, which is deployed on heroku.

if (environment === 'production') {
    ENV.APP.HOST = 'xxxxxx(my url).herokuapp.com'
    ENV.rootURL = null;
    ENV.locationType = 'hash';
    ENV.APP.applicationId = '(I don't know what to set here)'
  }

That's my code on environment.js