问:
Can I mock CrudRepository with Spring Data JDBC without any database using Spring Boot?
I am developing an app that uses Spring Boot 2 and Spring Data JDBC. The final app will use MySQL.

I currently have a persistence layer and a service layer together with a few repositories derived from CrudRepository.

For my unit tests, I want to really do unit tests without any database. Not even HSQL. I know there are several different philosophies to subscribe to here, but I want to switch to pure unit tests and see how it plays out. I will use a database in the integration tests.

I have a separate application.properties in my test folder, where I have a separate configuration for my tests.

Spring Boot will default to HSQL if no datasource is defined in application.properties. But again, I want to run my tests without any database and only mock my CrudRepository implementations. I tried disabling Spring Boot's database autoconfiguration by using different variants of the following in my application.properties:

```<code>spring.autoconfigure.exclude= \
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
  org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
</code>```

In my tests, I tried to do something like this:

```<code>@ExtendWith(SpringExtension.class)
@Transactional
@SpringBootTest
public class UserServiceTest {

    private UserService userService;

    @MockBean
    private UserRepository userRepository;

    @BeforeEach
    void setUp() {
        userService = new UserService(userRepository);
    }

    @Test
    public void doSomeTest() {

         // Test code goes here

    }

}
</code>```

I am using constructor-based dependency injection in the services. However, I get errors from Spring like the following:

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'package.userRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

</code>```

What I want is a mocked userRepository where I can pre-configure a faked repository to return dummy data. But it appears that removing the database configuration completely removes the CrudRepository so that no part of the spring boot app can start. Or am I missing something else.

I am using Eclipse, Maven, Mockito and JUnit5. I should note that everything works if I run "unit tests" against a test mysql database, so I know there's nothing really wrong with the code or with the tests or the setup in general. The issues start only when I want to get rid of the database.

I am a junior Java developer doing this for fun, so I might be missing something obvious. Searching around on the web for Spring Data JDBC is difficult, since I almost only find solutions relating to JPA.

答:
@SpringBootTest loads all your context. Spring boot – @SpringBootTest

Under the hood, @SpringBootTest tries to mimic the processes added by Spring Boot framework for creating the context e.g. it decides what to scan based on package structures, loads external configurations from predefined locations, optionally runs auto-configuration starters and so on.

As we see that this annotation starts and configure almost whole
  application before the test begin, we should use @SpringBootTest to
  write an integration tests that use the application processes and
  dependencies.

Including UserService. And I guess it can't find UserRepository so it fails.

I guess you should remove these strings

```<code>spring.autoconfigure.exclude= \
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
  org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration
</code>```

and test like this

```<code>@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional
public class UserServiceTest {

    @TestConfiguration
    class UserServiceTestContextConfiguration {

        @Bean
        public UserService userService() {
            return new UserService(userRepository);
        }
    }

    @Autowired
    private UserService userService;

    @MockBean
    private UserRepository userRepository;

    // write test cases here
}
</code>```

I took it from here

And keep in mind that Spring handles @TestConfiguration specifically so don't "shot your leg" with it Spring boot – @TestConfiguration

In spring boot, any beans configured in a top-level class annotated with @TestConfiguration will not be picked up via component scanning. We must explicitly register the @TestConfiguration class with the class that contains the test cases.

Body:
I am developing an app that uses Spring Boot 2 and Spring Data JDBC. The final app will use MySQL.

I currently have a persistence layer and a service layer together with a few repositories derived from CrudRepository.

For my unit tests, I want to really do unit tests without any database. Not even HSQL. I know there are several different philosophies to subscribe to here, but I want to switch to pure unit tests and see how it plays out. I will use a database in the integration tests.

I have a separate application.properties in my test folder, where I have a separate configuration for my tests.

Spring Boot will default to HSQL if no datasource is defined in application.properties. But again, I want to run my tests without any database and only mock my CrudRepository implementations. I tried disabling Spring Boot's database autoconfiguration by using different variants of the following in my application.properties:

spring.autoconfigure.exclude= \
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
  org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration

In my tests, I tried to do something like this:

@ExtendWith(SpringExtension.class)
@Transactional
@SpringBootTest
public class UserServiceTest {

    private UserService userService;

    @MockBean
    private UserRepository userRepository;

    @BeforeEach
    void setUp() {
        userService = new UserService(userRepository);
    }

    @Test
    public void doSomeTest() {

         // Test code goes here

    }

}

I am using constructor-based dependency injection in the services. However, I get errors from Spring like the following:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'package.userRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

What I want is a mocked userRepository where I can pre-configure a faked repository to return dummy data. But it appears that removing the database configuration completely removes the CrudRepository so that no part of the spring boot app can start. Or am I missing something else.

I am using Eclipse, Maven, Mockito and JUnit5. I should note that everything works if I run "unit tests" against a test mysql database, so I know there's nothing really wrong with the code or with the tests or the setup in general. The issues start only when I want to get rid of the database.

I am a junior Java developer doing this for fun, so I might be missing something obvious. Searching around on the web for Spring Data JDBC is difficult, since I almost only find solutions relating to JPA.

Body:
@SpringBootTest loads all your context. Spring boot – @SpringBootTest

Under the hood, @SpringBootTest tries to mimic the processes added by Spring Boot framework for creating the context e.g. it decides what to scan based on package structures, loads external configurations from predefined locations, optionally runs auto-configuration starters and so on.

As we see that this annotation starts and configure almost whole
  application before the test begin, we should use @SpringBootTest to
  write an integration tests that use the application processes and
  dependencies.

Including UserService. And I guess it can't find UserRepository so it fails.

I guess you should remove these strings

spring.autoconfigure.exclude= \
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
  org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
  org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration

and test like this

@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional
public class UserServiceTest {

    @TestConfiguration
    class UserServiceTestContextConfiguration {

        @Bean
        public UserService userService() {
            return new UserService(userRepository);
        }
    }

    @Autowired
    private UserService userService;

    @MockBean
    private UserRepository userRepository;

    // write test cases here
}

I took it from here

And keep in mind that Spring handles @TestConfiguration specifically so don't "shot your leg" with it Spring boot – @TestConfiguration

In spring boot, any beans configured in a top-level class annotated with @TestConfiguration will not be picked up via component scanning. We must explicitly register the @TestConfiguration class with the class that contains the test cases.


来源: stackexchange

问:
How can i create this Curved Bottom ImageView?
Target Image View

I want to create an image view like the one in the design. I have no idea how to go about it. I'm hoping someone can point me int the right direction. A library or what I can do to get it.

答: create png image  that curved image. then set src into imageview </p>

ContentLicense: CC BY-SA 4.0


问:
SQL Filter by List of ids
I have three tables

```<code>1-rests
2-amenity_rest
3-amenities
</code>```

```<code>rests
id      name
1       rest1
2       rest2
3       rest3

amenities
id     name
1      amenity1
2      amenity2
3      amenity3

amenity_rest
rest_id         amenity_id
1                  1
1                  3
2                  2
3                  1
</code>```

I would like to send a List of amenities like [1,3]

and it should return the rest that its id=1

and if I send array [1,2,3] it should return no result

How would such a query look alike?

答:
Your controller should have a function like this:

```<code>function retrieveData(Request $request){
    $data = Amenities_rest::whereIn('amenity_id', $request->amenities)
                            ->groupBy('rest_id')
                            ->havingRaw('COUNT (*) = ' . count($request->amenities))
                            ->get();
    return $data
}
</code>```

That should do it. I hope it helps.

Title: SQL Filter by List of ids

Body:
I have three tables

1-rests
2-amenity_rest
3-amenities

rests
id      name
1       rest1
2       rest2
3       rest3

amenities
id     name
1      amenity1
2      amenity2
3      amenity3

amenity_rest
rest_id         amenity_id
1                  1
1                  3
2                  2
3                  1

I would like to send a List of amenities like [1,3]

and it should return the rest that its id=1

and if I send array [1,2,3] it should return no result

How would such a query look alike?

Body:
Your controller should have a function like this:

function retrieveData(Request $request){
    $data = Amenities_rest::whereIn('amenity_id', $request->amenities)
                            ->groupBy('rest_id')
                            ->havingRaw('COUNT (*) = ' . count($request->amenities))
                            ->get();
    return $data
}

That should do it. I hope it helps.


问:
How to get the progress of copy operation in AWS copy operation in android?
I try to copy one file from one folder to other folder inside the same bucket. For copying the file i use CopyObjectRequest class. But i do not know how can i get the progress of copy operation?
So please help me in it , how can i get the progress status of copy operation.

For copy operation i followed this way-

```<code>try {
        AmazonS3 s3Client =new AmazonS3Client(credentials,cc);

        // Copy the object into a new object in the same bucket.
        CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, sourceKey, "wedorias-new", "test/test111/logo.png"/*destinationKey*/);
        s3Client.copyObject(copyObjRequest);

        if (copyObjRequest.isRequesterPays()){

            System.out.println("sadfbgnh==");
        }

    } catch (AmazonServiceException e) {
        // The call was transmitted successfully, but Amazon S3 couldn't process
        // it, so it returned an error response.
        e.printStackTrace();
        System.out.println("exception==!"+e.getErrorMessage());
        System.out.println("exception==!"+e.getErrorCode());
        System.out.println("exception==!"+e.getMessage());
    } catch (Exception e) {

        e.printStackTrace();
        System.out.println("exception==!"+e.getMessage());
    }
</code>```

答:
If you want to copy one object from one folder to another one (Or other Buckets if it's the case) and check the progress, you will have to use  Amazon S3 Multipart Upload.

AWS docs have a nice example called Copy an Object Using the AWS SDK for Java Multipart Upload API, it shows you what you have to do to set it up and check the progress of the copy.

```<code>// Get the object size to track the end of the copy operation.
GetObjectMetadataRequest metadataRequest = new GetObjectMetadataRequest(sourceBucketName, sourceObjectKey);
ObjectMetadata metadataResult = s3Client.getObjectMetadata(metadataRequest);
long objectSize = metadataResult.getContentLength();
</code>```

Notice

Multipart upload is a must when the object is greater than 5GB.

Multipart upload is recommended when the object is greater than 100MB.

Multipart upload doesn't work if the object is less than 5MB.

Body:
I try to copy one file from one folder to other folder inside the same bucket. For copying the file i use CopyObjectRequest class. But i do not know how can i get the progress of copy operation?
So please help me in it , how can i get the progress status of copy operation.

For copy operation i followed this way-

try {
        AmazonS3 s3Client =new AmazonS3Client(credentials,cc);

        // Copy the object into a new object in the same bucket.
        CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, sourceKey, "wedorias-new", "test/test111/logo.png"/*destinationKey*/);
        s3Client.copyObject(copyObjRequest);

        if (copyObjRequest.isRequesterPays()){

            System.out.println("sadfbgnh==");
        }

    } catch (AmazonServiceException e) {
        // The call was transmitted successfully, but Amazon S3 couldn't process
        // it, so it returned an error response.
        e.printStackTrace();
        System.out.println("exception==!"+e.getErrorMessage());
        System.out.println("exception==!"+e.getErrorCode());
        System.out.println("exception==!"+e.getMessage());
    } catch (Exception e) {

        e.printStackTrace();
        System.out.println("exception==!"+e.getMessage());
    }

Body:
If you want to copy one object from one folder to another one (Or other Buckets if it's the case) and check the progress, you will have to use  Amazon S3 Multipart Upload.

AWS docs have a nice example called Copy an Object Using the AWS SDK for Java Multipart Upload API, it shows you what you have to do to set it up and check the progress of the copy.

// Get the object size to track the end of the copy operation.
GetObjectMetadataRequest metadataRequest = new GetObjectMetadataRequest(sourceBucketName, sourceObjectKey);
ObjectMetadata metadataResult = s3Client.getObjectMetadata(metadataRequest);
long objectSize = metadataResult.getContentLength();

Notice

Multipart upload is a must when the object is greater than 5GB.

Multipart upload is recommended when the object is greater than 100MB.

Multipart upload doesn't work if the object is less than 5MB.


问:
SwiftUI change inner state button with action callback request
I have custom stack of two buttons here No/Yes. Both have external actions implemented. But, I can't find the way to do modify with accept / decline action, I need also to change inner

@State var type: SelectionType = .none - to .yes or .no

struct SegmentedButtonView: View {
    @State var type: SelectionType = .none
    var accept: () -> ()
    var decline: () -> ()
    var body: some View {
        HStack(alignment: .center) {
            Button(action: accept ){
                Spacer()
                Text(SelectionType.no.rawValue)
                    .font(.Montserrat(weight: (type == .yes || type == .none) ? .SemiBold : .Bold, size: 16))
                    .foregroundColor((type == .none || type == .yes) ? Color.lightGray : Color.white)
                Spacer()
            }
            .frame(height: 40)
            .background(type == .no ? Color.brand_purple : Color.white)

            Rectangle().vertical_line().background(type == .none ? Color.lightGray : Color.brand_purple)

            Button(action: decline){
                Spacer()
                Text(SelectionType.yes.rawValue)
                    .font(.Montserrat(weight: (type == .no || type == .none) ? .SemiBold : .Bold, size: 16))
                    .foregroundColor((type == .none || type == .no) ? Color.lightGray : Color.white)
                Spacer()
            }
            .frame(height: 40)
            .background(type == .yes ? Color.brand_purple : Color.white)

        }.frame(width: 138, height: 40)
            .font(.Montserrat(weight: .Bold, size: 16))
            .background(Color.white)
            .cornerRadius(7)
            .overlay(
                RoundedRectangle(cornerRadius: 7)
                    .stroke(type != .none ? Color.brand_purple : Color.lightGray, lineWidth: 1))
    }
}
```

答:
If I correctly understood your needs, it can be like following</p>

```<code>    HStack(alignment: .center) {
        Button(action: {
           self.accept()
           self.type = .yes
        } ){
</code>```

Body:
If I correctly understood your needs, it can be like following

    HStack(alignment: .center) {
        Button(action: {
           self.accept()
           self.type = .yes
        } ){


问:
Setting a rails session in an ajax post
Kind of a strange problem, hopefully someone can help me out.

I want to set a session in my rails controller which I hit via jquery ajax post.

Its a regular rails form which i submit via ajax

```<code> $.post($(this).attr('action'), $(this).serialize(), function(data){

 }, 'json');
</code>```

which hits the leads controller

```<code>def create
    @lead = Lead.new(params[:lead])
    @lead.save!

    if @lead.save
      session[:lead] = "#{@lead.id}"
    end

  end
</code>```

however the session doesnt seem to be set across the ajax call.

Anyone have an ideas on this?

答:
The problem could be because your using your localhost and not a proper domain I have heard some browsers ignore such sessions.

The other problem could be your not sending the CSRF authentication token used to stop forgery attacks, this is now a requirement for XHR requests by default and not just forms (although it may not have been with the version of rails at the time of your original post).

ContentLicense: CC BY-SA 3.0

Title: Setting a rails session in an ajax post

Body:
Kind of a strange problem, hopefully someone can help me out.

I want to set a session in my rails controller which I hit via jquery ajax post.

Its a regular rails form which i submit via ajax

 $.post($(this).attr('action'), $(this).serialize(), function(data){

 }, 'json');

which hits the leads controller

def create
    @lead = Lead.new(params[:lead])
    @lead.save!

    if @lead.save
      session[:lead] = "#{@lead.id}"
    end

  end

however the session doesnt seem to be set across the ajax call.

Anyone have an ideas on this?


问:
To merge two dictionaries of list in Python
There are two dictionaries

```<code>x={1:['a','b','c']}
y={1:['d','e','f'],2:['g']}
</code>```

I want another dictionary z which is a merged one of x and y such that

```<code>z = {1:['a','b','c','d','e','f'],2:['g']}
</code>```

Is it possible to do this operation?
I tried update operation

```<code>x.update(y)
</code>```

But it gives me the following result

```<code>z= {1:['d','e','f'],2:['g']}
</code>```

答:
This is what worked for me :

```<code>d1={'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
d2 = {'a':[10,11,12], 'b':[13,14,15], 'c':[16,17,18]}
d3 = {}
for k in d1.keys():
    d3.update( {k : []} )
    for i in d1[k]:
        d3[k].append(i)
    for j in d2[k]:
        d3[k].append(j)
print(d3)
</code>```

I know it's a roundabout way of doing it, but the other methods didn't work when the dictionary values were ndarrays.

Body:
There are two dictionaries

x={1:['a','b','c']}
y={1:['d','e','f'],2:['g']}

I want another dictionary z which is a merged one of x and y such that

z = {1:['a','b','c','d','e','f'],2:['g']}

Is it possible to do this operation?
I tried update operation

x.update(y)

But it gives me the following result

z= {1:['d','e','f'],2:['g']}

Body:
This is what worked for me :

d1={'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9]}
d2 = {'a':[10,11,12], 'b':[13,14,15], 'c':[16,17,18]}
d3 = {}
for k in d1.keys():
    d3.update( {k : []} )
    for i in d1[k]:
        d3[k].append(i)
    for j in d2[k]:
        d3[k].append(j)
print(d3)

I know it's a roundabout way of doing it, but the other methods didn't work when the dictionary values were ndarrays.


问:
Need properties in Configuration class
I have spring boot application and application.properties file in resources folder.
I need some properties in a configuration class. I cant use getClass().getClassLoader().getResourceAsStream() because null pointer. How do I get the properties in configuration class?
Property class:

@Configuration
@PropertySource("classpath:application.properties")
public class AppProperties {
    @Value("${server.ssl.key-store}")
    private String serverSSLKeyStore;

    @Value("${server.ssl.trust-store}")
    private String serverSSLTrustStore;

    @Value("${server.ssl.key-store-password}")
    private String serverSSLKeyStorePwd;

    @Value("${server.ssl.trust-store-password}")
    private String serverSSLTrustStorePwd;

    @Value("${rabo.api.url}")
    private String raboApiUrl;

    @Value("${tpp.certificate}")
    private String TPPCertificate;

    @Value("${rabo.client.id}")
    private String raboClientId;

    @Value("${rabo.key.id}")
    private String raboKeyId;

    @Value("${rabo.private.key}")
    private String raboPrivateKey;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("application.properties"));
        return propertySourcesPlaceholderConfigurer;

    }
// Getters

}
```

<p>Configuration class:</p>

<pre class="lang-java prettyprint-override"><code>@Configuration
public class RetrofitConfiguration {
    private static final Logger LOG = LoggerFactory.getLogger(RetrofitConfiguration.class);

    @Bean
    SSLTrustManagerHelper provideSSLTrustManagerHelper(AppProperties properties) {
        try {
            LOG.error(properties.getServerSSLKeyStore()); // PRINTS NULL
            InputStream keystore = new FileInputStream(properties.getServerSSLKeyStore());
            InputStream truststore = new FileInputStream(properties.getServerSSLTrustStore());
            String keystorePwd = properties.getServerSSLKeyStorePwd();
            String truststorePwd = properties.getServerSSLTrustStorePwd();
            SSLTrustManagerHelper ssl = null;
            try {
                ssl = new SSLTrustManagerHelper(keystore, keystorePwd, truststore, truststorePwd);
            } catch (Exception e) {
                LOG.error("error occured while creating ssl trust manager helper!", e);
            }
            return ssl;
        } catch (FileNotFoundException e) {
            LOG.error("file not found ", e);
            return null;
        }
    }

// Other config
}
</code>```

The AppProperties class is created but properties return null.

答:
There are few changes can be done

Remove bean propertyConfigInDev

If there is not overriden path (of property file)
defined then you do not require
@PropertySource("classpath:application.properties"), you may skip this line of code as well

You may use @Value directly in RetrofitConfiguration class as shown below

```<code>@Configuration
public class RetrofitConfiguration {
   private static final Logger LOG = LoggerFactory.getLogger(RetrofitConfiguration.class);

@Value("${server.ssl.trust-store}")
private String serverSSLTrustStore;

@Bean
SSLTrustManagerHelper provideSSLTrustManagerHelper() {
   LOG.error(serverSSLTrustStore); // **SHOULDN'T PRINTS NULL**
   }
}
</code>```

Title: Need properties in Configuration class

Body:
I have spring boot application and application.properties file in resources folder.
I need some properties in a configuration class. I cant use getClass().getClassLoader().getResourceAsStream() because null pointer. How do I get the properties in configuration class?
Property class:

@Configuration
@PropertySource("classpath:application.properties")
public class AppProperties {
    @Value("${server.ssl.key-store}")
    private String serverSSLKeyStore;

    @Value("${server.ssl.trust-store}")
    private String serverSSLTrustStore;

    @Value("${server.ssl.key-store-password}")
    private String serverSSLKeyStorePwd;

    @Value("${server.ssl.trust-store-password}")
    private String serverSSLTrustStorePwd;

    @Value("${rabo.api.url}")
    private String raboApiUrl;

    @Value("${tpp.certificate}")
    private String TPPCertificate;

    @Value("${rabo.client.id}")
    private String raboClientId;

    @Value("${rabo.key.id}")
    private String raboKeyId;

    @Value("${rabo.private.key}")
    private String raboPrivateKey;

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertySourcesPlaceholderConfigurer.setLocation(new ClassPathResource("application.properties"));
        return propertySourcesPlaceholderConfigurer;

    }
// Getters

}

Configuration class:

@Configuration
public class RetrofitConfiguration {
    private static final Logger LOG = LoggerFactory.getLogger(RetrofitConfiguration.class);

    @Bean
    SSLTrustManagerHelper provideSSLTrustManagerHelper(AppProperties properties) {
        try {
            LOG.error(properties.getServerSSLKeyStore()); // PRINTS NULL
            InputStream keystore = new FileInputStream(properties.getServerSSLKeyStore());
            InputStream truststore = new FileInputStream(properties.getServerSSLTrustStore());
            String keystorePwd = properties.getServerSSLKeyStorePwd();
            String truststorePwd = properties.getServerSSLTrustStorePwd();
            SSLTrustManagerHelper ssl = null;
            try {
                ssl = new SSLTrustManagerHelper(keystore, keystorePwd, truststore, truststorePwd);
            } catch (Exception e) {
                LOG.error("error occured while creating ssl trust manager helper!", e);
            }
            return ssl;
        } catch (FileNotFoundException e) {
            LOG.error("file not found ", e);
            return null;
        }
    }

// Other config
}

The AppProperties class is created but properties return null.

Body:
There are few changes can be done

Remove bean propertyConfigInDev

If there is not overriden path (of property file)
defined then you do not require
@PropertySource("classpath:application.properties"), you may skip this line of code as well

You may use @Value directly in RetrofitConfiguration class as shown below

@Configuration
public class RetrofitConfiguration {
   private static final Logger LOG = LoggerFactory.getLogger(RetrofitConfiguration.class);

@Value("${server.ssl.trust-store}")
private String serverSSLTrustStore;

@Bean
SSLTrustManagerHelper provideSSLTrustManagerHelper() {
   LOG.error(serverSSLTrustStore); // **SHOULDN'T PRINTS NULL**
   }
}


问:
Javascript: $.ajax is null inside the for loop
I have an onclick function btn-book, and inside it is a for loop for the data of Ajax. I'm sure that data have values but i dont get it why i always get null. here is the code of the onclick. </p>

```<code>$('#mapContainer').on('click', '.btn-book', function(e){
    e.preventDefault();
    var id = e.currentTarget.id;
    var routeOrigin = route_Search.origin;
    routeOrigin = routeOrigin.filter(function(e){return e});
    var url = base_url;

    for(var i = 1; i <= desNo; i++){
            $.ajax({
                type: "POST",
                url: url,
                data: {
                    id: id,

                    origin: $('#route-origin'+i).val(),
                    origin_contactperson: $('#origin-contactperson'+i).val(),
                    origin_company: $('#origin-company'+i).val(),
                    origin_phonenumber: $('#origin-phonenumber'+i).val(),
                    origin_notes: $('#origin-notes'+i).val(),
                    origin_Lng: routeOrigin[i-1].lng(),
                    origin_Lat: routeOrigin[i-1].lat(),
                },
                success: function(msg)
                {
                    console.log(msg);
                },
                error: function()
                {
                    alert("An error occured while updating. Try again in a while");
                }
            })

    }

});
</code>```

答:
use like this.</p>

```<code> $('#mapContainer').on('click', '.btn-book', function(e){
        e.preventDefault();
        var id = e.currentTarget.id;
        var routeOrigin = route_Search.origin;
        routeOrigin = routeOrigin.filter(function(e){return e});
        var url = base_url;
        var origin = [], origin_contactperson = []

        for(var i = 1; i <= desNo; i++){
             origin.push($('#route-origin'+i).val());
             origin_contactperson.push($('#origin-contactperson'+i).val());
                .....
        }

         $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        id: id,

                        origin: origin,
                        origin_contactperson: origin_contactperson,
                        origin_company: origin_company,
                        origin_phonenumber: origin_phonenumber,
                        origin_notes: origin_notes,
                        origin_Lng: origin_Lng,
                        origin_Lat: origin_Lat
                    },
                    success: function(msg)
                    {
                        console.log(msg);
                    },
                    error: function()
                    {
                        alert("An error occured while updating. Try again in a while");
                    }
                })

    });
</code>```

Body:
I have an onclick function btn-book, and inside it is a for loop for the data of Ajax. I'm sure that data have values but i dont get it why i always get null. here is the code of the onclick.

$('#mapContainer').on('click', '.btn-book', function(e){
    e.preventDefault();
    var id = e.currentTarget.id;
    var routeOrigin = route_Search.origin;
    routeOrigin = routeOrigin.filter(function(e){return e});
    var url = base_url;

    for(var i = 1; i <= desNo; i++){
            $.ajax({
                type: "POST",
                url: url,
                data: {
                    id: id,

                    origin: $('#route-origin'+i).val(),
                    origin_contactperson: $('#origin-contactperson'+i).val(),
                    origin_company: $('#origin-company'+i).val(),
                    origin_phonenumber: $('#origin-phonenumber'+i).val(),
                    origin_notes: $('#origin-notes'+i).val(),
                    origin_Lng: routeOrigin[i-1].lng(),
                    origin_Lat: routeOrigin[i-1].lat(),
                },
                success: function(msg)
                {
                    console.log(msg);
                },
                error: function()
                {
                    alert("An error occured while updating. Try again in a while");
                }
            })

    }

});

Body:
use like this.

 $('#mapContainer').on('click', '.btn-book', function(e){
        e.preventDefault();
        var id = e.currentTarget.id;
        var routeOrigin = route_Search.origin;
        routeOrigin = routeOrigin.filter(function(e){return e});
        var url = base_url;
        var origin = [], origin_contactperson = []

        for(var i = 1; i <= desNo; i++){
             origin.push($('#route-origin'+i).val());
             origin_contactperson.push($('#origin-contactperson'+i).val());
                .....
        }

         $.ajax({
                    type: "POST",
                    url: url,
                    data: {
                        id: id,

                        origin: origin,
                        origin_contactperson: origin_contactperson,
                        origin_company: origin_company,
                        origin_phonenumber: origin_phonenumber,
                        origin_notes: origin_notes,
                        origin_Lng: origin_Lng,
                        origin_Lat: origin_Lat
                    },
                    success: function(msg)
                    {
                        console.log(msg);
                    },
                    error: function()
                    {
                        alert("An error occured while updating. Try again in a while");
                    }
                })

    });


问:
google-cloud-sdk-app-engine-java with openjdk-11
Is it possible to install app engine sdk over openjdk 11?

When I try it I get:

$ sudo apt-get install google-cloud-sdk-app-engine-java

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 google-cloud-sdk-app-engine-java : Depends: openjdk-7-jdk but it is not installable or
                                             openjdk-8-jdk but it is not installable
E: Unable to correct problems, you have held broken packages.
</code>```

On my linux distro (Debian testing) openjdk-8-jdk is not available anymore

答:
The App Engine SDK component for the Google Cloud SDK is currently not available for Java 11.

For reference, here you have an installation guide for the Cloud SDK and its components. The link also contains a list of the Gcloud SDK additional components

Body:
Is it possible to install app engine sdk over openjdk 11?

When I try it I get:

$ sudo apt-get install google-cloud-sdk-app-engine-java

Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 google-cloud-sdk-app-engine-java : Depends: openjdk-7-jdk but it is not installable or
                                             openjdk-8-jdk but it is not installable
E: Unable to correct problems, you have held broken packages.

On my linux distro (Debian testing) openjdk-8-jdk is not available anymore


问:
Supported camera preview sizes for popular Android handsets
I'm working with camera preview frames, and need to make a decision about what minimum preview size I will work with. I need fairly high resolution, and am trying to figure out the highest preview resolution I can get across the more popular Android handsets and OS versions. (Judging by this question about Nexus One / Froyo preview sizes, it looks like they sometimes change across OS versions for the same device.)

Is there a resource anywhere that basically lists the output of android.hardware.Camera.Parameters.getSupportedPreviewSizes() for lots of different devices (or device/OS version pairs)?

Alternatively, if there is no such listing, this question could become such a resource. I will very happily upvote any answers that include new individual data points for specific handsets / OS versions.

And to forestall the obvious comment: Yes, I know I will need to test my code on lots of devices anyway. But ideally I would like to make some reasonably informed decisions about resolution early on, without having to purchase a bevy of devices just to get started.

答:
My experience tells me,  that 640x480 is available almost everywhere, and even if bigger resolutions are advertised by camera object,  not all of them are actually usable.
I experienced segfaults on HTC Hero when I tried maximal resolution -  data buffer used
for passing preview images is mmaped, and this size seems to be limited</p>

ContentLicense: CC BY-SA 2.5


问:
Pusher module is not found although installed
Error received below:

```<code>Error: Cannot find module 'Pusher'
Require stack:
- /home/ec2-user/realtime_map/node_modules/require-stack/src/index.js
- /home/ec2-user/realtime_map/node_modules/require-stack/index.js
- /home/ec2-user/realtime_map/node_modules/@adonisjs/fold/src/Ioc/index.js
- /home/ec2-user/realtime_map/node_modules/@adonisjs/fold/index.js
- /home/ec2-user/realtime_map/server.js

at /home/ec2-user/realtime_map/start/events.js(anonymous):3
1      //events.js
2
3      const Pusher = use('Pusher')
4      const Event = use('Event');
5      const Env = use('Env');
6
7      // set up Pusher
8      let pusher = new Pusher({

1 requireStack
  /home/ec2-user/realtime_map/node_modules/require-stack/src/index.js:44

2 Ioc._require
  /home/ec2-user/realtime_map/node_modules/@adonisjs/fold/src/Ioc/index.js:345

3 Ioc.use
  /home/ec2-user/realtime_map/node_modules/@adonisjs/fold/src/Ioc/index.js:742

Application crashed, make sure to kill all related running process, fix the issue and re-run the app
</code>```

Installed versions of pusher are;

adonis-fullstack-app@4.1.0 /home/ec2-user/realtime_map
    └── pusher@3.0.0

adonis-fullstack-app@4.1.0 /home/ec2-user/realtime_map
    └── adonis-pusher@1.0.4

答:
Your error indicates that a module name Pusher could not be found, but your installation notes pusher being installed.
Can you try lowercase p on your import:

```<code>const Pusher = use('pusher')
</code>```

Body:
Error received below:

Error: Cannot find module 'Pusher'
Require stack:
- /home/ec2-user/realtime_map/node_modules/require-stack/src/index.js
- /home/ec2-user/realtime_map/node_modules/require-stack/index.js
- /home/ec2-user/realtime_map/node_modules/@adonisjs/fold/src/Ioc/index.js
- /home/ec2-user/realtime_map/node_modules/@adonisjs/fold/index.js
- /home/ec2-user/realtime_map/server.js

at /home/ec2-user/realtime_map/start/events.js(anonymous):3
1      //events.js
2
3      const Pusher = use('Pusher')
4      const Event = use('Event');
5      const Env = use('Env');
6
7      // set up Pusher
8      let pusher = new Pusher({

1 requireStack
  /home/ec2-user/realtime_map/node_modules/require-stack/src/index.js:44

2 Ioc._require
  /home/ec2-user/realtime_map/node_modules/@adonisjs/fold/src/Ioc/index.js:345

3 Ioc.use
  /home/ec2-user/realtime_map/node_modules/@adonisjs/fold/src/Ioc/index.js:742

Application crashed, make sure to kill all related running process, fix the issue and re-run the app

Installed versions of pusher are;

adonis-fullstack-app@4.1.0 /home/ec2-user/realtime_map
    └── pusher@3.0.0

adonis-fullstack-app@4.1.0 /home/ec2-user/realtime_map
    └── adonis-pusher@1.0.4

Body:
Your error indicates that a module name Pusher could not be found, but your installation notes pusher being installed.
Can you try lowercase p on your import:

const Pusher = use('pusher')


问:
How can I add line under Row of UICollectionView, Swift 5, Xcode
How can I add line under Row of UICollectionView, Swift 5, Xcode?

I want separate row by line.

答: Since UICollectionView doesn't have separators for it's cells you can either switched to a UITableView only if it's suitable for your page's design or you can add a separator within the UICollectionViewCell by using a UIView at the bottom with height of 1. There are also some third party solutions you might try which you can find on GitHub such as these: Solution 1, Solution 2.


问:
Pip not working - ModuleNotFoundError: No module named 'runpy'
I have installed Python to C:\Python.

I have added the following paths to PATH environment variables:

C:\Python

C:\Python\Lib\site-packages

C:\Python\Scripts

I have installed get-pip.py to desktop successfully, returns the following:

```<code>Collecting pip   Using cached
https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl
Collecting setuptools   Using cached
https://files.pythonhosted.org/packages/ff/f4/385715ccc461885f3cedf57a41ae3c12b5fec3f35cce4c8706b1a112a133/setuptools-40.0.0-py2.py3-none-any.whl
Collecting wheel   Using cached
https://files.pythonhosted.org/packages/81/30/e935244ca6165187ae8be876b6316ae201b71485538ffac1d718843025a9/wheel-0.31.1-py2.py3-none-any.whl
Installing collected packages: pip, setuptools, wheel Successfully
installed pip-10.0.1 setuptools-40.0.0 wheel-0.31.1
</code>```

When trying to install libraries with C:\Users\XXXX\Desktop>pip install gevent, it returns the following:

```<code>Could not import runpy module
ModuleNotFoundError: No module named 'runpy'
</code>```

Running this also returns the same error C:\Users\XXXX\Desktop>pip:

```<code>Could not import runpy module
ModuleNotFoundError: No module named 'runpy'
</code>```

I have searched endlessly for this error and none of them have helped me. I have tried searching for the runpy module but could not find it nor its location.

Hope someone can help

答:
Delete the Virtual environment folder under the C: driver User path named as Envs. Then search the virtual keyword in the search tab and delete all the Python virtual environment packages and folders. Finally, reinstall the Python
Note - Install Python 64bit for the 64bit machine. Hope You will get some idea from it.

Body:
I have installed Python to C:\Python.

I have added the following paths to PATH environment variables:

C:\Python

C:\Python\Lib\site-packages

C:\Python\Scripts

I have installed get-pip.py to desktop successfully, returns the following:

Collecting pip   Using cached
https://files.pythonhosted.org/packages/0f/74/ecd13431bcc456ed390b44c8a6e917c1820365cbebcb6a8974d1cd045ab4/pip-10.0.1-py2.py3-none-any.whl
Collecting setuptools   Using cached
https://files.pythonhosted.org/packages/ff/f4/385715ccc461885f3cedf57a41ae3c12b5fec3f35cce4c8706b1a112a133/setuptools-40.0.0-py2.py3-none-any.whl
Collecting wheel   Using cached
https://files.pythonhosted.org/packages/81/30/e935244ca6165187ae8be876b6316ae201b71485538ffac1d718843025a9/wheel-0.31.1-py2.py3-none-any.whl
Installing collected packages: pip, setuptools, wheel Successfully
installed pip-10.0.1 setuptools-40.0.0 wheel-0.31.1

When trying to install libraries with C:\Users\XXXX\Desktop>pip install gevent, it returns the following:

Could not import runpy module
ModuleNotFoundError: No module named 'runpy'

Running this also returns the same error C:\Users\XXXX\Desktop>pip:

Could not import runpy module
ModuleNotFoundError: No module named 'runpy'

I have searched endlessly for this error and none of them have helped me. I have tried searching for the runpy module but could not find it nor its location.

Hope someone can help


问:
Android Tv not displaying Recyclerview
I created a recycler view in my android tv app, but its not showing anything, I did it as I do for mobile apps, checked by debugging using break points, and the recycler view data is showing there.

My code is as follows

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_browse_fragment"
    android:name="com.rimapps.alrahabeachhotel.MainFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.MainActivity"
    tools:deviceIds="tv"
    tools:ignore="MergeRootFrame"
    android:background="@drawable/home_bg"
    android:orientation="vertical">
    <RelativeLayout
        android:id="@+id/relTopLeft"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp"
        android:layout_marginLeft="50dp">

        <ImageView
            android:layout_width="230dp"
            android:layout_height="120dp"
            android:scaleType="fitXY"
            android:src="@drawable/home_logo"></ImageView>

        <TextView
            android:id="@+id/tvTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="20dp"
            android:layout_marginRight="20dp"
            android:inputType="date"
            android:text="11:47 PM"
            android:textColor="#fff"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/tvdate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/tvTime"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="20dp"
            android:inputType="date"
            android:text="Sunday 02/02/2020"
            android:textColor="#fff"
            android:textSize="12sp" />
        <ImageView
            android:id="@+id/ivWeather"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentEnd="true"
            android:layout_below="@id/tvdate"
            android:src="@drawable/weather"
            android:layout_marginTop="20dp"
            android:layout_marginRight="140dp"
            android:scaleType="fitXY"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:text="28 C / 68 F"
            android:textColor="#fff"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:layout_below="@id/tvdate"
            android:textSize="16sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_marginEnd="0dp"
            android:background="@drawable/chip"
            android:text="@string/welcome"
            android:textColor="#fff"
            android:textSize="16sp" />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:background="@drawable/chip"
        android:orientation="vertical" >

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_home_selector"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

</LinearLayout>```
</div>
</div>

Main Activity</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.rimapps.myapplication.activity;

import android.app.Activity;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rimapps.myapplication.R;
        ;
import com.rimapps.myapplication.adapter.HomeSelectorAdapter;
import com.rimapps.myapplication.model.ModelHomeSelector;

import java.util.ArrayList;
import java.util.List;

import static java.security.AccessController.getContext;

/*
 * Main Activity class that loads {@link MainFragment}.
 */
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView rvSelector = (RecyclerView)findViewById(R.id.rv_home_selector);
        rvSelector.setNestedScrollingEnabled(false);
        List<ModelHomeSelector> homeSelectorList = new ArrayList();

        ModelHomeSelector object1 = new ModelHomeSelector();
        object1.setSelectorTitle("Guest Directory");
        object1.setSelectorImg(R.drawable.guestdirector);
        homeSelectorList.add(object1);

        ModelHomeSelector object2 = new ModelHomeSelector();
        object2.setSelectorTitle("Restaurant & Bar");
        object2.setSelectorImg(R.drawable.restaurandandbar);
        homeSelectorList.add(object2);

        ModelHomeSelector object3 = new ModelHomeSelector();
        object3.setSelectorTitle("Leisure Facility");
        object3.setSelectorImg(R.drawable.leisurefacility);
        homeSelectorList.add(object3);

        ModelHomeSelector object4 = new ModelHomeSelector();
        object4.setSelectorTitle("Go Green");
        object4.setSelectorImg(R.drawable.go_green_bg);
        homeSelectorList.add(object4);

        ModelHomeSelector object5 = new ModelHomeSelector();
        object5.setSelectorTitle("Promotions");
        object5.setSelectorImg(R.drawable.promotions);
        homeSelectorList.add(object5);

        ModelHomeSelector object6 = new ModelHomeSelector();
        object6.setSelectorTitle("Tv Guide");
        object6.setSelectorImg(R.drawable.tvguide);
        homeSelectorList.add(object6);

        rvSelector.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
        HomeSelectorAdapter adapter = new HomeSelectorAdapter(homeSelectorList, getApplicationContext());
        rvSelector.setAdapter(adapter);

    }
}</code>```

Model class

package com.rimapps.myapplication.model;

public class ModelHomeSelector {
    String selectorTitle;
    int selectorImg;

    public String getSelectorTitle() {
        return selectorTitle;
    }

    public void setSelectorTitle(String selectorTitle) {
        this.selectorTitle = selectorTitle;
    }

    public int getSelectorImg() {
        return selectorImg;
    }

    public void setSelectorImg(int selectorImg) {
        this.selectorImg = selectorImg;
    }
}```
</div>
</div>
</p>

<p>Adapter class</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>package com.rimapps.myapplication.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.leanback.widget.ImageCardView;
import androidx.recyclerview.widget.RecyclerView;

import com.rimapps.myapplication.R;
import com.rimapps.myapplication.model.ModelHomeSelector;

import java.util.ArrayList;
import java.util.List;

public class HomeSelectorAdapter extends RecyclerView.Adapter<HomeSelectorAdapter.ViewHolder> {

    private List<ModelHomeSelector> homeSelectorList = new ArrayList<>();
    Context context;

    public HomeSelectorAdapter(List<ModelHomeSelector> homeSelectorList, Context applicationContext) {
        this.homeSelectorList = this.homeSelectorList;
        this.context = context;
    }

    @NonNull
    @Override
    public HomeSelectorAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_home, parent, false);
        return new ViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") final int position) {

        final String selectorTitle = homeSelectorList.get(position).getSelectorTitle();
        holder.selectorTitle.setText(selectorTitle);
        holder.selectorImg.setImageResource(Integer.parseInt(String.valueOf(homeSelectorList.get(position).getSelectorImg())));
    }

    @Override
    public int getItemCount() {
        return homeSelectorList.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView selectorTitle;
        public ImageView selectorImg;
        public ImageCardView selectorCard;
        public ViewHolder(View itemView) {
            super(itemView);
            selectorCard = (ImageCardView) itemView.findViewById(R.id.selector_card);
            selectorTitle = (TextView) itemView.findViewById(R.id.tv_home_seletor);
            selectorImg=(ImageView) itemView.findViewById(R.id.iv_home_selector);
        }
    }}</code>```

recycler view layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.leanback.widget.ImageCardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/selector_card"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/circle">

        <ImageView
            android:id="@+id/iv_home_selector"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="30dp"
            android:src="@drawable/gogreeen" />
        <TextView
            android:id="@+id/tv_home_seletor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Guest Directory"
            android:textColor="#fff"
            android:textSize="12sp"
            android:textStyle="bold"
            android:layout_below="@id/iv_home_selector"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>

</androidx.leanback.widget.ImageCardView>```

Is there something else I need to do to display it in TV?

答:
Your code looks fine but check these below things which can cause problems

1.Try adding this line and check.

```<code>rvSelector.setHasFixedSize(true);
</code>```

2. also for the sake of trying, remove true from the following line and pass false and LinearLayoutManager.HORIZONTAL to RecylerView.HORIZONTAL here

instead of
rvSelector.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,true));

change it to

rvSelector.setLayoutManager(new LinearLayoutManager(this,RecyclerView.HORIZONTAL, false));

I don't know why are you using this rvSelector.setNestedScrollingEnabled(false) try removing it and check.

Title: Android Tv not displaying Recyclerview

Body:
I created a recycler view in my android tv app, but its not showing anything, I did it as I do for mobile apps, checked by debugging using break points, and the recycler view data is showing there.

My code is as follows

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_browse_fragment"
    android:name="com.rimapps.alrahabeachhotel.MainFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".activity.MainActivity"
    tools:deviceIds="tv"
    tools:ignore="MergeRootFrame"
    android:background="@drawable/home_bg"
    android:orientation="vertical">
    <RelativeLayout
        android:id="@+id/relTopLeft"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp"
        android:layout_marginLeft="50dp">

        <ImageView
            android:layout_width="230dp"
            android:layout_height="120dp"
            android:scaleType="fitXY"
            android:src="@drawable/home_logo"></ImageView>

        <TextView
            android:id="@+id/tvTime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="20dp"
            android:layout_marginRight="20dp"
            android:inputType="date"
            android:text="11:47 PM"
            android:textColor="#fff"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/tvdate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/tvTime"
            android:layout_alignParentEnd="true"
            android:layout_marginRight="20dp"
            android:inputType="date"
            android:text="Sunday 02/02/2020"
            android:textColor="#fff"
            android:textSize="12sp" />
        <ImageView
            android:id="@+id/ivWeather"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_alignParentEnd="true"
            android:layout_below="@id/tvdate"
            android:src="@drawable/weather"
            android:layout_marginTop="20dp"
            android:layout_marginRight="140dp"
            android:scaleType="fitXY"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:text="28 C / 68 F"
            android:textColor="#fff"
            android:layout_marginRight="20dp"
            android:layout_marginTop="20dp"
            android:layout_below="@id/tvdate"
            android:textSize="16sp" />
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_marginEnd="0dp"
            android:background="@drawable/chip"
            android:text="@string/welcome"
            android:textColor="#fff"
            android:textSize="16sp" />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:background="@drawable/chip"
        android:orientation="vertical" >

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/rv_home_selector"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </LinearLayout>

</LinearLayout>

Main Activity

/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.rimapps.myapplication.activity;

import android.app.Activity;
import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.rimapps.myapplication.R;
        ;
import com.rimapps.myapplication.adapter.HomeSelectorAdapter;
import com.rimapps.myapplication.model.ModelHomeSelector;

import java.util.ArrayList;
import java.util.List;

import static java.security.AccessController.getContext;

/*
 * Main Activity class that loads {@link MainFragment}.
 */
public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView rvSelector = (RecyclerView)findViewById(R.id.rv_home_selector);
        rvSelector.setNestedScrollingEnabled(false);
        List<ModelHomeSelector> homeSelectorList = new ArrayList();

        ModelHomeSelector object1 = new ModelHomeSelector();
        object1.setSelectorTitle("Guest Directory");
        object1.setSelectorImg(R.drawable.guestdirector);
        homeSelectorList.add(object1);

        ModelHomeSelector object2 = new ModelHomeSelector();
        object2.setSelectorTitle("Restaurant & Bar");
        object2.setSelectorImg(R.drawable.restaurandandbar);
        homeSelectorList.add(object2);

        ModelHomeSelector object3 = new ModelHomeSelector();
        object3.setSelectorTitle("Leisure Facility");
        object3.setSelectorImg(R.drawable.leisurefacility);
        homeSelectorList.add(object3);

        ModelHomeSelector object4 = new ModelHomeSelector();
        object4.setSelectorTitle("Go Green");
        object4.setSelectorImg(R.drawable.go_green_bg);
        homeSelectorList.add(object4);

        ModelHomeSelector object5 = new ModelHomeSelector();
        object5.setSelectorTitle("Promotions");
        object5.setSelectorImg(R.drawable.promotions);
        homeSelectorList.add(object5);

        ModelHomeSelector object6 = new ModelHomeSelector();
        object6.setSelectorTitle("Tv Guide");
        object6.setSelectorImg(R.drawable.tvguide);
        homeSelectorList.add(object6);

        rvSelector.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
        HomeSelectorAdapter adapter = new HomeSelectorAdapter(homeSelectorList, getApplicationContext());
        rvSelector.setAdapter(adapter);

    }
}

Model class

package com.rimapps.myapplication.model;

public class ModelHomeSelector {
    String selectorTitle;
    int selectorImg;

    public String getSelectorTitle() {
        return selectorTitle;
    }

    public void setSelectorTitle(String selectorTitle) {
        this.selectorTitle = selectorTitle;
    }

    public int getSelectorImg() {
        return selectorImg;
    }

    public void setSelectorImg(int selectorImg) {
        this.selectorImg = selectorImg;
    }
}

Adapter class

package com.rimapps.myapplication.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.leanback.widget.ImageCardView;
import androidx.recyclerview.widget.RecyclerView;

import com.rimapps.myapplication.R;
import com.rimapps.myapplication.model.ModelHomeSelector;

import java.util.ArrayList;
import java.util.List;

public class HomeSelectorAdapter extends RecyclerView.Adapter<HomeSelectorAdapter.ViewHolder> {

    private List<ModelHomeSelector> homeSelectorList = new ArrayList<>();
    Context context;

    public HomeSelectorAdapter(List<ModelHomeSelector> homeSelectorList, Context applicationContext) {
        this.homeSelectorList = this.homeSelectorList;
        this.context = context;
    }

    @NonNull
    @Override
    public HomeSelectorAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_home, parent, false);
        return new ViewHolder(itemView);
    }
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, @SuppressLint("RecyclerView") final int position) {

        final String selectorTitle = homeSelectorList.get(position).getSelectorTitle();
        holder.selectorTitle.setText(selectorTitle);
        holder.selectorImg.setImageResource(Integer.parseInt(String.valueOf(homeSelectorList.get(position).getSelectorImg())));
    }

    @Override
    public int getItemCount() {
        return homeSelectorList.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView selectorTitle;
        public ImageView selectorImg;
        public ImageCardView selectorCard;
        public ViewHolder(View itemView) {
            super(itemView);
            selectorCard = (ImageCardView) itemView.findViewById(R.id.selector_card);
            selectorTitle = (TextView) itemView.findViewById(R.id.tv_home_seletor);
            selectorImg=(ImageView) itemView.findViewById(R.id.iv_home_selector);
        }
    }}

recycler view layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.leanback.widget.ImageCardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/selector_card"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/circle">

        <ImageView
            android:id="@+id/iv_home_selector"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="30dp"
            android:src="@drawable/gogreeen" />
        <TextView
            android:id="@+id/tv_home_seletor"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Guest Directory"
            android:textColor="#fff"
            android:textSize="12sp"
            android:textStyle="bold"
            android:layout_below="@id/iv_home_selector"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true" />

    </RelativeLayout>

</androidx.leanback.widget.ImageCardView>

Is there something else I need to do to display it in TV?

Body:
Your code looks fine but check these below things which can cause problems

1.Try adding this line and check.

rvSelector.setHasFixedSize(true);

2. also for the sake of trying, remove true from the following line and pass false and LinearLayoutManager.HORIZONTAL to RecylerView.HORIZONTAL here

instead of
rvSelector.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL,true));

change it to

rvSelector.setLayoutManager(new LinearLayoutManager(this,RecyclerView.HORIZONTAL, false));

I don't know why are you using this rvSelector.setNestedScrollingEnabled(false) try removing it and check.


问:
Spring boot deployement with Tomcat
I am currently working on the deployement of an application but for some reason it seems to not working perfectly.

While coding, I am running/debugging the project with Intellij Spring Boot runner which is easy to configure.

As I need to deploy on a Tomcat server, I tried to set up first in Intellij a Tomcat Server Runner before running my war from my Tomcat server directly.

Problem is: the run seems not to work properly. In fact, the application is not starting completly even if the deployement doesn't return any error.

Here is a Spring Boot runner output:

```<code>2020-02-19 11:50:18.373 DEBUG 1192 --- [  restartedMain] com.myapp.Application              : Running with Spring Boot v2.2.4.RELEASE, Spring v5.2.3.RELEASE
2020-02-19 11:50:18.374  INFO 1192 --- [  restartedMain] com.myapp.Application              : No active profile set, falling back to default profiles: default
2020-02-19 11:50:18.421  INFO 1192 --- [  restartedMain] o.s.b.devtools.restart.ChangeableUrls    : The Class-Path manifest attribute in C:\Users\user\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.2\jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2020-02-19 11:50:18.422  INFO 1192 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-02-19 11:50:18.422  INFO 1192 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-02-19 11:50:19.223  INFO 1192 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-02-19 11:50:19.288  INFO 1192 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 57ms. Found 1 JPA repository interfaces.
2020-02-19 11:50:19.807  INFO 1192 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-19 11:50:20.115  INFO 1192 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2020-02-19 11:50:20.125  INFO 1192 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-02-19 11:50:20.125  INFO 1192 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-02-19 11:50:20.233  INFO 1192 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
etc.
2020-02-19 11:50:24.396  INFO 1192 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-02-19 11:50:24.399  INFO 1192 --- [  restartedMain] com.myapp.Application              : Started Application in 6.531 seconds (JVM running for 7.815)
</code>```

And a Tomcat runner output:

```<code>2020-02-19 12:14:15.753  INFO 4436 --- [on(3)-127.0.0.1] com.myapp.Application              : Starting Application on UO with PID 4436 (C:\App\apache-tomcat-8.0.47\webapps\server_war\WEB-INF\classes started by user in C:\App\apache-tomcat-8.0.47\bin)
2020-02-19 12:14:15.757 DEBUG 4436 --- [on(3)-127.0.0.1] com.myapp.Application              : Running with Spring Boot v2.2.4.RELEASE, Spring v5.2.3.RELEASE
2020-02-19 12:14:15.760  INFO 4436 --- [on(3)-127.0.0.1] com.myapp.Application              : No active profile set, falling back to default profiles: default
2020-02-19 12:14:15.937  INFO 4436 --- [on(3)-127.0.0.1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 113 ms
2020-02-19 12:14:15.994  INFO 4436 --- [on(3)-127.0.0.1] com.myapp.Application              : Started Application in 1.045 seconds (JVM running for 7.228)
[2020-02-19 12:14:16,029] Artifact server:war: Artifact is deployed successfully
[2020-02-19 12:14:16,029] Artifact server:war: Deploy took 5,204 milliseconds
</code>```

As you can see, Spring is launched correclty but seems to not proceed all its starting tasks.

I already have the spring-boot-starter-tomcat provided in my pom and here is my Application.class:

```<code>@SpringBootApplication public class Application extends SpringBootServletInitializer {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return builder.sources(Application.class);
  }
}
</code>```

My questions are: Did I miss something in my configuration? How to run everything properly with Tomcat with multiple profiles (I am currently using VM options in the runner)?

答:
The Spring Boot Framework itself encapsulates an integrated Tomcat to facilitate implementation without the need to generate a .war and implement its own Tomcat in the traditional way, simply using, for example, the Maven plug-in and to execute it, you would have to use mvn spring-boot : run.

However, if that is how you want, you must generate the war from your Spring Boot project with maven and then add the war to the tomcat webapps folder and now you can launch tomcat locally to test.
Follow the steps that are incorporated into the documentation and you should not have a problem.

https://www.baeldung.com/spring-boot-war-tomcat-deploy

To configure different profiles for deployment you must configure the Tomcat catalina.properties file, so as not to repeat myself a lot, take a look at the following thread:

How to specify a profile when deploying a Spring boot war file to Tomcat?

I hope it helps you!

Title: Spring boot deployement with Tomcat

Body:
I am currently working on the deployement of an application but for some reason it seems to not working perfectly.

While coding, I am running/debugging the project with Intellij Spring Boot runner which is easy to configure.

As I need to deploy on a Tomcat server, I tried to set up first in Intellij a Tomcat Server Runner before running my war from my Tomcat server directly.

Problem is: the run seems not to work properly. In fact, the application is not starting completly even if the deployement doesn't return any error.

Here is a Spring Boot runner output:

2020-02-19 11:50:18.373 DEBUG 1192 --- [  restartedMain] com.myapp.Application              : Running with Spring Boot v2.2.4.RELEASE, Spring v5.2.3.RELEASE
2020-02-19 11:50:18.374  INFO 1192 --- [  restartedMain] com.myapp.Application              : No active profile set, falling back to default profiles: default
2020-02-19 11:50:18.421  INFO 1192 --- [  restartedMain] o.s.b.devtools.restart.ChangeableUrls    : The Class-Path manifest attribute in C:\Users\user\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.2\jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/C:/Users/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
2020-02-19 11:50:18.422  INFO 1192 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2020-02-19 11:50:18.422  INFO 1192 --- [  restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2020-02-19 11:50:19.223  INFO 1192 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-02-19 11:50:19.288  INFO 1192 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 57ms. Found 1 JPA repository interfaces.
2020-02-19 11:50:19.807  INFO 1192 --- [  restartedMain] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-19 11:50:20.115  INFO 1192 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2020-02-19 11:50:20.125  INFO 1192 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-02-19 11:50:20.125  INFO 1192 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-02-19 11:50:20.233  INFO 1192 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
etc.
2020-02-19 11:50:24.396  INFO 1192 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-02-19 11:50:24.399  INFO 1192 --- [  restartedMain] com.myapp.Application              : Started Application in 6.531 seconds (JVM running for 7.815)

And a Tomcat runner output:

2020-02-19 12:14:15.753  INFO 4436 --- [on(3)-127.0.0.1] com.myapp.Application              : Starting Application on UO with PID 4436 (C:\App\apache-tomcat-8.0.47\webapps\server_war\WEB-INF\classes started by user in C:\App\apache-tomcat-8.0.47\bin)
2020-02-19 12:14:15.757 DEBUG 4436 --- [on(3)-127.0.0.1] com.myapp.Application              : Running with Spring Boot v2.2.4.RELEASE, Spring v5.2.3.RELEASE
2020-02-19 12:14:15.760  INFO 4436 --- [on(3)-127.0.0.1] com.myapp.Application              : No active profile set, falling back to default profiles: default
2020-02-19 12:14:15.937  INFO 4436 --- [on(3)-127.0.0.1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 113 ms
2020-02-19 12:14:15.994  INFO 4436 --- [on(3)-127.0.0.1] com.myapp.Application              : Started Application in 1.045 seconds (JVM running for 7.228)
[2020-02-19 12:14:16,029] Artifact server:war: Artifact is deployed successfully
[2020-02-19 12:14:16,029] Artifact server:war: Deploy took 5,204 milliseconds

As you can see, Spring is launched correclty but seems to not proceed all its starting tasks.

I already have the spring-boot-starter-tomcat provided in my pom and here is my Application.class:

@SpringBootApplication public class Application extends SpringBootServletInitializer {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return builder.sources(Application.class);
  }
}

My questions are: Did I miss something in my configuration? How to run everything properly with Tomcat with multiple profiles (I am currently using VM options in the runner)?


问:
Using id in place of an NSString
I'm parsing some JSON.

Sometimes the JSON returns an NSNull which i was allowing to go into a string and then i would check the String to see if it contrained the NSNull and then handled it. The code worked as intended but the compiler complained with a warning.

```<code>if ((theMonograph.cautions != nil) && (theMonograph.cautions != [NSNull null]))
{
    //draw string
}
</code>```

In Monograph.h

```<code>NSString *cautions;
@property (nonatomic, retain) NSString *cautions;
</code>```

So I though maybe the correct way to handle it would be to change to an id in the place of the NSString

Monograph.h

```<code>id *cautions;
@property (nonatomic, retain) id *cautions;
</code>```

But this still generated another warning

passing argument 1 of 'setCautions:' from incompatible pointer type

What is the correct way to handle this? I'm guessing letting NSNull go into an NSString object was wrong. But putting an id object in its place didnt seem right.

Many Thanks
-Code

答:
An id is already declared as a pointer to an NSObject so get rid of the asterisk:

```<code>id cautions;
@propertry (nonatomic, retain) id cautions;
</code>```

Title: Using id in place of an NSString

Body:
I'm parsing some JSON.

Sometimes the JSON returns an NSNull which i was allowing to go into a string and then i would check the String to see if it contrained the NSNull and then handled it. The code worked as intended but the compiler complained with a warning.

if ((theMonograph.cautions != nil) && (theMonograph.cautions != [NSNull null]))
{
    //draw string
}

In Monograph.h

NSString *cautions;
@property (nonatomic, retain) NSString *cautions;

So I though maybe the correct way to handle it would be to change to an id in the place of the NSString

Monograph.h

id *cautions;
@property (nonatomic, retain) id *cautions;

But this still generated another warning

passing argument 1 of 'setCautions:' from incompatible pointer type

What is the correct way to handle this? I'm guessing letting NSNull go into an NSString object was wrong. But putting an id object in its place didnt seem right.

Many Thanks
-Code

Body:
An id is already declared as a pointer to an NSObject so get rid of the asterisk:

id cautions;
@propertry (nonatomic, retain) id cautions;


问:
Can't set Authentication Header with Angular and Spring Security
I'm having trouble getting Angular, CORS, SpringSecurity and Basic Authentication to play nicely.  I have the following Angular Ajax call where I'm trying to set the header to include a Basic Authorization header in the request.

```<code>var headerObj = {headers: {'Authorization': 'Basic am9lOnNlY3JldA=='}};
return $http.get('http://localhost:8080/mysite/login', headerObj).then(function (response) {
    return response.data;
});
</code>```

I am running my angular app on localhost:8888 and my backend server on localhost:8080.  So I had to add a CORS filter to my server side which is Spring MVC.  So I created a filter and added it to my web.xml.

web.xml

```<code><filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>com.abcinsights.controller.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

CorsFilter

```<code>public class SimpleCorsFilter extends OncePerRequestFilter {

@Override
public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
    Enumeration<String> headerNames = req.getHeaderNames();
    while(headerNames.hasMoreElements()){
        String headerName = headerNames.nextElement();
        System.out.println("headerName " + headerName);
        System.out.println("headerVal " + req.getHeader(headerName));
    }
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization");
    chain.doFilter(req, res);
}
}
</code>```

This all works fine and when I look at the header names/values I see my Authorization header with the Basic value and the hard coded Base64 string.

So then I tried to add SpringSecurity which would use the Authorization header to do basic authentication.  Here's my web.xml and spring security config with Spring Security added in.

updated web.xml

```<code><listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/config/security-config.xml</param-value>
</context-param>

<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

security-config.xml

```<code><http auto-config="true" use-expressions="false">
    <intercept-url pattern="/**" access="ROLE_USER" />
    <http-basic/>
    <custom-filter ref="corsHandler" before="SECURITY_CONTEXT_FILTER"/>
</http>

<beans:bean id="corsHandler" class="com.abcinsights.controller.SimpleCorsFilter"/>

<authentication-manager>
    <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"/>
    </authentication-provider>
</authentication-manager>
</code>```

As you can see, I had to add my CORS filter to the front of the spring security filter chain (I also removed it from web.xml).  This seems to be working in the sense that the CORS filter still gets called when I make a request.  But the request coming from my AJAX call no longer has the Authorization header added in.  When I remove the SpringSecurity filter chain and just put my CORS filter back into web.xml the Authorization header comes back.  I'm at a loss but am wondering if it has something to do with preflight communication working one way when my CORS filter is stand alone in web.xml and another way when it is in the Spring Security filter chain?  Any help would be appreciated.

Thanks

答:
A bit late to the party, but I encountered a similar problem, and thought my soulution might help someone. Joe Rice's soulution really helped me, but I had to make some modifications. I should also mention that I'm not an expert on Spring or Tomcat, so this is probably not a perfect solution.

I have a setup with a React client (running on localhost:3000), Tomcat server (localhost:8080) and Spring Security. I had to make Tomcat handle the CORS headers, as I have two .war-files running on the application server: my application and Geowebcache. It was not sufficient for me to make Spring Security handle the headers, as that would mean that the headers would not be added when the client was communicating directly with Geowebcache.

I also use a login-page implemented with Spring Security. Using Tomcat 'CorsFilter' works fine for all regular requests, but for some reason, the CORS headers was not added on the login request from the client, resulting in the response being blocked by the browser because of missing because of missing 'Access-Control-Allow-Origin' header. My solution to this was to manually add the headers to the login-call from the client, and let the Tomcat config handle the rest. This is my setup.

Spring Security - web.xml:

```<code><filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>path.to.cors.filter.security.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

Spring Security Config:

```<code> http.csrf().disable()
            .formLogin().loginPage("/login").permitAll()
            .loginProcessingUrl("/perform_login")
            .defaultSuccessUrl("/index.html", true)
            .failureUrl("/login?error=true");
</code>```

SimpleCorsFilter.java:

```<code>public class SimpleCorsFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (request.getRequestURI().endsWith("perform_login")) {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization, X-CSRF-TOKEN");
    }

    chain.doFilter(req, res);
}
</code>```

Tomcat - web.xml

```<code><filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>http://localhost:3000</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Content-Disposition,Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>
</code>```

I am using Axios to make the requests from the client, and I had to add 'withCredentials: true' to make the server accept the requests. This is my Axios configuration:

```<code>axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:8080/api/' : '/api/',
  timeout: 300000,
  withCredentials: true
});
</code>```

Hope this can help someone!

Body:
I'm having trouble getting Angular, CORS, SpringSecurity and Basic Authentication to play nicely.  I have the following Angular Ajax call where I'm trying to set the header to include a Basic Authorization header in the request.

var headerObj = {headers: {'Authorization': 'Basic am9lOnNlY3JldA=='}};
return $http.get('http://localhost:8080/mysite/login', headerObj).then(function (response) {
    return response.data;
});

I am running my angular app on localhost:8888 and my backend server on localhost:8080.  So I had to add a CORS filter to my server side which is Spring MVC.  So I created a filter and added it to my web.xml.

web.xml

<filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>com.abcinsights.controller.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

CorsFilter

public class SimpleCorsFilter extends OncePerRequestFilter {

@Override
public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
    Enumeration<String> headerNames = req.getHeaderNames();
    while(headerNames.hasMoreElements()){
        String headerName = headerNames.nextElement();
        System.out.println("headerName " + headerName);
        System.out.println("headerVal " + req.getHeader(headerName));
    }
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization");
    chain.doFilter(req, res);
}
}

This all works fine and when I look at the header names/values I see my Authorization header with the Basic value and the hard coded Base64 string.

So then I tried to add SpringSecurity which would use the Authorization header to do basic authentication.  Here's my web.xml and spring security config with Spring Security added in.

updated web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/config/security-config.xml</param-value>
</context-param>

<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

security-config.xml

<http auto-config="true" use-expressions="false">
    <intercept-url pattern="/**" access="ROLE_USER" />
    <http-basic/>
    <custom-filter ref="corsHandler" before="SECURITY_CONTEXT_FILTER"/>
</http>

<beans:bean id="corsHandler" class="com.abcinsights.controller.SimpleCorsFilter"/>

<authentication-manager>
    <authentication-provider>
        <jdbc-user-service data-source-ref="dataSource"/>
    </authentication-provider>
</authentication-manager>

As you can see, I had to add my CORS filter to the front of the spring security filter chain (I also removed it from web.xml).  This seems to be working in the sense that the CORS filter still gets called when I make a request.  But the request coming from my AJAX call no longer has the Authorization header added in.  When I remove the SpringSecurity filter chain and just put my CORS filter back into web.xml the Authorization header comes back.  I'm at a loss but am wondering if it has something to do with preflight communication working one way when my CORS filter is stand alone in web.xml and another way when it is in the Spring Security filter chain?  Any help would be appreciated.

Thanks

Body:
A bit late to the party, but I encountered a similar problem, and thought my soulution might help someone. Joe Rice's soulution really helped me, but I had to make some modifications. I should also mention that I'm not an expert on Spring or Tomcat, so this is probably not a perfect solution.

I have a setup with a React client (running on localhost:3000), Tomcat server (localhost:8080) and Spring Security. I had to make Tomcat handle the CORS headers, as I have two .war-files running on the application server: my application and Geowebcache. It was not sufficient for me to make Spring Security handle the headers, as that would mean that the headers would not be added when the client was communicating directly with Geowebcache.

I also use a login-page implemented with Spring Security. Using Tomcat 'CorsFilter' works fine for all regular requests, but for some reason, the CORS headers was not added on the login request from the client, resulting in the response being blocked by the browser because of missing because of missing 'Access-Control-Allow-Origin' header. My solution to this was to manually add the headers to the login-call from the client, and let the Tomcat config handle the rest. This is my setup.

Spring Security - web.xml:

<filter>
    <filter-name>corsFilter</filter-name>
    <filter-class>path.to.cors.filter.security.SimpleCorsFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>corsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Spring Security Config:

 http.csrf().disable()
            .formLogin().loginPage("/login").permitAll()
            .loginProcessingUrl("/perform_login")
            .defaultSuccessUrl("/index.html", true)
            .failureUrl("/login?error=true");

SimpleCorsFilter.java:

public class SimpleCorsFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (request.getRequestURI().endsWith("perform_login")) {
        response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization, X-CSRF-TOKEN");
    }

    chain.doFilter(req, res);
}

Tomcat - web.xml

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>http://localhost:3000</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Content-Disposition,Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

I am using Axios to make the requests from the client, and I had to add 'withCredentials: true' to make the server accept the requests. This is my Axios configuration:

axios.create({
  baseURL: process.env.NODE_ENV === 'development' ? 'http://localhost:8080/api/' : '/api/',
  timeout: 300000,
  withCredentials: true
});

Hope this can help someone!