问:
Jackson Mapper returning null with spring rest
I am getting Json from this link

I am using following two pojo classes for mapping .

1)NewsSource.class

```<code>@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "status", "sources" })
public class NewsSource {

    @JsonProperty("status")
    private String status;
    @JsonProperty("sources")
    private List<Source> sources = null;

    @JsonProperty("status")
    public String getStatus() {
        return status;
    }

    @JsonProperty("status")
    public void setStatus(String status) {
        this.status = status;
    }

    @JsonProperty("sources")
    public List<Source> getSources() {
        return sources;
    }

    @JsonProperty("sources")
    public void setSources(List<Source> sources) {
        this.sources = sources;
    }

}
</code>```

2)Source.class

```<code>    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({ "id", "name", "description", "url", "category", "language", "country", "sortBysAvailable" })

    public class Source {

        @JsonProperty("id")
        private String id;
        @JsonProperty("name")
        private String name;
        @JsonProperty("description")
        private String description;
        @JsonProperty("url")
        private String url;
        @JsonProperty("category")
        private String category;
        @JsonProperty("language")
        private String language;
        @JsonProperty("country")
        private String country;
        @JsonProperty("sortBysAvailable")
        private List<String> sortBysAvailable = null;
//getter setters generated with IDE , and annotated with @JsonProperty too
</code>```

I'm using this code to mapping json to pojo .

```<code> public NewsSource getNewsSource() {
        String URL = source_url; //above mentioned url to get json
ObjectMapper omapper= new ObjectMapper();
        omapper.setVisibilityChecker(omapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

   NewsSource newsSource =null;
        try {
        String result = restTemplate.getForObject(URL, String.class);
//result is returnning data properly
            omapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            newsSource = omapper.readValue(result, NewsSource.class);
//newsSource returnning null
}catch (Exception ex){

System.out.println("oooh exception ");
}
</code>```

I have tried many suggested tricks that are mentioned on this link but no one worked for me :)

Note: I am using following maven dependency for Jackson .

```<code>        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</code>```

Any suggestion would be appreciated. thanks in advance

Update
I have used following code .

```<code>    private static Object getJsonObject(String str) {
        Object obj = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            if (str != null) {
                obj = mapper.readValue(str, NewsSource.class);

            }
        } catch (Exception exc) {
            exc.printStackTrace();
        }
        System.out.println("json obj:===>" + obj);
        return obj;
    }

    public NewsSource getNewsSource() {
        String URL = source_url;

        NewsSource newsSource =null;
        try {
            String result = restTemplate.getForObject(URL, String.class);
            //String jsonStr=getJsonString(result);
            ObjectMapper mapper = new ObjectMapper();
        //    newsSource = mapper.readValue(result, NewsSource.class);

            newsSource= (NewsSource) getJsonObject(result);
            System.out.println("done:" +newsSource);
}catch (Exception ex){

System.out.println("oooh exception ");
}

        return newsSource;
    }
</code>```

StackTrace

```<code>    com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
 at [Source: {"status":"ok","sources":[{"id":"abc-news-au","name":"ABC News (AU)","description":"Australia's most trusted source of local, national and world news. Comprehensive, independent, in-depth analysis, the latest business, sport, weather and more.","url":"http://www.abc.net.au/news","category":"general","language":"en","country":"au","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"al-jazeera-english","name":"Al Jazeera English","description":"News, analysis from the Middle East and worldwide, multimedia and interactives, opinions, documentaries, podcasts, long reads and broadcast schedule.","url":"http://www.aljazeera.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"ars-technica","name":"Ars Technica","description":"The PC enthusiast's resource. Power users and the tools they love, without computing religion.","url":"http://arstechnica.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"associated-press","name":"Associated Press","description":"The AP delivers in-depth coverage on the international, politics, lifestyle, business, and entertainment news.","url":"https://apnews.com/","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"bbc-news","name":"BBC News","description":"Use BBC News for up-to-the-minute news, breaking news, video, audio and feature stories. BBC News provides trusted World and UK news as well as local and regional perspectives. Also entertainment, business, science, technology and health news.","url":"http://www.bbc.co.uk/news","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"bbc-sport","name":"BBC Sport","description":"The home of BBC Sport online. Includes live sports coverage, breaking news, results, video, audio and analysis on Football, F1, Cricket, Rugby Union, Rugby League, Golf, Tennis and all the main world sports, plus major events such as the Olympic Games.","url":"http://www.bbc.co.uk/sport","category":"sport","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"time","name":"Time","description":"Breaking news and analysis from TIME.com. Politics, world news, photos, video, tech reviews, health, science and entertainment news.","url":"http://time.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"usa-today","name":"USA Today","description":"Get the latest national, international, and political news at USATODAY.com.","url":"http://www.usatoday.com/news","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"}]}; line: 1, column: 402] (through reference chain: com.example.demo.dto.NewsSource["sources"]->java.util.ArrayList[0]->com.example.demo.dto.Source["sortBysAvailable"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
    at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)
    at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.handleNonArray(StringCollectionDeserializer.java:260)
    at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:187)
    at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:177)
    at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:20)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
    at com.example.demo.Utill.RuleUtill.getJsonObject(RuleUtill.java:80)
    at com.example.demo.Utill.RuleUtill.getNewsSource(RuleUtill.java:100)
    at com.example.demo.Service.NewsApiService.getSource(NewsApiService.java:32)
    at com.example.demo.Controller.Home.somespecific(Home.java:56)
    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 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    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:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    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)
json obj:===>null
done:null
</code>```

答:
The code is working correctly. Looks like you are using older version of jackson. I tested with 2.9.0 and below code is working as expected although with 2.9.0 version setVisibilityChecker(.....) is deprecated. </p>

```<code>public static void main(String[] args) {

    NewsSource nSource=new NewsSource();

    nSource.setStatus("status");

    Source source=new Source();

    source.setCategory("category");

    List<Source> sList=new ArrayList<Source>();
    sList.add(source);

    nSource.setSources(sList);

    String jsonStr=getJsonString(nSource);
    //{"status":"status","sources":[{"category":"category"}]}
    System.out.println(jsonStr);

    NewsSource newsSource =(NewsSource)getJsonObject(jsonStr);
    //NewsSource@1810399e
    System.out.println(newsSource);

}

private static String getJsonString(Object object) {
    String jsonString = "";
    try {
        ObjectMapper mapper = new ObjectMapper();
        if (object != null) {
            jsonString = mapper.writeValueAsString(object);
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    System.out.println("jsonString:===>" + jsonString);
    return jsonString;
}

private static Object getJsonObject(String str) {
    Object obj = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        if (str != null) {
             obj = mapper.readValue(str, NewsSource.class);

        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    System.out.println("json obj:===>" + obj);
    return obj;
}
</code>```

Body:
I am getting Json from this link

I am using following two pojo classes for mapping .

1)NewsSource.class

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "status", "sources" })
public class NewsSource {

    @JsonProperty("status")
    private String status;
    @JsonProperty("sources")
    private List<Source> sources = null;

    @JsonProperty("status")
    public String getStatus() {
        return status;
    }

    @JsonProperty("status")
    public void setStatus(String status) {
        this.status = status;
    }

    @JsonProperty("sources")
    public List<Source> getSources() {
        return sources;
    }

    @JsonProperty("sources")
    public void setSources(List<Source> sources) {
        this.sources = sources;
    }

}

2)Source.class

    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({ "id", "name", "description", "url", "category", "language", "country", "sortBysAvailable" })

    public class Source {

        @JsonProperty("id")
        private String id;
        @JsonProperty("name")
        private String name;
        @JsonProperty("description")
        private String description;
        @JsonProperty("url")
        private String url;
        @JsonProperty("category")
        private String category;
        @JsonProperty("language")
        private String language;
        @JsonProperty("country")
        private String country;
        @JsonProperty("sortBysAvailable")
        private List<String> sortBysAvailable = null;
//getter setters generated with IDE , and annotated with @JsonProperty too

I'm using this code to mapping json to pojo .

 public NewsSource getNewsSource() {
        String URL = source_url; //above mentioned url to get json
ObjectMapper omapper= new ObjectMapper();
        omapper.setVisibilityChecker(omapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

   NewsSource newsSource =null;
        try {
        String result = restTemplate.getForObject(URL, String.class);
//result is returnning data properly
            omapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            newsSource = omapper.readValue(result, NewsSource.class);
//newsSource returnning null
}catch (Exception ex){

System.out.println("oooh exception ");
}

I have tried many suggested tricks that are mentioned on this link but no one worked for me :)

Note: I am using following maven dependency for Jackson .

        <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

Any suggestion would be appreciated. thanks in advance

Update
I have used following code .

    private static Object getJsonObject(String str) {
        Object obj = null;
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            if (str != null) {
                obj = mapper.readValue(str, NewsSource.class);

            }
        } catch (Exception exc) {
            exc.printStackTrace();
        }
        System.out.println("json obj:===>" + obj);
        return obj;
    }

    public NewsSource getNewsSource() {
        String URL = source_url;

        NewsSource newsSource =null;
        try {
            String result = restTemplate.getForObject(URL, String.class);
            //String jsonStr=getJsonString(result);
            ObjectMapper mapper = new ObjectMapper();
        //    newsSource = mapper.readValue(result, NewsSource.class);

            newsSource= (NewsSource) getJsonObject(result);
            System.out.println("done:" +newsSource);
}catch (Exception ex){

System.out.println("oooh exception ");
}

        return newsSource;
    }

StackTrace

    com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token
 at [Source: {"status":"ok","sources":[{"id":"abc-news-au","name":"ABC News (AU)","description":"Australia's most trusted source of local, national and world news. Comprehensive, independent, in-depth analysis, the latest business, sport, weather and more.","url":"http://www.abc.net.au/news","category":"general","language":"en","country":"au","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"al-jazeera-english","name":"Al Jazeera English","description":"News, analysis from the Middle East and worldwide, multimedia and interactives, opinions, documentaries, podcasts, long reads and broadcast schedule.","url":"http://www.aljazeera.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"ars-technica","name":"Ars Technica","description":"The PC enthusiast's resource. Power users and the tools they love, without computing religion.","url":"http://arstechnica.com","category":"technology","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"associated-press","name":"Associated Press","description":"The AP delivers in-depth coverage on the international, politics, lifestyle, business, and entertainment news.","url":"https://apnews.com/","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"bbc-news","name":"BBC News","description":"Use BBC News for up-to-the-minute news, breaking news, video, audio and feature stories. BBC News provides trusted World and UK news as well as local and regional perspectives. Also entertainment, business, science, technology and health news.","url":"http://www.bbc.co.uk/news","category":"general","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"bbc-sport","name":"BBC Sport","description":"The home of BBC Sport online. Includes live sports coverage, breaking news, results, video, audio and analysis on Football, F1, Cricket, Rugby Union, Rugby League, Golf, Tennis and all the main world sports, plus major events such as the Olympic Games.","url":"http://www.bbc.co.uk/sport","category":"sport","language":"en","country":"gb","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"time","name":"Time","description":"Breaking news and analysis from TIME.com. Politics, world news, photos, video, tech reviews, health, science and entertainment news.","url":"http://time.com","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"},{"id":"usa-today","name":"USA Today","description":"Get the latest national, international, and political news at USATODAY.com.","url":"http://www.usatoday.com/news","category":"general","language":"en","country":"us","urlsToLogos":{"small":"","medium":"","large":""},"sortBysAvailable":"top"}]}; line: 1, column: 402] (through reference chain: com.example.demo.dto.NewsSource["sources"]->java.util.ArrayList[0]->com.example.demo.dto.Source["sortBysAvailable"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
    at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)
    at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.handleNonArray(StringCollectionDeserializer.java:260)
    at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:187)
    at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:177)
    at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:20)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:287)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:259)
    at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:26)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:504)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:104)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:276)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3814)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2858)
    at com.example.demo.Utill.RuleUtill.getJsonObject(RuleUtill.java:80)
    at com.example.demo.Utill.RuleUtill.getNewsSource(RuleUtill.java:100)
    at com.example.demo.Service.NewsApiService.getSource(NewsApiService.java:32)
    at com.example.demo.Controller.Home.somespecific(Home.java:56)
    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 org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    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:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    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)
json obj:===>null
done:null

Body:
The code is working correctly. Looks like you are using older version of jackson. I tested with 2.9.0 and below code is working as expected although with 2.9.0 version setVisibilityChecker(.....) is deprecated.

public static void main(String[] args) {

    NewsSource nSource=new NewsSource();

    nSource.setStatus("status");

    Source source=new Source();

    source.setCategory("category");

    List<Source> sList=new ArrayList<Source>();
    sList.add(source);

    nSource.setSources(sList);

    String jsonStr=getJsonString(nSource);
    //{"status":"status","sources":[{"category":"category"}]}
    System.out.println(jsonStr);

    NewsSource newsSource =(NewsSource)getJsonObject(jsonStr);
    //NewsSource@1810399e
    System.out.println(newsSource);

}

private static String getJsonString(Object object) {
    String jsonString = "";
    try {
        ObjectMapper mapper = new ObjectMapper();
        if (object != null) {
            jsonString = mapper.writeValueAsString(object);
        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    System.out.println("jsonString:===>" + jsonString);
    return jsonString;
}

private static Object getJsonObject(String str) {
    Object obj = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        if (str != null) {
             obj = mapper.readValue(str, NewsSource.class);

        }
    } catch (Exception exc) {
        exc.printStackTrace();
    }
    System.out.println("json obj:===>" + obj);
    return obj;
}


来源: stackexchange

问:
Dose an application (executable jar) need permission to listen on a port on centos?
I am running a Spring Boot application that I exported from Eclipse as an executable JAR. I have tested it on local host on a Windows machine, both in Eclipse and as an executable JAR.

On my local Windows machine, I can connect to the executable JAR’s REST API using RESTClient for Firefox. The executable also successfully sends a message to a remote server when it initialises on my windows device.

I am trying to deploy the executable to a CentOS device to test it. I have allowed all traffic through the firewall by setting the default for Input to accept using IP tables (I know, a very bad idea, but the device won't be alive for more than a few mins for a demo).

The executable JAR runs on the CentOS system. It says it is listening on port 8080, it successfully sends information to another remote server when initialised; but I cannot access the REST API delivered by the Spring application.

The executable launches on the CentOS server without any complication. I can ping the centOS server, I can SSH into the server; but when I try using RESTCLient to access the machine, I am told that the URL is invalid, and when I try make a GET request using my browser I am told the connection was reset. On the console for the spring application nothing registers when I try and make a connection to the device.

Can I deploy the application to the CentoOS server in this way or does it need additional permissions to listen to a port? Please Advises!

答:
Do you have a firewall activated?
So you have to open the port in the firewall settings:

```<code>firewall-cmd --zone=public --add-port=8080/tcp --permanent
</code>```

Then remember to reload the firewall for changes to take effect.

```<code>firewall-cmd --reload
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Do you have a firewall activated?
So you have to open the port in the firewall settings:

firewall-cmd --zone=public --add-port=8080/tcp --permanent

Then remember to reload the firewall for changes to take effect.

firewall-cmd --reload


问:
Degree of multiprogramming definition
What is the degree of multiprogramming in OS?
Is it the number of processes in the ready queue or the number of processes in the memory? </p>

答:
In a multiprogramming-capable system, jobs to be executed are loaded into a pool. Some number of those jobs are loaded into main memory, and one is selected from the pool for execution by the CPU. If at some point the program in progress terminates or requires the services of a peripheral device, the control of the CPU is given to the next job in the pool.

An important concept in multiprogramming is the degree of multiprogramming. The degree of multiprogramming describes the maximum number of processes that a single-processor system can accommodate efficiently.

These are some of the factors affecting the degree of multiprogramming:

The primary factor  is the amount of memory available to be allocated
to executing processes. If the amount of memory is too limited, the
degree of multiprogramming will be limited because fewer processes
will fit in memory.

Operating system - The means by which resources are allocated to processes. If the operating system
can not allocate resources to executing processes in a fair and
orderly fashion, the system will waste time in reallocation, or
process execution could enter into a deadlock state as programs wait
for allocated resources to be freed by other blocked processes.

Other factors affecting the degree of multiprogramming are program
I/O needs, program CPU needs, and memory and disk access speed.

Hope this answers you. :)

If not, You can get it in more detail here: http://www.tcnj.edu/~coburn/os

Title: Degree of multiprogramming definition


问:
margin text in TextBlock
Is it possible margin Text in TextBlock control ?

My style on textBlock control is here :

```<code><Style x:Key="InfosStyle" TargetType="{x:Type TextBlock}">
    <Setter Property="FontSize" Value="13"/>
    <Setter Property="FontWeight" Value="Normal"/>
    <Setter Property="Height" Value="35"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="TextAlignment" Value="Justify"/>
    <!--<Setter Property="BorderThickness" Value="1"/>-->
    <!--<Setter Property="BorderBrush" Value="#BFE3FE"/>-->
    <Setter Property="Background" Value="#BFE3FE"/>
    <Setter Property="Margin" Value="2,4,0,1" />
</Style>
</code>```

Result is here:

For examole I would like align or set margin on text in textBlock.

Now: |Chatuje  to |_Chatuje

I would like  have some free space on left side in TextBlock.

Free space TextOfTextBlock

No

TextOfTextBlock

答: Looks like you need to set Padding instead of Margin.</p>

Title: margin text in TextBlock

Body:
Is it possible margin Text in TextBlock control ?

My style on textBlock control is here :

Result is here:

For examole I would like align or set margin on text in textBlock.

Now: |Chatuje  to |_Chatuje

I would like  have some free space on left side in TextBlock.

Free space TextOfTextBlock

No

TextOfTextBlock

ContentLicense: CC BY-SA 2.5


问:
react native TextInput onBlur get unedfined at android
My react-native version is 0.38.0

```<code><TextInput onBlur={ (event) =>
   this.handleBlurCheck(event.nativeEvent.text,params) } />
</code>```

In function handleBlurCheck, I get the value at iOS, but I get undefined at Android.

How to get value when TextInput is blurred on android platform?

The nativeEvent object on iOS:

```<code>nativeEvent:{
    eventCount: 5,
    target: 1046,
    text: '56'
}
</code>```

The nativeEvent on Android:

```<code>nativeEvent:{
    target: 1046,
}
</code>```

答:
Documentation on the arguments is really limited:

https://facebook.github.io/react-native/releases/0.38/docs/textinput.html

Though as a walk around one can use

<TextInput
  onChangeText={(text) => this.setState({text})}
  onEndEditing={() => this.handleBlurCheck(this.state.text, params)}
/>
```

<hr>

<p><strong>UPD.</strong></p>

<p>Another working solution to consider would be:</p>

```<TextInput
  onEndEditing={(e) => this.handleBlurCheck(e.nativeEvent.text, params)}
/>
```

<p><strong>Detailed description:</strong></p>

<p>Looking at the source code it is obvious that what you get is exactly what is sent:
ReactTextInputBlurEvent.java
</p>

```private WritableMap serializeEventData() {
  WritableMap eventData = Arguments.createMap();
  eventData.putInt("target", getViewTag());
  return eventData;
}
```

<p>Unlike iOS code that has everything in place:
RCTEventDispatcher.m
</p>

```NSMutableDictionary *body = [[NSMutableDictionary alloc] initWithDictionary:@{
  @"eventCount": @(eventCount),
  @"target": reactTag
}];

if (text) {
  body[@"text"] = text;
}

if (key) {
  if (key.length == 0) {
    key = @"Backspace"; // backspace
} else {
  switch ([key characterAtIndex:0]) {
    case '\t':
    key = @"Tab";
    break;
    case '\n':
    key = @"Enter";
    default:
    break;
  }
}
body[@"key"] = key;
```

<p>However if we look at the "onEndEditing" event:
ReactTextInputEndEditingEvent.java
</p>

```private WritableMap serializeEventData() {
  WritableMap eventData = Arguments.createMap();
  eventData.putInt("target", getViewTag());
  eventData.putString("text", mText);
  return eventData;
}
```

the text property is set there.

Body:
My react-native version is 0.38.0

<TextInput onBlur={ (event) =>
   this.handleBlurCheck(event.nativeEvent.text,params) } />

In function handleBlurCheck, I get the value at iOS, but I get undefined at Android.

How to get value when TextInput is blurred on android platform?

The nativeEvent object on iOS:

nativeEvent:{
    eventCount: 5,
    target: 1046,
    text: '56'
}

The nativeEvent on Android:

nativeEvent:{
    target: 1046,
}

Body:
Documentation on the arguments is really limited:

https://facebook.github.io/react-native/releases/0.38/docs/textinput.html

Though as a walk around one can use

<TextInput
  onChangeText={(text) => this.setState({text})}
  onEndEditing={() => this.handleBlurCheck(this.state.text, params)}
/>

UPD.

Another working solution to consider would be:

<TextInput
  onEndEditing={(e) => this.handleBlurCheck(e.nativeEvent.text, params)}
/>

Detailed description:

Looking at the source code it is obvious that what you get is exactly what is sent:
ReactTextInputBlurEvent.java

private WritableMap serializeEventData() {
  WritableMap eventData = Arguments.createMap();
  eventData.putInt("target", getViewTag());
  return eventData;
}

Unlike iOS code that has everything in place:
RCTEventDispatcher.m

NSMutableDictionary *body = [[NSMutableDictionary alloc] initWithDictionary:@{
  @"eventCount": @(eventCount),
  @"target": reactTag
}];

if (text) {
  body[@"text"] = text;
}

if (key) {
  if (key.length == 0) {
    key = @"Backspace"; // backspace
} else {
  switch ([key characterAtIndex:0]) {
    case '\t':
    key = @"Tab";
    break;
    case '\n':
    key = @"Enter";
    default:
    break;
  }
}
body[@"key"] = key;

However if we look at the "onEndEditing" event:
ReactTextInputEndEditingEvent.java

private WritableMap serializeEventData() {
  WritableMap eventData = Arguments.createMap();
  eventData.putInt("target", getViewTag());
  eventData.putString("text", mText);
  return eventData;
}

the text property is set there.

ContentLicense: CC BY-SA 4.0


问:
Umlauts not working by exporting a CSV-File
i have a problem by exporting data with umlauts (like "ä", "ü" ...) in a CSV-File. I tried different solutions, but nothing works. Here is my code:

Controller:

```<code>  def bom_export
    @configurations = []
    @bom = []

    params[:configurations].each do |configuration_id|
      @configurations << Configuration::Configuration.find(configuration_id.to_i)
    end

    @configurations.each do |conf|
      conf.bill_of_materials.each do |material|
        @bom << material
      end
    end

    respond_to do |format|
      format.csv {
        csv_string = CSV.generate do |csv|
          csv << ["Id", "Titel", "Beschreibung", "Breite", "Höhe", "Länge"]
          @bom.each do |bom|
            csv << [bom.id, bom.title, bom.description, bom.width, bom.height, bom.length]
          end
        end

        c = Iconv.new('ISO-8859-15','UTF-8')
        send_data(c.iconv(csv_string),
                  :type => 'text/csv; charset=iso8859-1; header=present',
                  :filename => "test.csv")

      }
    end
  end
</code>```

Server-Log:

```<code>Started GET "/admin/customer_orders/61/configuration_configurations" for 127.0.0.1 at 2014-01-06 16:27:31 +0100

SyntaxError (/Users/shop-it1/workspace/shop/app/controllers/configuration/configurations_controller.rb:106: invalid multibyte char (US-ASCII)
/Users/shop-it1/workspace/shop/app/controllers/configuration/configurations_controller.rb:106: invalid multibyte char (US-ASCII)
/Users/shop-it1/workspace/shop/app/controllers/configuration/configurations_controller.rb:106: syntax error, unexpected $end, expecting ']'
… "Beschreibung", "Breite", "Höhe", "Länge"]
…                               ^):

Rendered /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (42.2ms)
Error during failsafe response: ActionView::Template::Error
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/core_ext/string/output_safety.rb:23:in `gsub'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/core_ext/string/output_safety.rb:23:in `html_escape'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb:7:in `___sers_shop_it___rvm_gems_ruby_______p__gems_actionpack________lib_action_dispatch_middleware_templates_rescues_diagnostics_erb___3189230765086009151_70220166701020_1793258824290671195'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/template.rb:135:in `block in render'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/notifications.rb:54:in `instrument'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/template.rb:127:in `render'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/render/rendering.rb:59:in `block in _render_template'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/notifications.rb:52:in `block in instrument'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/notifications.rb:52:in `instrument'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/render/rendering.rb:56:in `_render_template'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/render/rendering.rb:26:in `render'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/show_exceptions.rb:88:in `rescue_action_locally'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/show_exceptions.rb:68:in `render_exception'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/show_exceptions.rb:59:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/rack/logger.rb:13:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/runtime.rb:17:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/lock.rb:11:in `block in call'
  <internal:prelude>:10:in `synchronize'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/lock.rb:11:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/static.rb:30:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/application.rb:168:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/application.rb:77:in `method_missing'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/rack/log_tailer.rb:14:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/content_length.rb:13:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/chunked.rb:15:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:80:in `block in pre_process'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:78:in `catch'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:78:in `pre_process'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:53:in `process'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:38:in `receive_data'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run_machine'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/backends/base.rb:61:in `start'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/server.rb:159:in `start'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/handler/thin.rb:14:in `run'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/server.rb:217:in `start'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/commands/server.rb:65:in `start'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/commands.rb:30:in `block in <top (required)>'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/commands.rb:27:in `tap'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/commands.rb:27:in `<top (required)>'
  /Users/shop-it1/workspace/shop/script/rails:6:in `require'
  /Users/shop-it1/workspace/shop/script/rails:6:in `<top (required)>'
  -e:1:in `load'
  -e:1:in `<main>'
</code>```

After trying to save the CSV-File the server crashes (500). Without umlauts everything works fine.

答:
For me this did the trick

```<code>send_data(csv_string.encode("UTF-8"),
          :type => 'text/csv; charset=UTF-8; header=present',
          :filename => "test.csv")
</code>```

while

```<code># encoding: utf-8
</code>```

didn't help

Body:
i have a problem by exporting data with umlauts (like "ä", "ü" ...) in a CSV-File. I tried different solutions, but nothing works. Here is my code:

Controller:

  def bom_export
    @configurations = []
    @bom = []

    params[:configurations].each do |configuration_id|
      @configurations << Configuration::Configuration.find(configuration_id.to_i)
    end

    @configurations.each do |conf|
      conf.bill_of_materials.each do |material|
        @bom << material
      end
    end

    respond_to do |format|
      format.csv {
        csv_string = CSV.generate do |csv|
          csv << ["Id", "Titel", "Beschreibung", "Breite", "Höhe", "Länge"]
          @bom.each do |bom|
            csv << [bom.id, bom.title, bom.description, bom.width, bom.height, bom.length]
          end
        end

        c = Iconv.new('ISO-8859-15','UTF-8')
        send_data(c.iconv(csv_string),
                  :type => 'text/csv; charset=iso8859-1; header=present',
                  :filename => "test.csv")

      }
    end
  end

Server-Log:

Started GET "/admin/customer_orders/61/configuration_configurations" for 127.0.0.1 at 2014-01-06 16:27:31 +0100

SyntaxError (/Users/shop-it1/workspace/shop/app/controllers/configuration/configurations_controller.rb:106: invalid multibyte char (US-ASCII)
/Users/shop-it1/workspace/shop/app/controllers/configuration/configurations_controller.rb:106: invalid multibyte char (US-ASCII)
/Users/shop-it1/workspace/shop/app/controllers/configuration/configurations_controller.rb:106: syntax error, unexpected $end, expecting ']'
… "Beschreibung", "Breite", "Höhe", "Länge"]
…                               ^):

Rendered /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (42.2ms)
Error during failsafe response: ActionView::Template::Error
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/core_ext/string/output_safety.rb:23:in `gsub'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/core_ext/string/output_safety.rb:23:in `html_escape'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb:7:in `___sers_shop_it___rvm_gems_ruby_______p__gems_actionpack________lib_action_dispatch_middleware_templates_rescues_diagnostics_erb___3189230765086009151_70220166701020_1793258824290671195'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/template.rb:135:in `block in render'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/notifications.rb:54:in `instrument'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/template.rb:127:in `render'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/render/rendering.rb:59:in `block in _render_template'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/notifications.rb:52:in `block in instrument'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/notifications/instrumenter.rb:21:in `instrument'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/notifications.rb:52:in `instrument'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/render/rendering.rb:56:in `_render_template'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_view/render/rendering.rb:26:in `render'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/show_exceptions.rb:88:in `rescue_action_locally'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/show_exceptions.rb:68:in `render_exception'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/show_exceptions.rb:59:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/rack/logger.rb:13:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/runtime.rb:17:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/activesupport-3.0.10/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/lock.rb:11:in `block in call'
  <internal:prelude>:10:in `synchronize'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/lock.rb:11:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/actionpack-3.0.10/lib/action_dispatch/middleware/static.rb:30:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/application.rb:168:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/application.rb:77:in `method_missing'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/rack/log_tailer.rb:14:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/content_length.rb:13:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/chunked.rb:15:in `call'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:80:in `block in pre_process'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:78:in `catch'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:78:in `pre_process'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:53:in `process'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/connection.rb:38:in `receive_data'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run_machine'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/eventmachine-0.12.10/lib/eventmachine.rb:256:in `run'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/backends/base.rb:61:in `start'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/thin-1.3.1/lib/thin/server.rb:159:in `start'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/handler/thin.rb:14:in `run'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/rack-1.2.4/lib/rack/server.rb:217:in `start'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/commands/server.rb:65:in `start'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/commands.rb:30:in `block in <top (required)>'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/commands.rb:27:in `tap'
  /Users/shop-it1/.rvm/gems/ruby-1.9.3-p0/gems/railties-3.0.10/lib/rails/commands.rb:27:in `<top (required)>'
  /Users/shop-it1/workspace/shop/script/rails:6:in `require'
  /Users/shop-it1/workspace/shop/script/rails:6:in `<top (required)>'
  -e:1:in `load'
  -e:1:in `'

After trying to save the CSV-File the server crashes (500). Without umlauts everything works fine.

Body:
For me this did the trick

send_data(csv_string.encode("UTF-8"),
          :type => 'text/csv; charset=UTF-8; header=present',
          :filename => "test.csv")

while

# encoding: utf-8

didn't help


问:
How to generate output based on variable in a single spoon transformation?
I am new to pentaho. I am stuck with one issue.

I have a spoon transformation. I have an input file with data. Based on the input file, an output file need to be generated. My issue is how to generate output file with different file names based on input file.

Eg: I have an input file which has a field country( say USA). I need to generate an output xls file with this country at the end i.e. USA.xls
For that what I did is that I mapped the country field to a variable

${COUNTRY_NAME}

, so that I can use this variable while generating the output file name. But it is not working as expected.

I need to run this transformation multiple times based on input file. Each input file have country field with different country names. So I need to generate corresponding excel for each country.

Eg: In my first run I used a file with USA. now ${COUNTRY_NAME} is USA. The output file generated name ends with USA.xls. So far so good. But when I run the transformation  second time with AUS, the  ${COUNTRY_NAME} is still USA. The output file generated name ends with USA.xls not AUS.xls.

I have only one transformation. Please help me to generate xls file with different name based on input file.

Thanks in advance

答:
You cannot do that in a single transformation. The reason is that in a transformation all the steps run in parallel, so when it comes to writing to your output files, the data for US and AUS are still mixed in the processing pipeline.

When you need to do time related stuff, use a job. Basically you take your transformation as is, filtering the data based on the ${country} and putting it in a file named filename${country}.xls (yes you can, strings get concatenated).

The variable ${country} is defined in another transformation which reads your data, keep a Unique row by country, and Set Variables.

Then you make a job that reads the second transfo (define ${country}) and chain to the second (produce filename${country}.xls).

You have a sample folder, shipped with your PDI, that sits in the same directory as your spoon.bat/spoon.sh. The sample/job/run_all/Run all sample transformations.kjb does almost the same as what you want  to achieve.

I know, the first reaction is that it seams daunting for so simple a task. But when you will get used to the reasoning, you'll discover all the benefits of being able to control parallel processing in so simple a way.


问:
Locking a file while copying using Commons IO
I am using the Apache Commons IO:

```<code>     FileUtils.copyFileToDirectory(srcFile, destDir)
</code>```

How do I make Windows lock the destination file during copy? Windows locks the file correctly if I use:

```<code>      Runtime.getRuntime().exec(
      "cmd /c copy /Y \"" + srcFile.getCanonicalPath() + "\" \""
          + destDir.getCanonicalPath() + "\"").waitFor();
</code>```

Notes:
The contention is not with the local program, but an external one. The file is being copied to a remote system. The remote system is processing the file before it completes the copy. Because the systems are Windows, the normal copy locks the file and blocks the external program from access.

答:
When copying files, always copy to a temporary filename and rename the file when you are done writing. This way, another process can never see a corrupt file.

Even better, you can write to *.tmp. Then check if the destination file exists. Rename the dest file to *.bak if it exists. Lastly rename *.tmp -> dest.

OwnerDisplayName: Joshua

Body:
I am using the Apache Commons IO:

     FileUtils.copyFileToDirectory(srcFile, destDir)

How do I make Windows lock the destination file during copy? Windows locks the file correctly if I use:

      Runtime.getRuntime().exec(
      "cmd /c copy /Y \"" + srcFile.getCanonicalPath() + "\" \""
          + destDir.getCanonicalPath() + "\"").waitFor();

Notes:
The contention is not with the local program, but an external one. The file is being copied to a remote system. The remote system is processing the file before it completes the copy. Because the systems are Windows, the normal copy locks the file and blocks the external program from access.

LastEditorDisplayName: Joshua

OwnerDisplayName: Aaron Digulla


问:
Can I use Chinese characters in CSS class names?
Is it possible to use Chinese class names for my CSS classes? I'm trying to get the Chinese word with jQuery and then create img elements with classes named by the Chinese words.

I have for instance a file named 2020_Cars_哈喽_1.jpg, and I created a code that takes the year, the category (Cars), and the Chinese word which is the name of the album, and creates an img element with classes according to the file name in order to filter the images later.

I have an example here where you can see the categories which translated to classes without any problem, and the %46%bd% which are Chinese words that I could not transform successfully into a class name.

Any suggestions please?

The jQuery code which takes the file name and split it into classes:

```<code> $.ajax({
     url: dir,
     success: function(data){
         $(data).find("a:contains(.JPG)").each(function(){
             // will loop through
             var images = $(this).attr("href");
             var splittedName = images.split('_');
             var classesToAdd = 'thumbnailpic';
             for(var i=0;i<3;i++){
                 classesToAdd+=' '+splittedName[i];
             }

             if(years.indexOf(splittedName[0])===-1){
                 years.push(splittedName[0]);
             }
             if(categories.indexOf(splittedName[1])===-1) {
                 categories.push(splittedName[1]);
             }
             if(albums.indexOf(splittedName[2])===-1) {
                 albums.push(splittedName[2]);
             }

             $('.gallery').append('<img class="'+classesToAdd+'" src="'+dir+'/'+images+'"'+'>');

         });

         for(var a=0;a<years.length;a++){
             $('.years').append('<div id="filter-button" class="filter-select" >'+years[a]+'</div>');
         }

         for(var b=0;b<categories.length;b++){
             $('.categories').append('<div id="filter-button" class="filter-select">'+categories[b]+'</div>');
         }

         for(var c=0;c<albums.length;c++){
             $('.albums').append('<div id="filter-button" class="filter-select">'+albums[c]+'</div>');
         }
         hideBigPic();
         $('.filters').fadeIn(1000);
         $('.gallery').fadeIn(1000);
     }
 });
</code>```

Thank you in advance!

答:
Yes, you can use Chinese characters as class names and selectors.

div {
  width: 100px;
  height: 100px;
}

.tomato {
  background: tomato;
}

.蓝色 {
  background: navy;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="蓝色"></div>
<div class="tomato"></div>
<br>
<button onclick="console.log(document.querySelector('.蓝色'))">Find Element</button></code>```

But it looks like the real question here is how do you turn URL encoded characters (%46 etc) back into real characters and for that you need decodeURIComponent

console.log(decodeURIComponent('%E8%93%9D'))```

Hope this answers all of your questions.

Body:
Is it possible to use Chinese class names for my CSS classes? I'm trying to get the Chinese word with jQuery and then create img elements with classes named by the Chinese words.

I have for instance a file named 2020_Cars_哈喽_1.jpg, and I created a code that takes the year, the category (Cars), and the Chinese word which is the name of the album, and creates an img element with classes according to the file name in order to filter the images later.

I have an example here where you can see the categories which translated to classes without any problem, and the %46%bd% which are Chinese words that I could not transform successfully into a class name.

Any suggestions please?

The jQuery code which takes the file name and split it into classes:

 $.ajax({
     url: dir,
     success: function(data){
         $(data).find("a:contains(.JPG)").each(function(){
             // will loop through
             var images = $(this).attr("href");
             var splittedName = images.split('_');
             var classesToAdd = 'thumbnailpic';
             for(var i=0;i<3;i++){
                 classesToAdd+=' '+splittedName[i];
             }

             if(years.indexOf(splittedName[0])===-1){
                 years.push(splittedName[0]);
             }
             if(categories.indexOf(splittedName[1])===-1) {
                 categories.push(splittedName[1]);
             }
             if(albums.indexOf(splittedName[2])===-1) {
                 albums.push(splittedName[2]);
             }

             $('.gallery').append('');

         });

         for(var a=0;a<years.length;a++){
             $('.years').append('
'+years[a]+'
');
         }

         for(var b=0;b<categories.length;b++){
             $('.categories').append('
'+categories[b]+'
');
         }

         for(var c=0;c<albums.length;c++){
             $('.albums').append('
'+albums[c]+'
');
         }
         hideBigPic();
         $('.filters').fadeIn(1000);
         $('.gallery').fadeIn(1000);
     }
 });

Thank you in advance!

Body:
Yes, you can use Chinese characters as class names and selectors.

div {
  width: 100px;
  height: 100px;
}

.tomato {
  background: tomato;
}

.蓝色 {
  background: navy;
}

<div class="蓝色"></div>
<div class="tomato"></div>
<br>
<button onclick="console.log(document.querySelector('.蓝色'))">Find Element</button>

But it looks like the real question here is how do you turn URL encoded characters (%46 etc) back into real characters and for that you need decodeURIComponent

console.log(decodeURIComponent('%E8%93%9D'))

Hope this answers all of your questions.


问:
Linkage matrix value error: setting an array element with a sequence
enter image description hereI'm using Python, numpy and scipy to do some hierarchical clustering on the output of a topic model I created for text analysis.

I applied my testcorpus to the ldamodel so it became a bag-of-words representation. Then I turned it into a matrix. Now I want to use scipy to make a linkage matrix of my matrix. But it gives the Value Error: setting an array element with a sequence.
I guess that this is because only equally shaped arrays can be clustered. And my matrix has a difference in lengths between the lists inside the list of lists.
I just don't now how to solve this.
Here is a little part of the code. I don't know if it is helpful. I just really hope someone can help me.

```<code>  import numpy as np
  X = np.array(corpus)
  from matplotlib import pyplot as plt
  from scipy.cluster.hierarchy import dendrogram, linkage
  Z = linkage(X, 'cosine')
</code>```

答:
As you'd mentioned getting matrix X from lda model, it might be a sparse matrix of some sort. You can convert to dense matrix by X.todense() and apply the linkage method.If the matrix is too large to hold in the memory you can do
Z=linkage(X.todense(),distance='cosine').

In some cases, changing the dtype of matrix helps.

P.S : I too faced the same issue and converting my sparse feature matrix (scipy.sparse.csr matrix) to dense solved the issue.

Body:
enter image description hereI'm using Python, numpy and scipy to do some hierarchical clustering on the output of a topic model I created for text analysis.

I applied my testcorpus to the ldamodel so it became a bag-of-words representation. Then I turned it into a matrix. Now I want to use scipy to make a linkage matrix of my matrix. But it gives the Value Error: setting an array element with a sequence.
I guess that this is because only equally shaped arrays can be clustered. And my matrix has a difference in lengths between the lists inside the list of lists.
I just don't now how to solve this.
Here is a little part of the code. I don't know if it is helpful. I just really hope someone can help me.

  import numpy as np
  X = np.array(corpus)
  from matplotlib import pyplot as plt
  from scipy.cluster.hierarchy import dendrogram, linkage
  Z = linkage(X, 'cosine')


问:
NoClassDefFoundError: javax/xml/bind/UnmarshalException - Spring Security oauth2
Currently I'm working on securing a REST SpringBoot service. I've decided to use oauth2 with JWT. But I'm facing that strange error on application startup. I believe there must be some mistake on spring-security-core and spring-security-jwt versions. Here is stack:

```<code>    Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
    2017-11-17 11:47:34.428 ERROR 9604 --- [           main] o.s.boot.SpringApplication               : Application startup failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at
org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) [spring-boot-maven-plugin-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at java.base/java.lang.Thread.run(Thread.java:844) [na:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 26 common frames omitted
    Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer.geDefaultMessageConverters(DefaultOAuth2ExceptionRenderer.java:117) ~[spring-security-oauth2-2.2.0.RELEASE.jar:na]
...
        at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 27 common frames omitted
    Caused by: java.lang.ClassNotFoundException: javax.xml.bind.UnmarshalException
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:466) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:563) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496) ~[na:na]
        ... 51 common frames omitted
</code>```

Here is my pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

...

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>
    <!-- Dependency for embed mongo testing -->
    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <version>2.0.0</version>
        <scope>test</scope>
    </dependency>
    **<!-- Dependency for web security -->
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>3.2.10.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>**
</dependencies>

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

Is there anything that I've missed on that Configuration?

答:
You have to include Jaxb Api, so in your pom.xml you should add its dependency:

```<code><!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>
</code>```

Body:
Currently I'm working on securing a REST SpringBoot service. I've decided to use oauth2 with JWT. But I'm facing that strange error on application startup. I believe there must be some mistake on spring-security-core and spring-security-jwt versions. Here is stack:

    Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
    2017-11-17 11:47:34.428 ERROR 9604 --- [           main] o.s.boot.SpringApplication               : Application startup failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at
org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:527) [spring-boot-maven-plugin-1.5.8.RELEASE.jar:1.5.8.RELEASE]
        at java.base/java.lang.Thread.run(Thread.java:844) [na:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 26 common frames omitted
    Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/UnmarshalException
        at org.springframework.security.oauth2.provider.error.DefaultOAuth2ExceptionRenderer.geDefaultMessageConverters(DefaultOAuth2ExceptionRenderer.java:117) ~[spring-security-oauth2-2.2.0.RELEASE.jar:na]
...
        at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.12.RELEASE.jar:4.3.12.RELEASE]
        ... 27 common frames omitted
    Caused by: java.lang.ClassNotFoundException: javax.xml.bind.UnmarshalException
        at java.base/java.net.URLClassLoader.findClass(URLClassLoader.java:466) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:563) ~[na:na]
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496) ~[na:na]
        ... 51 common frames omitted

Here is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

...

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.7.0</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.7.0</version>
    </dependency>

    <dependency>
        <groupId>de.flapdoodle.embed</groupId>
        <artifactId>de.flapdoodle.embed.mongo</artifactId>
        <version>2.0.0</version>
        <scope>test</scope>
    </dependency>
    **
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>3.2.10.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-jwt</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>2.2.0.RELEASE</version>
    </dependency>**
</dependencies>

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

Is there anything that I've missed on that Configuration?

Body:
You have to include Jaxb Api, so in your pom.xml you should add its dependency:

<!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>


问:
How do I apply an Ansible with_items loop to the included tasks?
The documentation for import_tasks mentions

Any loops, conditionals and most other keywords will be applied to the included tasks, not to this statement itself.

This is exactly what I want. Unfortunately, when I attempt to make import_tasks work with a loop

```<code>- import_tasks: msg.yml
  with_items:
    - 1
    - 2
    - 3
</code>```

I get the message

ERROR! You cannot use loops on 'import_tasks' statements. You should use 'include_tasks' instead.

I don't want the include_tasks behaviour, as this applies the loop to the included file, and duplicates the tasks. I specifically want to run the first task for each loop variable (as one task with the standard with_items output), then the second, and so on. How can I get this behaviour?

Specifically, consider the following:

Suppose I have the following files:

playbook.yml

```<code>---

- hosts: 192.168.33.100
  gather_facts: no
  tasks:
  - include_tasks: msg.yml
    with_items:
      - 1
      - 2
</code>```

msg.yml

```<code>---

- name: Message 1
  debug:
    msg: "Message 1: {{ item }}"

- name: Message 2
  debug:
    msg: "Message 2: {{ item }}"
</code>```

I would like the printed messages to be

Message 1: 1

  Message 1: 2

  Message 2: 1

  Message 2: 2

However, with import_tasks I get an error, and with include_tasks I get

Message 1: 1

  Message 2: 1

  Message 1: 2

  Message 2: 2

答:
It is not possible. include/import statements operate with task files as a whole.

So with loops you'll have:

```<code>Task 1 with Item 1
Task 2 with Item 1
Task 3 with Item 1
Task 1 with Item 2
Task 2 with Item 2
Task 3 with Item 2
Task 1 with Item 3
Task 2 with Item 3
Task 3 with Item 3
</code>```

Body:
The documentation for import_tasks mentions

Any loops, conditionals and most other keywords will be applied to the included tasks, not to this statement itself.

This is exactly what I want. Unfortunately, when I attempt to make import_tasks work with a loop

- import_tasks: msg.yml
  with_items:
    - 1
    - 2
    - 3

I get the message

ERROR! You cannot use loops on 'import_tasks' statements. You should use 'include_tasks' instead.

I don't want the include_tasks behaviour, as this applies the loop to the included file, and duplicates the tasks. I specifically want to run the first task for each loop variable (as one task with the standard with_items output), then the second, and so on. How can I get this behaviour?

Specifically, consider the following:

Suppose I have the following files:

playbook.yml

---

- hosts: 192.168.33.100
  gather_facts: no
  tasks:
  - include_tasks: msg.yml
    with_items:
      - 1
      - 2

msg.yml

---

- name: Message 1
  debug:
    msg: "Message 1: {{ item }}"

- name: Message 2
  debug:
    msg: "Message 2: {{ item }}"

I would like the printed messages to be

Message 1: 1

  Message 1: 2

  Message 2: 1

  Message 2: 2

However, with import_tasks I get an error, and with include_tasks I get

Message 1: 1

  Message 2: 1

  Message 1: 2

  Message 2: 2

Body:
It is not possible. include/import statements operate with task files as a whole.

So with loops you'll have:

Task 1 with Item 1
Task 2 with Item 1
Task 3 with Item 1
Task 1 with Item 2
Task 2 with Item 2
Task 3 with Item 2
Task 1 with Item 3
Task 2 with Item 3
Task 3 with Item 3


问:
How to use a Pandas series as a lookup for another series
For two series: one with numeric identifiers and another that is a lookup associating those identifiers to names, how can I join them?  Example:

Series with numeric IDs:

```<code>data_series = pd.Series(np.random.randint(0,100,5),
                        index = ["id_"+i for i in np.arange(5).astype('str')])
print(data_series)

id_0    38
id_1    35
id_2    36
id_3    32
id_4    94
dtype: int64
</code>```

Series with names to look up:

```<code>name_lookup_series = pd.Series(['Google','YouTube','Facebook','Baidu','Wikipedia'],
                        index=["id_"+i for i in np.arange(5).astype('str')])
print(name_lookup_series)

id_0       Google
id_1      YouTube
id_2     Facebook
id_3        Baidu
id_4    Wikipedia
dtype: object
</code>```

Desired data frame:

```<code>Google       38
YouTube      35
Facebook     36
Baidu        32
Wikipedia    94
dtype: int64
</code>```

I am able to do this by hacking away with Pandas-fu, but this such a common join-looking operation I assume there is a more idiomatic way to do it.  My current method:

```<code>data_series.index = data_series.index.map(lambda x: name_lookup_series.loc[x])
</code>```

Is there another way to do this, preferably with cleaner code and in one line?

答:
If your data is perfectly aligned on their indices:

```<code>pd.concat((name_lookup_series, data_series), axis=1)
#               0   1
# id_0     Google  13
# id_1    YouTube   6
# id_2   Facebook  22
3 id_3      Baidu  77
# id_4  Wikipedia  42
</code>```

If it is not always aligned on index to begin with, throw in pd.Series.align.  This nicely gets you a tuple that you can pass to .concat().

```<code>pd.concat(name_lookup_series.align(data_series), axis=1)
#               0   1
# id_0     Google  13
# id_1    YouTube   6
# id_2   Facebook  22
# id_3      Baidu  77
# id_4  Wikipedia  42
</code>```

Body:
For two series: one with numeric identifiers and another that is a lookup associating those identifiers to names, how can I join them?  Example:

Series with numeric IDs:

data_series = pd.Series(np.random.randint(0,100,5),
                        index = ["id_"+i for i in np.arange(5).astype('str')])
print(data_series)

id_0    38
id_1    35
id_2    36
id_3    32
id_4    94
dtype: int64

Series with names to look up:

name_lookup_series = pd.Series(['Google','YouTube','Facebook','Baidu','Wikipedia'],
                        index=["id_"+i for i in np.arange(5).astype('str')])
print(name_lookup_series)

id_0       Google
id_1      YouTube
id_2     Facebook
id_3        Baidu
id_4    Wikipedia
dtype: object

Desired data frame:

Google       38
YouTube      35
Facebook     36
Baidu        32
Wikipedia    94
dtype: int64

I am able to do this by hacking away with Pandas-fu, but this such a common join-looking operation I assume there is a more idiomatic way to do it.  My current method:

data_series.index = data_series.index.map(lambda x: name_lookup_series.loc[x])

Is there another way to do this, preferably with cleaner code and in one line?

Body:
If your data is perfectly aligned on their indices:

pd.concat((name_lookup_series, data_series), axis=1)
#               0   1
# id_0     Google  13
# id_1    YouTube   6
# id_2   Facebook  22
3 id_3      Baidu  77
# id_4  Wikipedia  42

If it is not always aligned on index to begin with, throw in pd.Series.align.  This nicely gets you a tuple that you can pass to .concat().

pd.concat(name_lookup_series.align(data_series), axis=1)
#               0   1
# id_0     Google  13
# id_1    YouTube   6
# id_2   Facebook  22
# id_3      Baidu  77
# id_4  Wikipedia  42


问:
Weifenluo DockPanel - hide tab control
Is there a way to hide the whole "tabs" strip that runs across the top of a DockPanel? I found a very old page from '05  that said to set the DockPanel.SdiDocument to true, but the SdiDocument property doesn't seem to be around any more.

When this project was originally written (I'm not the original dev) this area was going to have multiple tabs but it has since been decided that there will only ever be one tab and that it can not be closed, so we don't need the "tabs" part of this control.

Honestly, it would probably be better if this was just a panel but it would be a lot of work to make that change so if anyone knows how to do this I would greatly appreciate it!

答:
Currently this is not possible. See this GitHub issue for reference.

Problem seems to be the expected audience of this feature, but PRs are welcome.

Title: Weifenluo DockPanel - hide tab control


问:
How to convert a datetime from sqlserver to java.util.Date
I am getting a row from a table with sql server database (with Asp net core as web api) using retrofit library in android and as far as I understood I must consider an string equivalent to datetime and then convert it to java.util.Date. An example of retrieved date time is 2018-10-29T19:56:59. Is there anyway to convert datetime to java.util.Date directly?
the code is shown below.

```<code>public class Food {
    @SerializedName("Id")
    private long Id;

    @SerializedName("Name")
    private String Name;

    @SerializedName("Content")
    private String Content;

    @SerializedName("IsActive")
    private boolean IsActive;

    @SerializedName("DoesExist")
    private boolean DoesExist;

    @SerializedName("Cost")
    private int Cost;

    @SerializedName("OffPercentage")
    private int OffPercentage;

    @SerializedName("OffTimeout")
    private Date OffTimeout;
...
}
</code>```

答: Another possible solution would be to convert it to Unix timestamp on a server before sending it. Timestamp is much more robust format for dealing with dates / times</p>

Body:
I am getting a row from a table with sql server database (with Asp net core as web api) using retrofit library in android and as far as I understood I must consider an string equivalent to datetime and then convert it to java.util.Date. An example of retrieved date time is 2018-10-29T19:56:59. Is there anyway to convert datetime to java.util.Date directly?
the code is shown below.

public class Food {
    @SerializedName("Id")
    private long Id;

    @SerializedName("Name")
    private String Name;

    @SerializedName("Content")
    private String Content;

    @SerializedName("IsActive")
    private boolean IsActive;

    @SerializedName("DoesExist")
    private boolean DoesExist;

    @SerializedName("Cost")
    private int Cost;

    @SerializedName("OffPercentage")
    private int OffPercentage;

    @SerializedName("OffTimeout")
    private Date OffTimeout;
...
}


问:
libgit2sharp equivalent of "git mergetool"
I want to use the equivalent  of "git mergetool" within libgit2sharp. Is there a sample to do this? Or do I have to dive deep and try to implement this in libgit2sharp?

The call "git mergetool" checks if merge is required and calls the custom mergetool with a copy of the server. A proper way to call the mergetool would be usefull. I know I can read the config and search the mergetool and its "cmd" command.

Greetings
Thomas

答:
LibGit2Sharp is used to programmatically interact with a git repository. It won't launch a mergetool directly.

However, you can use LibGit2Sharp to retrieve the configuration values from a given repository. For instance, by using:

```<code>var mergeTool = repo.Config.Get<string>("merge.tool").Value;
var path = repo.Config.Get<string>("mergetool." + mergeTool + ".path").Value;
</code>```

You can retrieve the path of the configured merge tool.

Body:
LibGit2Sharp is used to programmatically interact with a git repository. It won't launch a mergetool directly.

However, you can use LibGit2Sharp to retrieve the configuration values from a given repository. For instance, by using:

var mergeTool = repo.Config.Get<string>("merge.tool").Value;
var path = repo.Config.Get<string>("mergetool." + mergeTool + ".path").Value;

You can retrieve the path of the configured merge tool.