Create Tables From Entity Definitions From JPA Spring

How to create database tables from JPA using Hibernate

We know ORM. It will be a nightmare or a bliss based on the angle you are looking at it. This time a bliss :)

If you have started development from the java side and you have all the entities figured out, then hibernate can create the database for you from the entities.

For this example I will be assuming you are using Spring and Hibernate, with that, how do you create the database from the entities

Initial Setup assumptions

So, I will be assuming you have the spring being setup already, the configuration file for your application would look like:


jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/database
jdbc.username = root
jdbc.password = 123
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = true
hibernate.hbm2ddl.auto = create|create-drop|update|none

Here the values to hibernate.hbm2ddl.auto could be create – if you want to crate during the sessionFactory initiation, create-drop, update when you want to update the exiting database when there is a change on the schema or none if you don’t want to do anything with it.

java class not found exception

spring error ClassNotFoundException org.springframework.web.context.ContextLoaderList

ClassNotFoundException org.springframework.web.context.ContextLoaderList

When working on spring framework, you might get this error specially on eclipse. I am assuming you are working on maven and eclipse environment.

The ClassNotFound exception is a bit self explanatory that eclipse could not find the mentioned class ContextLoaderList

The web.xml file for the spring configuration might look like


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

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

With this, you might have similar file like application-context in the WEB-INF path

How to fix ClassNotFoundException for ContextLoaderList

The problem will during deployment. It is not basically compile time error. It is rather runtime error.

So, we have to make sure the jar responsible for this class is available in the classpath that eclipse is reading.

Pom dependency check

Make sure you have the same/similar configuration as the one listed below on your pom file.


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>
	
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

You can have the right version for your spring in the parameter section or you can just replace it with the current version you have.

Using Deployment Assembly fix in eclipse

As we know, it is a deployment time problem, hence we have to tell the assembly where it can get its dependencies.

      Right click on the project
      Go to/search for Deployment Assembly
      Click on Add
      Select on Java Build path entries
      Select all the maven dependencies
      Finish
      Clean and build the project

Either of the above methods should fix the problem

The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path

The superclass “javax.servlet.http.HttpServlet” was not found on the Java Build Path error in java webapp

If you are using eclipse, this might be due to project facet, right click on the project, go to project facet and select Runtimes and check the server you have configured.

if the app you are running is not spring or other web app framework that already comprised of servlet, then you need to add servlet to the build path.

You can add the servlet either through dependency management tools like gradle and maven or you can add it to the project lib file and compile it.

Also, you can add the dependency to servlet in your pom and get rid of the problem.


<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>

facebook social marketing

Add batch/multiple posts to Facebook Page – Graph API

facebook graph API batch request usage

If you have or managing any facebook page, chances are you might be using faebook’s graph API. It comes with lots of flavors of languages like Java, PHP, Javascript.

Ok you know about that, this post is not about that. If you want to see how to make a post to facebook through graph API, look at this post https://gullele.com/using-facebook-api-post-articles-php/

This post is about making multiple posts to Facebook page.

Why would I need batch requests

Imagine you have 20 blog articles you want to post to facebook. If you are not using batch, then it means you are sending 20 post requests to facebook. And as you can imaging it is easy to hit the limit easily. Facebook will stop you from bombarding their site.

When you are using batch, you have only one request, holding all 20 posts. Yup, that is it. One request vs 20. Now you know why you have to use that.

How to send multiple blog posts or other posts to Facebook page at once

If you follow the above link I referenced, you will have an idea on how single post is doing. I will just continue on that example class and will add just one more method to handle batch request.

The main idea is, each blog or whatever post has to be an object of Request. And you will send all those requests wrapped in one and send it.


	/**
	 * Send batch request to FB than a single one
	 * @param $post_data
	 */
	private function batchPost(array $post_data, $token)
	{
		/*
		 * In the case of the batch request, each has to be an object of request. And all those can be 
		 * send as one big request.
		 */
		$batch_response = [];
		$requests = [];
		foreach ($post_data as $id => $data) {
			$requests[$id] = $this->facebook->request('POST', '/me/feed', $data);
		}

		$batch_response = $this->facebook->sendBatchRequest($requests, $token);

		return $batch_response;
	}

In the above example, the method will be accepting $post_data as a parameter. If a post example is considered, a single $data will look like


$data = [
			'link' => "https://gullele.com/link-goes-here",
			'message'=>"how to make batch request in facebook api",
			'title'=>"Making Multiple Requests in Facebook",
			'description' => 'In this article I will show you how you can make multiple blog posts to Facebook page with one single request.',
		];

Then the line with $this->facebook->request will create a request object and add it as part of request array. Also mind the $id, each should have unique key in the $request array.

Then Facebook will send you back the response with post id and other lots of information that you might want to keep it for later reference like to get metrics on the post – how many likes, impressions, shares.. which will help you to improve in the long run.

Let me know if you have any questions or other methods.

Using Facebook API to post articles from PHP

How to automatically post to facebook page using PHP

This one is a bit detailed tutorial that is assumed for a novice php programmer who is new to Facebook API

Step 1.
Create a developer account from developer.facebook.com. All you need is your facebook account and you can get a developer account from it.

Step 2.
Create a Facebook page. From your Facebook page, on the top right corner, click on the dropdown menu and hit on create page. Select the type of the page you would like to create and then you have it.

Now what you want to do is, to create an auto post to the facebook page you just created from PHP. Lets say you run a blog or product page and you want to post whenever there is new stuff to be posted to the facebook page automatically.
Continue reading Using Facebook API to post articles from PHP

Check if Function Exists in Javascript

How to check if function exists in javascript

Javascript might not be happy if you call function before it is being created. This can happen in a couple of cases.

You might be wondering how to check if function exists in javascript before calling it.

Lets say you have a onLoad logic, and there could be function definition below it. In that case, if you try to call the function from the onLoad, it might complain as

Uncaught referenceError: functionName is not defined 

This happens only because the browser will be creating the function later and there is no precedence on this.

How to fix Uncaught referenceError: is not defined javascript error

In this case you can check if the function exists first and call it afterwards:


if (typeof functionName == 'function') {
    functionName();
}

This will solve the problem. But there is a catch, you need to recall it again you make sure it is loaded.

Let me know if this solves your problem or not. I can add more based on your questions or suggestions.

Redirect to home page on 404 – htaccess

How to redirect to home page on page not found 404

If you have a page that is not found, then google and others will penalize your site for not finding the page. Hence, you should handle that internally.

At least the easiest thing one can do is to redirect the site to the home page using .htaccess directives.

Homepage redirection 404

First create a .htaccess file if you don’t have one yet. Place this .htaccess file in the root of the website.

Then add the following line in the .htaccess file.


Options -MultiViews
RewriteBase /
RewriteEngine On
#if you have other redirect rules, have them here
#put this at the end of the file.
ErrorDocument 404 /

Mind you, the page you are going to redirect to should be relative path.
On the above file, those starting with # are comments and won’t be read by the server.

Hope it helps. Let me know if this helps you or if you have better method by leaving the comment down.

spring boot

Spring Data error: getOutputStream() has already been called for this response

Spring data with spring boot error when using mapping

Spring boot has made life of the java developers a bliss. Thanks a million for the dedicated guys in spring.

Saying that, if you are working typical database related project with spring boot, you might have some error like this


java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:624) ~[tomcat-embed-core-8.5.16.jar!/:8.5.16]
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:211) ~[tomcat-embed-core-8.5.16.jar!/:8.5.16]
Continue reading Spring Data error: getOutputStream() has already been called for this response

facebook social marketing

Post to Facebook From app – Using PHP

Post to Facebook programatically

You can post whatever you like from PHP to your or company’s page. Facebook has provided an SDK that makes life easier to post to the Facebook page.

This is ideal if you want to post to facebook, from cron job especially. Or on some event like right after the post in wordpress.

First thing first, you need to have a developer account on Facebook and you can do that easily and free on https://developers.facebook.com

Then you need to create an app. A single page or something like that would work. You will see how to create one when you are setting up your account for developer.

Once you have that, on the left menu, you will see dashboard. This contains important information about the app you will use to interact from your code.
Continue reading Post to Facebook From app – Using PHP