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




vendredi 29 novembre 2019

Is it necessary to import jquery in Ember CLI 1.13

I am working on an old project which uses Ember CLI 1.13.12 where every file (including app.js/controllers/routes/components) has the following import at the top

import $ from 'jquery';

I removed the above line from all the files and still the app is running perfectly with all jquery code ( using $() or this.$()).

I tried to find if jquery is enabled in any config file but I couldn't. Also, there is no optional-features.json file in the project where jquery-integration can be set to true.

So, is it necessary to import jquery in an Ember CLI 1.13 project?

Can we disable the default jquery in Ember CLI 1.13?

I am new to Ember and that too to an old version so finding it difficult to understand.




jeudi 28 novembre 2019

Emberjs - how to render nested route template without parent route content?

Summary

I want to continue to use nested routes but without displaying top level content when the nested route is accessed. I'm not sure this is possible ?

Detail

Initially my requirement was to to display a list of, eg, foods and offer the user the option to add a food item foods/add . Using the outlet tag at the top of the list template allowed a form to add a food item to become visible at the top of the list, transitioning back to food after the add resulted in the list being displayed without the form.

New Requirement

The requirement has now changed and it's necessary to show the form without the the contents of the list and after a succesful add show the list without any form.

Question

I know I could abandon the sub-routes approach and create a route such as food-add but is there any other way of preserving the sub-route (and the corresponding file structure, which I like) but allow the the template for foods/add to be rendered without the list content ?




mercredi 27 novembre 2019

Ember-cli is ignoring options .babelrc

I want to configure my Ember app to either ignore the data-stubs folder, or set compact to false so I can silence the following error during builds:

[Babel: my-app > applyPatches][BABEL] 
 Note: The code generator has deoptimised the styling of dev/my-app/tests/data-stubs/foo.js
 as it exceeds the max of 500KB.

Accepted answers on StackOverflow say to configure the .babelrc file, but that isn't working with ember-cli builds. Answer: BABEL Note: The code generator has deoptimised the styling of "app.js" as it exceeds the max of "100KB in Meteor

I made a .babelrc file in the root folder of my ember app and have tried many different configurations:

{
  "ignore": ["**/data-stubs/*.js", "tests/data-stubs/*", "*tests/data-stubs/*"], //do not translate our stub files
  "compact": false,
  "env": {
    "development": {
      "compact": false
    }
  }
}

None has any effect and always results in the The code generator has deoptimised the styling error message. I also put a .babelrc file into the data-stubs folder with the same settings as above, and that isn't working either.




mardi 26 novembre 2019

Ember.js: EmberObject.create error on computed property inside a mixin

I am upgrading my ember app from 3.9 to 3.10.

I started getting an error.

Assertion Failed: EmberObject.create no longer supports defining computed properties. Define computed properties using extend() or reopen() before calling create().

I am not 100% sure, but after some tracking down, this piece of code seems to be causing this error (the computed property inside this mixin).

import Mixin from '@ember/object/mixin';
import { get, set, computed } from '@ember/object';
import { inject as service } from '@ember/service';
import DS from 'ember-data';

const { PromiseArray } = DS;

export default Mixin.create({
  ajax: service(),
  intl: service(),

  patientAnalysis: computed(function() {
    return this.getPatientAnalysis();
  }),

This mixin is being imported and used in another component, like so

import Analyses from 'ui/mixins/components/patient/analyses';
[...]
export default Component.extend(Analyses, {

I have read a few thread about this specific error, such as this one, but I can't figure out exactly how to make this work. I am not even sure why I am getting this error from upgrading to version 3.10 as this does not seems to have been deprecated or removed in that version.

I tried rewritting my mixin as the example from the ember doc, but without success.

If anyone could help me out figure out what exactly is going on and how to fix it, that would be appreciated.




lundi 25 novembre 2019

How to disable checkbox in certain column Ember js?

**enter image description here** May I know how can I disable the rest of the checkbox except for step 2,3 and 4? Those checkbox are link from the checkbox component. And i link the checkbox component into route at columns propertyName:"active". Below is a part of the route code.

export default Route.extend({
    model() {
        let results = {
            workflow: {
                columns: [
                    {
                        "propertyName": "step",
                        "title": "Step",
                        editable: false
                    },
                    {
                        "propertyName": "workflowName",
                        "title": "Workflow Name",
                    },
                    {
                        "propertyName": "preferredName",
                        "title": "Your Company Preferred Name",
                    },
                    {
                        "propertyName": "active",
                        "title": "Active",
                        component: "adk-workflow-select-row",
                        editable: false
                    },
                    {
                        title: "Edit",
                        component: "edit-row",
                        editable: false
                    }],
                rows: [
                    {
                        step: '0',
                        workflowName: 'New',
                        preferredName: '新',
                    },
                    {
                        step: '1',
                        workflowName: 'Budget Approval',
                        preferredName: '预算批准',
                    },
                    {
                        step: '2',
                        workflowName: 'Creative',
                        preferredName: '创作的',
                    },
                    {
                        step: '3',
                        workflowName: 'Visualize',
                        preferredName: '想象',
                    },
                    {
                        step: '4',
                        workflowName: 'Implementation',
                        preferredName: '履行',
                    },
                    {
                        step: '5',
                        workflowName: 'In Play',
                        preferredName: '活性',
                    },
                    {
                        step: '6',
                        workflowName: 'Completed',
                        preferredName: '已完成',
                    },
                    {
                        step: '7',
                        workflowName: 'Canceled',
                        preferredName: '取消',
                    },
                ]
            },

This is the adk-workflow-select-row which is the checkbox component. The code below is how i render the checkbox at. This enable all the checkbox. But i only need step 2,3 and 4 checkbox to be enable.





dimanche 24 novembre 2019

Why is Ember-Cli 3.14 throwing an ESLint No-New-Mixin error

I have three custom mixins that no longer work in Ember-Cli 3.14 (I had to step back down to 3.13.2). All I get is an Ember error saying no-new-mixins for each of the mixins. While the WebUI compiles and is hosted, the WebUI that is accessible no longer works properly. The errors appear to be thrown by ESLint.

Has anyone else had this problem with Ember 3.14?

https://github.com/ember-cli/eslint-plugin-ember/blob/master/docs/rules/no-new-mixins.md

I am hesitant to capriciously ignore a rule just because it does not get along with a new version of Ember, but works in others. So, I am checking with SO first.




vendredi 22 novembre 2019

How to pass input data from template to the component class in ember?

I am trying to pass the data which is in the input field to the component class

This is my component-class alpha.js

@tracked choice;

    @action next() {
        this.choice = this.get('this.choice');
        console.log(this.choice);
    }

This is my template alpha.hbs

    <Input @value= type="text"  />
    <button onclick=>Next</button>

I am getting Uncaught TypeError: this.get is not a function

Any help would be appreciated. Thanks




Ember unknown relationship

I'm currently building software with Rails + Ember 3.12, but hitting a strange issue.

My models are the following:

// test-case-run
import DS from 'ember-data';
const { Model } = DS;

export default Model.extend({
  testCase: DS.belongsTo('test-case'),
  testCaseRunLogs: DS.hasMany('test-case-run-logs')
});

// test-case-run-log
import DS from 'ember-data';
const { Model } = DS;

export default Model.extend({
  testCaseRun: DS.belongsTo('test-case-run'),
  payload: DS.attr('')
});

And, my backend is returning the following payload:

{
  "data": {
    "id": "83",
    "type": "test_case_run",
    "relationships": {
      "test_case": {
        "data": {
          "id": "90",
          "type": "test_case"
        }
      },
      "test_case_run_logs": {
        "data": []
      }
    }
  }
}
{
  "data": {
    "id": "83",
    "type": "test_case_run",
    "relationships": {
      "test_case": {
        "data": {
          "id": "90",
          "type": "test_case"
        }
      },
      "test_case_run_logs": {
        "data": [
          {
            "id": "426",
            "type": "test_case_run_log"
          }
        ]
      }
    }
  },
  "included": [
    {
      "id": "426",
      "type": "test_case_run_log",
      "attributes": {
        "payload": "SCREENSHOT"
      },
      "relationships": {
        "test_case_run": {
          "data": {
            "id": "83",
            "type": "test_case_run"
          }
        }
      }
    }
  ]
}

I've got a custom adapter defining:

  pathForType(type) {
    return underscore(pluralize(type));
  }

So, I think that everything should go well.

However, when I get into the ember inspector, I've got the following: enter image description here

It seems that my relationship is not loaded properly. And, I cannot access any data, such as:

log.get('testCaseRun') // that is null 
run.get('testCaseRunLogs.length') // it returns 0 

This is quite strange, as my records are loaded in the store, but not their relationships. I have no idea on how to troubleshoot this, since the amount of information I can get from ember is quite limited (there is no error, the format looks good, ...).

Could someone help me to understand what's wrong with my calls? I've tried many things, such as renaming my models, but this does not improve the situation.

Moreover, this model is the only one, which I have problem with. All my other models don't have this problem. So, that's a bit weird.

Thanks a lot




jeudi 21 novembre 2019

EmebrJS + CKEDITOR error while adding links using its dialog box

Type of report

Links adding with CKEditor in chrome 78.0.3904.97 gives an error of following and i have checked latest firefox also and i can reproduce this

link.js?t=J8Q8:27 Uncaught TypeError: Cannot read property 'length' of undefined
    at CKEDITOR.dialog.onOk (link.js?t=J8Q8:27)
    at CKEDITOR.dialog.<anonymous> (ckeditor.js:613)
    at CKEDITOR.dialog.l (ckeditor.js:10)
    at CKEDITOR.dialog.fire (ckeditor.js:12)
    at button.onClick (ckeditor.js:637)
    at button.<anonymous> (ckeditor.js:575)
    at button.l (ckeditor.js:10)
    at button.fire (ckeditor.js:12)
    at button.click (ckeditor.js:574)
    at CKEDITOR.dom.element.<anonymous> (ckeditor.js:566)

reproduction steps

  1. enable links for CKeditor
  2. click the link icon in ckeditor toolbar
  3. it opens a dialog to add display name and the link
  4. adding link and display name 5.click ok

Expected result

close the dialog box and adding the link to the ckeditor text area

Actual result

dialog box is not closing and console gives

link.js?t=J8Q8:27 Uncaught TypeError: Cannot read property 'length' of undefined
    at CKEDITOR.dialog.onOk (link.js?t=J8Q8:27)
    at CKEDITOR.dialog.<anonymous> (ckeditor.js:613)
    at CKEDITOR.dialog.l (ckeditor.js:10)
    at CKEDITOR.dialog.fire (ckeditor.js:12)
    at button.onClick (ckeditor.js:637)
    at button.<anonymous> (ckeditor.js:575)
    at button.l (ckeditor.js:10)
    at button.fire (ckeditor.js:12)
    at button.click (ckeditor.js:574)
    at CKEDITOR.dom.element.<anonymous> (ckeditor.js:566)

Other details

  • Browser: chrome 78.0.3904.97 / firefox
  • OS:Mac
  • CKEditor version: 4.13.0
  • Installed CKEditor plugins:

Using CKEditor as Emberjs Component

components/ckeditor.js

import Ember from 'ember'; import config from 'project/config/environment';

export default Ember.Component.extend( {

  allowLinks: true,

  didInsertElement: function() {

    var self        = this,
        $textarea   = this.$().find( 'textarea' )[0],
        ckconfig    = {

          toolbarGroups: [

            { name: 'styles' },
            { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
            { name: 'paragraph',   groups: [ 'list' ] },
            { name: 'others' },
            { name: 'clipboard',   groups: [ 'undo' ] },
            { name: 'editing',     groups: [ 'find', 'selection' ] },
                { name: 'colors' }
          ],
          removeButtons: 'Subscript,Superscript,Cut,Copy,Paste,PasteText,PasteFromWord,Anchor,Styles,Font,FontSize,Find,Replace,SelectAll,BGColor',
          format_tags: 'h1;p',
          removeDialogTabs: 'link:advanced;link:target',
          removePlugins: 'magicline',
          disallowedContent :  {
            '$1': {
              styles: 'color'
            }
          }

        },
        outputRules = {

          indent: false,
          breakBeforeOpen: false,
          breakAfterOpen: false,
          breakBeforeClose: false,
          breakAfterClose: false
      };

    // custom config
    if ( this.get( 'allowLinks' ) ) ckconfig.toolbarGroups.splice( 3, 0, { name: 'links' } );

    CKEDITOR.config.customConfig    = false;
    CKEDITOR.config.defaultLanguage = 'en';
    CKEDITOR.config.language        = 'en';
    CKEDITOR.config.contentsCss     = config.baseURL + 'ckeditor.css' ;
    CKEDITOR.config.height          = 420;
    CKEDITOR.config.skin            = 'bootstrapck,' + config.baseURL + 'assets/bootstrapck/';
    CKEDITOR.config.colorButton_colors = '0000FF,FFA500';
    CKEDITOR.config.colorButton_enableMore = false;

    CKEDITOR.on( 'instanceReady', function(e) {

      e.editor.dataProcessor.writer.setRules( 'h1', outputRules );
      e.editor.dataProcessor.writer.setRules( 'p', outputRules );
      e.editor.dataProcessor.writer.setRules( 'ol', outputRules );
      e.editor.dataProcessor.writer.setRules( 'ul', outputRules );
      e.editor.dataProcessor.writer.setRules( 'li', outputRules );
    } );

    CKEDITOR.on( 'dialogDefinition', function(e) {

      var dialogName       = e.data.name,
          dialogDefinition = e.data.definition;

      if ( dialogName === 'link' ) {

        dialogDefinition.onShow = function () {

            var dialog        = CKEDITOR.dialog.getCurrent(),
                linkType      = dialog.getContentElement( 'info' , 'linkType' ),
                anchorOptions = dialog.getContentElement( 'info' , 'anchorOptions' ),
                emailOptions  = dialog.getContentElement( 'info' , 'emailOptions' ),
                protocol      = dialog.getContentElement( 'info' , 'protocol' );

            linkType.getElement().hide();
            anchorOptions.getElement().hide();
            emailOptions.getElement().hide();
            protocol.disable();
        };
      }
    } );

    Ember.run( function() {

      $textarea.value = self.get( 'value' ) || '';

      CKEDITOR.replace( $textarea, ckconfig ).on( 'change', function(e) {

        self.set( 'value', e.editor.getData() );
      } );
    } );
  }
} );

anyone has any idea how can i fixed it ? i have checked their github issues as well but unfortunately i couldn't find any thing




how to convert UTC time to specified format in momentjs in ember helper

i am working in ember with moment js. this below code convert my local time to UTC format

and output is like Tue Nov 26 2019 00:00:00 GMT+0000.

But i want to display the output like Tue, 26 Nov, 2019.

i tried moment-format for utc time but no luck




Ember Test for parent route with method calls

I was brought in on the "back-end" of a project and asked to help write tests for an app. I am very new to Ember and need just a little help getting started. We are trying to provide unit test for the routes, so we can have a bit more molecular scope over the app, instead of acceptance test. I have looked at some tutorials and went through every possible scenario that I could think of. I just need a bit of jumpstart.

Here is the part of the route.js for this route.

  • down stream of this parent route, we have another nested route that shows a list of contacts and when a user clicks on a show button it calls "model" and returns that variable "rec" for the template and the url


export default Route.extend(ScrollTo, {
  flashMessages: service(),

  model: function(params) {
    let rec= this.store.peekRecord('contact', params.contact_id);
    return rec;
  },

  actions: {
    saveContact: function() {
      let model = this.currentRouteModel();
      model
        .save()
        .then(() => {
          //this.refresh();
          //this.setModelHash();
          this.flashMessages
            .success(`Saved Contact: ${model.get('title')}`);

          //this.transitionTo('contacts');
        });
    }

Here is pre-generated code for the test. I really haven't made any modifications, because I really didn't know where to start.

  • This app doesn't have a back-end, it's design is to take in information and provide a iso file based on whatever standard the user wants.
  • I am sure I need to provide some mock data for the test and send that to the method, but again I am not sure what Qunit parts I use.
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';

module('Unit | Route | contact/show', function(hooks) {
  setupTest(hooks)

  test('it exists', function(assert) {
    var route = this.owner.lookup('route:contact/show');
    assert.ok(route, 'contact.show route works');
  });
});



uniq() returns a duplicate record

I'm using ember 2.6 and the uniq() return a duplicate records even if I used the uniq()

Even if I used the uniq it does still return the duplicate records, my question is my approach below is to return the uniq but it still return a duplicate record

foos: computed.alias('model.foos'),
bars: computed.mapBy('foos', 'bar.content'),
uniqBars: computed.uniq('bars'),



mercredi 20 novembre 2019

How to avoid downloading js files and authentication ember SPA

We have an ember single page application. On a specific page, while clicking on a hyperlink, I want to open a specific route in the new window.

The problem here is, it starts downloading all the js files (main.js) and authenticating the session and then only it is loading the route. This is taking too much time and giving a poor user experience. Since the hyperlink can be clicked only when the user is already logged in, is there a way to avoid downloading all the js files and authentication in ember? Something like a child window of the current window, so that the route will be loaded immediately.




EmberJS: queryRecord - adapter returns a JSON object but the call ultimately returns null

I am dumbfounded and have a hard time debugging this.

This is my adapter, it returns a settings object.

import DS from "ember-data";
import * as authServer from "doodledocs-app/config/auth-ms";
import DataAdapterMixin from "ember-simple-auth/mixins/data-adapter-mixin";

export default DS.RESTAdapter.extend(DataAdapterMixin, {
  authorizer: "authorizer:devise",
  async queryRecord(store, type, data) {
    const response = await fetch(`${authServer.HOST}/settings`, {
      method: "GET",
      headers: { Authorization: data.token }
    });
    const json = await response.json();
    console.log("res settings", json); //this works
    return json; //it doesn't matter what I return, queryRecord ultimately returns null
  }
});

It returns: settings {id: 1, pencil_thickness: 1, pencil_pressure_sensitivity: 1, eraser_thickness: 20, annotation_options: true, …}

The model is straightforward:

import DS from "ember-data";

export default DS.Model.extend({
  user: DS.belongsTo("user"),
  pencil_thickness: DS.attr("number"),
  pencil_pressure_sensitivity: DS.attr("number"),
  eraser_thickness: DS.attr("number"),
  annotation_options: DS.attr("boolean")
});

This is my route of settings.js

import Route from "@ember/routing/route";
import { inject as service } from "@ember/service";

export default Route.extend({
  session: service(),
  async model() {
    const session = this.session.data.authenticated;
    const result = await this.store.queryRecord("settings", session);
    console.log("result", result); //this returns null...
  }
});

How come that it returns null and not the settings record?




Manually trigger keyboard on IOS devices (via javascript)

I encountered the following issue:

I have input in modal window and want to trigger keyboard once modal is open, example:

HTML:
<input type="search" />

JS:
didOpen () {
    ...

    input.focus();

    ...
},

but on IOS devices keyboard isn't opened. Maybe you know some workaround to implement it?




lundi 18 novembre 2019

How to reload the data in an ember-light-table from the database without a page refresh

Currently I have an ember-light table which is connected to a model from a django database. New things are pushed into this database all the time and I need my table to be up to date.

At the moment I refresh the page every minute which fetches from the database if the cache is old (using store.query). However, this causes the page to reload everything and the page goes blank for a while.

Is it possible to reload the data from the django db and update the table and have the table stay on screen the whole time?

Route:

  actions: {
  refresh: function () {
    this.refresh();
  }
},



Write Ember Octane Component test to check if state is correct after I submit a form?

I want to write a test such that when I submit a string, then a @tracked array =[0,0,0] field will change. I have a simple <Textarea @value= ></Textarea> for hbs.
if input is 1 then the tracked array becomes [0,1,0]. How do I do this?? So far I have the following code that DOESN'T work:

import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { click, render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | array', function(hooks) {
    setupRenderingTest(hooks);



    test('Textarea should display PLACE [0,1,0]"', async function(assert) {

        await render(hbs`<Array />`);
        assert.equal(find('textarea').value, 'testing"')
      });

});



dimanche 17 novembre 2019

Proper way to toggle classes in Ember Octane with Handlebars?

I want to toggle between class display on and display-off using Ember.js Octane. How do I do this? Do I need an @action or @tracked?

<img src="flower.jpg" alt="flower" class="display-on">  
or
<img src="flower.jpg" alt="flower" class="display-off"> 



How do I write a scanner to get string commands in a text file?

I have a text file which needs to be scanned for commands which need a required format.
The commands must be in the following order and aren't string sensitive however integers must be of length 1.

1) START 2,4,GO
2) Like
3) ATE, SWAM, SING, DANCE

Note, 3rd command has to be one of those 4. What's the best way to do this? Should I make an array and then use regexp? Seems complicated...




samedi 16 novembre 2019

Tricky RegExp question? How would I do this?

I want a simple validation and case of words don't matter. How would I do this? Preferably I'd like to do this using RegExp and I'll have an array of strings. i.e.) LOCaTe 9,0,uP

I have a simple array ["Locate", "9", "," ,"4", "up"] . This array will work. If I have an array like ["Locate"," asdf", "9", "," ,"4", "up"] that array wont work. It has to be a string then number then comma then number then string.




how can i understand ,which ember addon version compatibility with ember-cli or node version

I have not much experienced in Ember dependency

I have searched but i can not find which ember addon version compatibility with ember-cli or node version

I can find only this ember-cli node support https://github.com/ember-cli/ember-cli/blob/master/docs/node-support.md

Do I have to experience all , I can only guess version compatibility

For example : ember-simple-auth@2.1.0 compatible with ember-cli 3.x , ember-simple-auth@1.1.0 compatible with ember-cli 2.x

https://www.npmjs.com/package/ember-simple-auth/v/2.1.0

In the topic "Basic Usage" , i saw the Ember code syntax then this is it

For example : nodejs v6.x , npm v3.x, ember-cli 2.13 , Let's say it is working i want to add "ember-cli-sass" , which version i must choose ?

Is there a way to find out or isn't there something like that

Thanks




vendredi 15 novembre 2019

Running ember tests with Chrome in separate container

I have a gitlab pipeline that runs our acceptance tests in containers. I have access to a chromedriver service that runs in a container and is available on port 4444. The problem is I can't figure out what config to use to tell the tests to use Chrome on that port. Is this even possible?




Add a parent route in ember for existing routes

Here is my problem, assume I am having an ember app with following ember route configuration:

Router.map(function() {
  this.route('todos', function() {
    this.route('new');
    this.route('view', {
      path: "/:id"
    });
  });
  this.route('articles', function() {
    this.route('view', {
      path: "/:id"
    });
    this.route('new');
  });
});

Now i want to add the add the prefix for each route based on some user information i would be fetching. For eg: Below are the two user information

dev = {
 id: 1, 
 workspace: 'DEV'
}
qa = {
 id: 2,
 workspace:'TEST'
} 

once the dev is landing in the app, route must be like: todos:

/DEV/todos/new

and same for the other users. once the qa is landing in the page, route must be like:

/TEST/todos/new

to solve this i know we generate the parent route and add all the other route as child, need to change the file structure for this case.

Here is Ember :

ember-cli: 2.13.3,
ember-data: 2.18.5



Cookies are cleared on every page navigation (on development)

Happens Only On The Development Environment

On an Ember + Ember-Simple-Auth (CookieStore) SPA with Rails + Devise on the backend I have the situation that every time I navigate somewhere (different URLs, reload on the same URL) the cookies are cleared by default and I can't find where this happens.

Once I reload the cookies that are sent to the backend are already cleared, which makes me guess that it's not Rails that's doing that.




jeudi 14 novembre 2019

How to build CSS/PostCSS only during CSS changes?

Everytime I update .js code in my Ember App (components, tests, etc.) my app.css file is rebuilt, even though I'm not touching any CSS!

I am using PostCSS and TailwindCSS plugin. Every time I save a .js the entire TailwindCSS library is rebuilt and takes 1200-2000ms. This is really unnecessary and I would like to know how to avoid it. If I disable TailwindCSS the rebuild time of PostCSS drops to 191ms on every .js save.

There are a few solution ideas I'd like to explore:

  1. Is it possible to configure Ember rebuild my CSS ONLY when I change CSS?
  2. Is it possible to configure PostCSS to rebuild only when CSS has changed?
  3. How can I configure TailwindCSS to use a static CSS file, and then setup PostCSS to build only my custom tailwind configurations using the tailwind plugin?

ember-cli-build.js

    postcssOptions: {
      compile: {
        plugins: [
          {
            module: require("postcss-import"),
            options: {
              path: ["node_modules"]
            }
          },
          require("tailwindcss")("./config/tailwind.config.js")
        ]
      }
    }

config/tailwind.config.js

module.exports = {
  theme: {
    extend: {
      height: {
        "80": "20rem",
        "screen-80": "80vh",
        "screen-60": "60vh"
      },
      minWidth: {
        "96": "24rem",
        screen: "100vw"
      },
      maxWidth: {
        "min-content": "min-content",
        screen: "100vw"
      },
      screens: {
        xxl: "1920px"
      },
      zIndex: {
        "9999": 9999
      },
      colors: {
        puke: {
          100: "#fff5f7",
          200: "#fed7e2",
          300: "#fbb6ce",
          400: "#f687b3",
          500: "#ed64a6",
          600: "#d53f8c",
          700: "#b83280",
          800: "#97266d",
          900: "#702459"
        }
      },
      backgroundColor: theme => theme("colors"),
      textColor: theme => theme("colors"),
      borderColor: theme => ({
        ...theme("colors"),
        default: theme("colors.gray.300", "currentColor")
      })
    }
  },
  variants: {},
  plugins: []
};




mercredi 13 novembre 2019

Using result of one helper function in another helper function within Handlebars

I am checking if there is anyway that I can use the result of one helper function in another helper function and how can I use it, for example, I am looping through as below And then if I am getting an another element as below, using the same index: Then how can I use this element that we have got in a statement like below, to check if that is first or last element etc? Any help please - thanks in advance




How do I make an optional action for an Octane component?

I want to write an Octane/Glimmer style component where passing in the action is optional. What is the best way to write this?

For example, I want both of these uses of the component to be valid:

<MyComponent />
<MyComponent @validate= />

Right now, my component class has a lot of code that looks like this, checking to see if an action was passed in before calling it:

if (this.args.validate) {
  this.args.validate()
}

That works fine for one action, but not if I need to call several optional methods in succession. What other options are there?