Sunday, January 31, 2021

Log4j2 Properties YAML XML - How to tell Application where to find log4j2 Configuration ?

 http://logging.apache.org/log4j/2.x/manual/configuration.html

https://stackoverflow.com/questions/28572783/no-log4j2-configuration-file-found-using-default-configuration-logging-only-er/38326259


-Dlog4j.configurationFile="file:///C:/Users/Karan/Desktop/ExternalConfig/log4j2.xml"


Log4j has the ability to automatically configure itself during initialization. When Log4j starts it will locate all the ConfigurationFactory plugins and arrange them in weighted order from highest to lowest. As delivered, Log4j contains four ConfigurationFactory implementations: one for JSON, one for YAML, one for properties, and one for XML.


Log4j will inspect the "log4j.configurationFile" system property and, if set, will attempt to load the configuration using the ConfigurationFactory that matches the file extension. Note that this is not restricted to a location on the local file system and may contain a URL.

If no system property is set the properties ConfigurationFactory will look for log4j2-test.properties in the classpath.

If no such file is found the YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the classpath.

If no such file is found the JSON ConfigurationFactory will look for log4j2-test.json or log4j2-test.jsn in the classpath.

If no such file is found the XML ConfigurationFactory will look for log4j2-test.xml in the classpath.

If a test file cannot be located the properties ConfigurationFactory will look for log4j2.properties on the classpath.

If a properties file cannot be located the YAML ConfigurationFactory will look for log4j2.yaml or log4j2.yml on the classpath.

If a YAML file cannot be located the JSON ConfigurationFactory will look for log4j2.json or log4j2.jsn on the classpath.

If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath.

If no configuration file could be located the DefaultConfiguration will be used. This will cause logging output to go to the console.

Saturday, January 30, 2021

Types of Spring @Autowired

 We can implement dependency injection with:

https://www.baeldung.com/properties-with-spring

https://reflectoring.io/constructor-injection/

  • constructor-based injection
@Component
class Sandwich {

  private Topping toppings;
  private Bread breadType;

  @Autowired
  Sandwich(Topping toppings, Bread breadType) {
    this.toppings = toppings;
    this.breadType = breadType;
  }

}

  • setter-based injection
@Component
class Cookie {

  private Topping toppings;

  @Autowired
  void setTopping(Topping toppings) {
    this.toppings = toppings;
  }
}

  • field-based injection.
@Component
class Pizza {

  @Autowired
  private Topping toppings;
}

Why can't you use @Autowired with static fields?

Because when the class loader loads the static values, the Spring context is not yet necessarily loaded. So the class loader won't properly inject the static fields in the bean and will fail.

https://stackoverflow.com/questions/10938529/why-cant-we-autowire-static-fields-in-spring/21875258#21875258


Its basically an "ANTI-PATTERN", Still we have a hack to work around this limitation, Here it is.

https://stackoverflow.com/questions/1018797/can-you-use-autowired-with-static-fields/5991240#5991240

@Component("NewClass")
public class NewClass{
    private static SomeThing someThing;

    @Autowired
    public void setSomeThing(SomeThing someThing){
        NewClass.someThing = someThing;
    }
}

URI - Filepath vs Spring Filepath Convention

 file:///C:/Path

https://en.wikipedia.org/wiki/File_URI_scheme

https://www.marcobehler.com/guides/java-files

Format[edit]

A file URI takes the form of

file://host/path

where host is the fully qualified domain name of the system on which the path is accessible, and path is a hierarchical directory path of the form directory/directory/.../name. If host is omitted, it is taken to be "localhost", the machine from which the URL is being interpreted. Note that when omitting host, the slash is not omitted (while "file:///foo.txt" is valid, "file://foo.txt" is not, although some interpreters manage to handle the latter).

RFC 3986 includes additional information about the treatment of ".." and "." segments in URIs.

How many slashes?[edit]

  • The // after the file: denotes that either a hostname or the literal term localhost will follow,[2] although this part may be omitted entirely, or may contain an empty hostname.[3]
  • The single slash between host and path denotes the start of the local-path part of the URI and must be present.[4]
  • A valid file URI must therefore begin with either file:/pathfile:///path or file://hostname/path.
  • file://path (i.e. two slashes, without a hostname) is never correct, but is often used.
  • Further slashes in path separate directory names in a hierarchical system of directories and subdirectories. In this usage, the slash is a general, system-independent way of separating the parts, and in a particular host system it might be used as such in any pathname (as in Unix systems).

Spring Filepath just has prefix "file:"
  • -DjunkCharCleanup="file:C:/Users/703250313/Desktop/ExternalConfig/junk-char-cleanup"
URI Filepath
  • -DsamlMetaDataFilepath="file:///C:/Users/703250313/Desktop/ExternalConfig/metadata.xml"

Spring Bean: Is autowired attribute initialised before constructor?

https://stackoverflow.com/questions/26230493/spring-bean-is-autowired-attribute-initialised-before-constructor


  1. First Constructor is called
  2. Then Spring Bean is initialized

Unicode to Character - How ?

https://www.branah.com/unicode-converter

Maven to Spring Application.Properties - Profile

 #server.port=8081

spring.profiles.active=@activatedProperties@

https://www.petrikainulainen.net/programming/tips-and-tricks/creating-profile-specific-configuration-files-with-maven/


<profiles>

<!-- DEV Build -->

<profile>

<id>DEV1</id>

<properties>

<activatedProperties>DEV1</activatedProperties>

</properties>

</profile>


<!-- AZURE Build -->

<profile>

<id>QA</id>

<properties>

<activatedProperties>QA</activatedProperties>

</properties>

</profile>

@Service classes are being created twice when the application starts.

https://stackoverflow.com/questions/4333390/service-are-constructed-twice


You're doing two separate component-scans over the same base-package. Remove one of them.
Make the following changes

myapp-config.xml

<!-- Load everything except @Controllers -->
<context:component-scan base-package="com.myapp">
    <context:exclude-filter expression="org.springframework.stereotype.Controller"
        type="annotation"/>
</context:component-scan>

myapp-servlet.xml

<!-- Load @Controllers only -->
<context:component-scan base-package="com.myapp" use-default-filters="false">
    <context:include-filter expression="org.springframework.stereotype.Controller" 
        type="annotation"/>
</context:component-scan>

CURL Headers Base64 Authorization

curl --location --request POST 'https://test.salesforce.com/services/oauth2/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: BrowserId=4jzphkElEeu76TsJSxG4Tw' \
--data-urlencode 'client_id='a2rtyoi.k9iosdgh.b6rbmnb' \
--data-urlencode 'client_secret=23987590772833' \
--data-urlencode 'grant_type=password' \
--data-urlencode 'username=foo@bar.com' \
--data-urlencode 'password=Red1$Apple'

curl --location --request GET 'http://10.102.13.101:8086' --header 'Authorization: Basic base64[username:Password]
curl --location --request GET 'http://AZ-CVS-LI-RE-02:8086' --header 
'Authorization: Basic U2hlZXRhbFM6ZWYxNTE1NWY3YTJjOGNiZWIyYjM3N2Q0NmQ2ZWRkYzkzOTg3NjljYTlhMzUyOTkwZDFhYjI1MzcxNDAyNzJiYQ=='

Friday, January 29, 2021

Code Syntax Highlighter in Blogger

Use this website 

https://tohtml.com   - It generates HTML

https://codebeautify.org/alleditor   - It just formats Code

http://hilite.me/  - It generates Line Number + Code Syntax Highlighter

Generate HTML code snippet and copy it in "HTML View" mode of Blogger



Thursday, January 28, 2021

Bean Create Dynamically in Spring with Params ?

package org.springframework.beans.factory.config;
public interface BeanDefinition extends AttributeAccessor, BeanMetadataElement {
	String SCOPE_SINGLETON = ConfigurableBeanFactory.SCOPE_SINGLETON;
	String SCOPE_PROTOTYPE = ConfigurableBeanFactory.SCOPE_PROTOTYPE;
}

Beans can be "prototype" - Bean generated afresh at each call
or It can be "singleton" - One Bean for all Calls




How to pass parameters dynamically to Spring beans @Bean
@Configuration
public class ApplicationConfiguration {
  @Bean
  @Scope("prototype") //As we want to create several beans with different args, right?


Thursday, January 21, 2021

Find a Word in VI editor

https://ccm.net/faq/982-finding-a-word-in-vi-vim



To find a word in Vi/Vim, simply type the / or ? key, followed by the word you're searching for.

Once found, you can press the n key to go directly to the next occurrence of the word.

Vi/Vim also allows you to launch a search on the word over which your cursor is positioned. To do this, place the cursor over the term, and then press * or # to look it up.

Wednesday, January 20, 2021

ResourceBundle - FileLocation and Classpath

 https://www.programmersought.com/article/44943226090/


ResourceBundle file is read in the classpath, that is, the src or src directory, and we need to be packaged in the project, properties files packed in jar, modify inconvenient, we need to be placed outside the jar file properties you can be modified at any time.

1, generally the default mode ResourceBundel read file is read path CLASSPATH, configuration file named resourceBundle.properties. In the src root directory:

ResourceBundle rb=ResourceBundle.getBundle("resourceBundle")



2, resourceBundle.properties placed in a folder, such as the new config folder,

private static ResourceBundle rb; private static BufferedInputStream inputStream; static { String proFilePath = System.getProperty("user.dir") +"\\config\\resourceBundle.properties"; try { inputStream = new BufferedInputStream(new FileInputStream(proFilePath)); rb = new PropertyResourceBundle(inputStream); inputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }


Tuesday, January 19, 2021

Configuration - Externalizing /Externalization

https://reflectoring.io/externalize-configuration/


The Road to Hell: Internal Configuration

The configuration parameters are inside of the deployment artifact, which is why I call this internal configuration.

So what’s wrong with this approach?

First off, this approach doesn’t scale. Each time we’re changing a configuration parameter we have to re-build and re-deploy an artifact. Each time we have to wait for the build to finish before we can test the change.

Basically, it all boils down to this approach being a violation of the Single Responsibility Principle. This principle says that a unit of code should have as few reasons to change as possible.

If we transfer this principle to our deployment artifact, we see that our deployment artifact simply has too many reasons to change. Any configuration parameter is such a reason. A change in any parameter inevitably leads to a new artifact.

A clear indicator for internal configuration is when the build process takes a parameter that specifies a certain runtime environment.



External Configuration to the Rescue



Within each environment lives a configuration that is valid for this environment only. This configuration is passed into the application at startup.

This approach negates all drawbacks of internal configuration discussed above.

  • Fixed File Path Directory having config files
  • Config Server
  • Cmd line
  • Environmental Variables


Externalisation of Configuration - Spring Boot --spring.config.location --spring.config.additional-location

https://www.baeldung.com/spring-properties-file-outside-jar

https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html

----------------------------------------------------------------------------

By default, Spring Boot looks for "application.properties", "application.yml" inside
locations defined by "spring.config.location" Application Java Arguments

Note :
-Dfoo.bar=fubar (JVM Arg) (-D)
--foo.bar=fubar (Application Arg) (--)

If If you prefer to add additional locations, rather than replacing them, you can use "spring.config.additional-location"

Spring Boot - will look for Files in these config Locations apart from Usual Config Directories inside the Project and read them and Will be used to fill Values from @Value Annotations at Startup 

@Configuration
public class SystemPropertiesFilepaths {

	@Value("${applicationProperties}")
	private String applicationProperties;

	@Value("${processDetails}")
	private String processDetails;

	@Value("${databaseProperties}")
	private String databaseProperties;
}
  //Getters or Field Level Accessors used to fetch Values 

----------------------------------------------------------------------------

export SPRING_CONFIG_NAME=application,jdbc export SPRING_CONFIG_LOCATION=file:///Users/home/config

java -jar app.jar --spring.config.name=application,jdbc --spring.config.location=file:///Users/home/config

----------------------------------------------------------------------------

Using the Default Location

By convention, Spring Boot looks for an externalized configuration file – application.properties or application.yml – in 4 predetermined locations in the following order of precedence:

  • /config subdirectory of the current directory

Using the Command Line

We can also pass a folder location where the application will search for the file:

java -jar app.jar --spring.config.name=application,jdbc --spring.config.location=file:///Users/home/config


Using Environment Variables

Or, let's say that we can't alter the start-up command. What's great is Spring Boot will also read the environment variables SPRING_CONFIG_NAME and SPRING_CONFIG_LOCATION

export SPRING_CONFIG_NAME=application,jdbc
export SPRING_CONFIG_LOCATION=file:///Users/home/config
java -jar app.jar


2.3. External Application Properties

Spring Boot will automatically find and load application.properties and application.yaml files from the following locations when your application starts:

  1. The classpath root

  2. The classpath /config package

  3. The current directory

  4. The /config subdirectory in the current directory

  5. Immediate child directories of the /config subdirectory

The list is ordered by precedence (with values from lower items overriding earlier ones). Documents from the loaded files are added as PropertySources to the Spring Environment.

If you do not like application as the configuration file name, you can switch to another file name by specifying a spring.config.name environment property. You can also refer to an explicit location by using the spring.config.location environment property (which is a comma-separated list of directory locations or file paths). The following example shows how to specify a different file name:

$ java -jar myproject.jar --spring.config.name=myproject

The following example shows how to specify two locations:

$ java -jar myproject.jar --spring.config.location=optional:classpath:/default.properties,optional:classpath:/override.properties
Use the prefix optional: if the locations are optional and you don’t mind if they don’t exist.
spring.config.name and spring.config.location are used very early to determine which files have to be loaded. They must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument).

If spring.config.location contains directories (as opposed to files), they should end in / (at runtime they will be appended with the names generated from spring.config.name before being loaded). Files specified in spring.config.location are used as-is. Whether specified directly or contained in a directory, configuration files must include a file extension in their name. Typical extensions that are supported out-of-the-box are .properties.yaml, and .yml.

When multiple locations are specified, the later ones can override the values of earlier ones.

Locations configured by using spring.config.location replace the default locations. For example, if spring.config.location is configured with the value optional:classpath:/custom-config/,optional:file:./custom-config/, the complete set of locations considered is:

  1. optional:classpath:custom-config/

  2. optional:file:./custom-config/

If you prefer to add additional locations, rather than replacing them, you can use spring.config.additional-location. Properties loaded from additional locations can override those in the default locations. For example, if spring.config.additional-location is configured with the value optional:classpath:/custom-config/,optional:file:./custom-config/, the complete set of locations considered is:

  1. optional:classpath:/

  2. optional:classpath:/config/

  3. optional:file:./

  4. optional:file:./config/

  5. optional:file:./config/*/

  6. optional:classpath:custom-config/

  7. optional:file:./custom-config/

This search ordering lets you specify default values in one configuration file and then selectively override those values in another. You can provide default values for your application in application.properties (or whatever other basename you choose with spring.config.name) in one of the default locations. These default values can then be overridden at runtime with a different file located in one of the custom locations.

Azure - Pipeline - Add Approver for Stage

https://learn.microsoft.com/en-us/azure/devops/pipelines/process/approvals?view=azure-devops&tabs=check-pass