Friday, 25 November 2016

Execution default of goal org.springframework.boot:spring-boot-maven-plugin:1.2.3.RELEASE:repackage failed: Unable to find main class

Solutions: 


Solution 1 :

You needed to change the packaging parameter to jar from pom. Also, the repositories, pluginRepositories, the maven-compiler-plugin and the spring-boot-maven-plugin's version and executions weren't needed.


Solution 2: 

Try mvn install and see if it works


Solution 3:


Preview:
<properties>
    <!-- The main class to start by executing java -jar -->
    <start-class>com.mycorp.starter.HelloWorldApplication</start-class>
</properties>

Solution 4:

Enable the main() method in your Application.java.

Configure spring-boot-maven-plugin to specify the class with the main class (Spring should find it anyway if you have one, but good to be explicit):


Preview:
<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>${spring-boot-version}</version>
    <configuration>
        <mainClass>the.package.of.Application</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Wednesday, 23 November 2016

Error: Could not find or load main class


Solutions :


Same Problem occur with me once below are the steps i follow.


Solution 1 :

  • I went to project > properties > javaBuildPath.
  • There In order of export , I moved up my java/main to the top priority.


Solution 2 :


  • Go to run configurations: - run->run configurations
  • In the Classpath tab: Select Advanced
  • Add where Eclipse usually put the *.class for the projects, which is in bin. So I added the bin directory for the project.

Solution 3 :

  • Project -> Clean
  • Make sure Project -> Build automatically is active
  • Project -> Properties -> Java Build Path -> Libraries: Remove any external libs you have ever added. Don't remove standard libraries like the JRE System Library.
  • Try to run your main class now. The "class could not be found / load" error should be gone. Try adding your external libs/jars one after each other.




java.lang.object cannot be resolved / javax.cache.Cache cannot be resolved. It is indirectly referenced from required .class files


Problem Statements :

Description
Location
Type
The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files
line 1
Java Problem
The project was not built since its build path is incomplete. Cannot find the class file for java.lang.Object. Fix the build path then try building this project
Unknown
Java Problem
The method myMethod(SomeClass) from the type MyOtherClass refers to the missing type (insert java type here: InputStream|File|Vector|IOException|etc)
line 123
Java Problem


Solutions : 

  • Close the project and reopen it.
  • Clean the project (It will rebuild the buildpath hence reconfiguring with the JDK libraries)
    OR
  • Delete and Re-import the project and if necessary do the above steps again.



The following steps could help:
  1. Right-click on project » Properties » Java Build Path
  2. Select Libraries tab
  3. Find the JRE System Library and remove it
  4. Click Add Library... button at right side » Add the JRE System Library (Workspace default JRE)




Add this  entry in your POM.xml file


Preview:
<dependency>

    <groupId>javax.cache</groupId>

    <artifactId>cache-api</artifactId>

</dependency>


Thursday, 17 November 2016

Required request body content is missing: org.springframework.web.method.HandlerMethod


You can't send a request body with an HTTP GET request. You should modify your call so that it only supports POST, and POST your JSON to that endpoint.

If you want to GET information about a bean, you should create a separate controller method that does that (and does not require a request body).

Also, double-check your endpoint definitions  in the $.ajax call.

Monday, 24 October 2016

Disable start up of Hibernate configuration in Spring boot.

#Exclude start up of Hibernate JPA configuration

Add below entry in your application.properties file


spring.autoconfigure.exclude[0]=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration

Friday, 14 October 2016

Error: [$http:badreq] Http request configuration url must be a string. Received


$http.get is a shortcut method for $http({ method: 'GET' }), and expects the URL as the first parameter.


Solution:
 
$http({
  method: 'JSONP',
  url: url
}).then(function successCallback(response) {
  // ok
}, function errorCallback(response) {
  // ko
});



Highlight code snippet in Blogger post.

I m using this pretty tool for my blog to highlight the codes.

Its colorful and also provide formatting of codes.


Go to link :
http://hilite.me/


So will see below window 




1. Just copy paste your code in the source code window.
2. select your language.
3. select your style.
4. Choose line numbers if you want to show.
5. click on highlight button.

Preview window will open with colorful text and formatted lines.


This is easy to use and pretty cool.

Thursday, 13 October 2016

exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.json.JSONObject

Could not write content: No serializer found for class org.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )


controller methods return simple POJOs - Collection<Bookmark>, and Bookmark, etc., 

When an HTTP request comes in that specifies an Accept header, Spring MVC loops through the configured HttpMessageConverter until it finds one that can convert from the POJO domain model types into the content-type specified in the Accept header, if so configured.

Spring Boot automatically wires up an HttpMessageConverter that can convert generic Object's to JSON, absent any more specific converter. HttpMessageConverter s work in both directions: incoming requests bodies are converted to Java objects, and Java objects are converted into HTTP response bodies.

To solve Exception just override the default behaivour of the HttpMessageConverter provided by spring.

    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
         MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
                ObjectMapper objectMapper = new ObjectMapper();
         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
         objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
         jsonConverter.setObjectMapper(objectMapper);
         return jsonConverter;
    }


This will do the trick for you.

Caused by: java.lang.IllegalArgumentException: 'dataSource' or 'jdbcTemplate' is required


A Simple DAO class extends JdbcDaoSupport, but, unable to inject or @autowired a “dataSource”, the method setDataSource is final, can’t override.

Solution

To quickly fix it, uses @PostConstruct to inject the dataSource like this :


@Repository
public class UserDetailsDaoImpl extends JdbcDaoSupport implements UserDetailsDao {

 @Autowired
 private DataSource dataSource;

 @PostConstruct
 private void initialize() {
  setDataSource(dataSource);
 }

}


Alternatively, create an own implementation of JdbcDaoSupport class, and do whatever you want. Dive inside the source code of JdbcDaoSupport, it’s just a simple helper class to create a jdbcTemplate.


Source :- https://www.mkyong.com/spring/how-to-autowire-datasource-in-jdbcdaosupport/

org.hibernate.hql.internal.ast.querysyntaxexception: "table_name" is not mapped Spring boot

Put your SampleWebJspApplication.java in pl.test package and execute the application.

It is recommended by Spring Boot to run your application from the root package and all your entities, controllers,DAO's and other service classes should be placed in child packages. This is not a hard and fast rule but it ensures all your subpackage annotated classes are scanned properly

In your case your User class is not scanned and Hibernate is not able to find the mapping for the same and eventually throwing the QuerySyntaxException when executing the from User query.

Currently Spring Boot will scan @Entity classes if they are placed in the same package or sub-packages where you specified the @SpringBootApplication annotation. Atleast, this is what I observed while developing spring boot apps lately.

If you do not want to move the location of the 

SampleApplication.java, then use 

@EntityScan(basePackages = "pl.test.model")

 annotation and this will fix the issue.

Wednesday, 12 October 2016

spring boot controllers not initialized

Controllers are not initialize because you have not scan the packages for controller

add these lines in your main class.

If you are scanning a particular class for controller.

@SpringBootApplication
@ComponentScan(basePackageClasses = temInventoryController.class)
public class InventoryApp {


if you want to scan a whole package for controller add this.

@ComponentScan(basePackages = "com.home.controller")





ORACLE : Io exception: The Network Adapter could not establish the connection

Not connecting to correct Database in oracle :


jdbc:oracle:thin:@<server_host>:1521:<instance_name>

the following commands will help:

1. Oracle query command to check the SID (or instance name):

select sys_context('userenv','instance_name') from dual; 


2. Oracle query command to check database name (or server host):

select sys_context('userenv', 'server_host') from dual;

Tuesday, 11 October 2016

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project mrpapp: Compilation failure

[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?


 Go to Window → Preferences → Java → Installed JREs.

And see if there is an entry pointing to your JDK path, and if not, click on Edit button and put the path you configured your JAVA_HOME environment


Saturday, 17 September 2016

Failure to transfer https://repo.maven.apache.org/maven2 was cached in the local repository


Error :

Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.17 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.17 from/to central (https://repo.maven.apache.org/maven2): The operation was cancelled. pom.xml /LogReaderServer line 1 Maven Configuration Problem


Solution :

Remove all your failed downloads:

For windows:
cd %userprofile%\.m2\repository
for /r %i in (*.lastUpdated) do del %i

Thursday, 5 May 2016

Spring circular dependency solution

I would like to suggest a solution of Dependency Injection which will be as much loyal as possible to the Spring IoC way and will help to overcome the circular dependency error.
This means that we will have a single class that will have a reference to all the classes which need to be injected and will be responsible for the injection.
I'll try to walk you through the steps.
Assuming we have the following service classes which cause the circular error:
@Service
public class ServiceA{
@Autowire
ServiceB serviceB;
@Autowire
ServiceC serviceC;
}
@Service
public class ServiceB{
@Autowire
ServiceA serviceA;
@Autowire
ServiceC serviceC;
}  
                                           
First step is to remove the @Autowire annotations, so we will move the wiring responsibility out of Spring hands.
Second step is to create a class which will hold a reference to all the classes to inject. Such as:


@Component
public class BeansManager{
@Autowire
private ServiceA serviceA;
@Autowire
private ServiceB serviceB;
@Autowire
private ServiceC serviceC;
get...
set...
}          
 
Third step is to create an interface name Injectable with method inject.
public interface Injectable
{
public void inject(BeansManager beansManager);
}

Forth step is to set each service class/interface to implement the injectable interface.
e.g. :

@Service
public class ServiceA implements Injectable{
ServiceB serviceB;
ServiceC serviceC;
//method to inject all the beans which were previously were injected by Spring
public void inject(BeansManager beansManager)
{
this.serviceB =  beansManager.getServiceB();
this.serviceC = beansManager.getServiceC();
}
                 
Fifth and final step is to set the BeansManager to be ready for the injection.

                                             
But take a moment to think -
It's obvious that we need  a reference of all the classes which need to be injected in the BeansManager, however, how can we make sure that the following sequence is maintained:
1. All Service classes are initiated
2. BeansManager is initiated with all the services injected by Spring
3. After BeansManager initiated and exist in its steady state, call all the service classes which need injection and inject the relevant service.

Step 3 can be achieved by a method which executed after constructor finished (via @PostConstruct annotation), however the big question here is how to make sure the BeansManager is initiated last? (after all the relevant services are initiated)

The trick is to have @Autowire on the Injectable set.

This way Spring will make sure that:
a. All the injectable classes are subscribed to the BeansManager for the injection
b. The BeansManager will be initiated last (after all injectable services are initiated)

public class BeansManager
{
//This line will guarantee the BeansManager class will be injected last
@Autowired
private Set<Injectable> injectables = new HashSet();
//This method will make sure all the injectable classes will
//get the BeansManager in its steady state,
//where it's class members are ready to be set
@PostConstruct
private void inject() {
   for (Injectable injectableItem : injectables) {
       injectableItem.inject(this);
   }
}
}

Make sure you understand all the magic that happened in the fifth step, it's really cool.



Actual Post -  http://gal-levinsky.blogspot.in/2012/04/judgement-day-weapon-for-circular.html


                                 

Spring boot with CORS

CORS (Cross-Origin Resource Sharing) errors occur when a web application running in a browser requests a resource from a different domain or...