blocked cors localhost:3000 springboot issue

I tried to fetch localhost:8080 spring-boot application and I got the following error in the console.

Access to XMLHttpRequest at 'http://localhost:8080/' from origin 'http://localhost:3000' has been blocked by CORS policy:

I did the following changes in SpringSecurityConfig class file:

    
@Override
protected void configure(HttpSecurity http) throws Exception {    
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().exceptionHandling()
    .authenticationEntryPoint(restAuthEntry).and()
    .authorizeRequests((request) -> request.antMatchers("/api/v1/auth/login").permitAll()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll())
    .addFilterBefore(new JWTAuthenticationFilter(userService, jWTTokenHelper),
            UsernamePasswordAuthenticationFilter.class);
    http.csrf().disable().cors().and().headers().frameOptions().disable();
}

This solved..

wsl issue code visual studio not working windows 10 ubuntu console

I installed docker desktop and ubuntu on windows 10. I followed the following tutorial:
https://code.visualstudio.com/docs/remote/wsl-tutorial

When I was trying to run on the ubuntu console. I got the following error:

/usr/share/code/bin/../code: error while loading shared libraries: libXss.so.1: cannot open shared object file: No such file or directory

I did not install VS code through the installer due of this error was coming.
Fix for this is.

Run this command on the Ubuntu console:

alias code="/mnt/c/NON-INSTALLED-SOFTWARES/VSCode-win32-x64-1.61.0/Code.exe"

This fixed my issue.

Without changing, ownership of folder give read-write permission Linux

If you want to give read and write permission to a folder in Linux os (fedora, centos, ubuntu then use the following command:

#setfacl -R -m u:YOUR_USERNAME:rwx FOLDER_NAME

This command will be helpful for other Linux users to change files and folders.

Cakephp Invalid key for decrypt(), key must be at least 256 bits (32 bytes) long: Solved

In cakephp 3 I tried to set cookie in my controller using write cookie method. Error got invalid key for decrypt(), key must be at least 256 bits (32 bytes) long – used following line of code.

$this->Cookie->write(‘username’, ‘test’, true, ‘1 year’);

I got following error after execting page.
Invalid key for decrypt(), key must be at least 256 bits (32 bytes) long

Before using cookie write method, I loaded cookie component in appcontroller using following line.
$this->loadComponent(‘Cookie’);

I loaded conponnet in initialize method (appcontroller.php)

After searching I found following solution. I changed app.php file and added following line of code

'Security' => [
        'salt' => '123456789purab@eparinay!@#*$($(',
    ]

Above solution worked for me and it solved issue.

If you are getting this error means your Security.salt in app.php does not have the correct length.

cakephp 3 getOriginalSubject undefined index issue fixed

I am using cakephp 3.1 for development one of my portal. While configuring email Igot undefined index getOriginalSubject in DebugkitTransport.php. I searched for some time on net for solution but I did not find any solution. This function tries to get subject from email obejct. I think this is bug in cakephp 3.1.

My solution is as follows. I opened DebugkitTransport.php file and in send function I changed following line


/fixing issue of $email->getOriginalSubject undefined index
$headers['Subject'] = $email->subject();

Above line fixed my issue and I am able to send email now. I using smtp setting for sending email. I am using following code for one of my site called http://eparinay.com


$email = new Email();
$email->transport('eparinay');
try {
$email->template('eparinay')
->emailFormat('html')
->to($email)
->bcc('purabdk@yahoo.co.in')
->from(['noreply@eparinay.com' => 'eParinay.com'])
->viewVars(array('username' => $username, 'email' => $email))
->subject('eParinay.com: New registration.')
->send();
} catch (Exception $e) {

echo 'Exception : ', $e->getMessage(), "\n";
}

 

Get base url or development URL in cakephp 3 and use in view ctp file

Getting baseurl in any framework is easy. But development URL in cakephp 3 in view file…took time…For adding css or js or other purpose we need base path cakephp.

While doing development my path was http://localhost/cakephp3/. I wanted to fetch that in my site.
Their are many ways we can get the path.

You can use any one method of following :

<?php 
    echo $this->Html->url('/', true)
    echo $this->Html->url('/');
    ?>

Define constant in Config/core.php as given bellow:

define(“BASE_URL”, “localhost/cakephp3/”);

Then you can use BASE_URL in view file.

For view file you can use following code.

<?php echo $this->Url->build('/', true); ?>

I used above code reference to following URL:
http://book.cakephp.org/3.0/en/views/helpers/url.html#generating-urls

 

Avoid subquery get records with max value for each group of grouped mySQL results

How do you get the rows that contain the max value for each grouped set. I faced issue many times but I ended with following solution of subquery and two queries and using one resultset result in another query.

Here is data of Employee table. I want max salary role based..users
Employee table Data:

Name	Salary	Role
David	130,000	Software Engineer
John	140,000	DevOps Engineer
Bob	120,000	Software Engineer
Sarah	130,000	DevOps Engineer
Alice	110,000	Software Engineer
Steve	95,000	DevOps Engineer

Old query which takes too much time and memory.

SELECT *
FROM Employee a
JOIN
(
SELECT max(salary) FROM Employee c
GROUP BY c.role
) b
ON a.ID = b.ID
ORDER BY book_count DESC LIMIT 1

Finally I found this query which solved my problem. following is correct query. I used this type query with 8CR rows..It works perfectly fine..But you need understand this.. Try to explain query before using it and do proper indexing…on column which are used in left outer join….

SELECT emp1.*, emp2.ID FROM
Employee AS emp1
LEFT OUTER JOIN Employee AS emp2 ON emp2.role = emp1.role AND emp2.salary > emp1.salary
WHERE emp2.salary IS NULL;

query result:

David	130,000	Software Engineer	NULL
John	140,000	DevOps Engineer	        NULL

Please note – for this solution to work, you need to make sure you have the correct index in place. In this example, you’ll need to create an index that includes the role and salary columns in order to avoid full table scans.

 

I found following articles Useful:

https://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/


	

Solved : Channel pear is already initialized

I faced channel pear installation issue many times on many linux OS. I installed the pear package first then I removed pear package from linux box. Then when I again tried to install the pear package on box I got the following error. I solved the channel pear issue using following commands.

Solved : Channel pear is already initialized

[root@localhost purab]# pear channel-discover pear.cakephp.org
Channel “pear.cakephp.org” is already initialized
[root@localhost purab]# pear install cakephp/CakePHP
No releases available for package “pear.cakephp.org/CakePHP”
install failed

[root@localhost purab]# pear remote-list -c cakephp
File http://pear.cakephp.org:80/rest/c/categories.xml not valid (redirected but no location)

[root@localhost purab]# pear install cakephp/CakePHP
No releases available for package “pear.cakephp.org/CakePHP”
install failed

[root@localhost purab]# pear channel-discover pear.cakephp.org
Channel “pear.cakephp.org” is already initialized
[root@localhost purab]# pear upgrade pear
Nothing to upgrade

Following command is solved my issue and I am able to install pear package successfully.
[root@localhost purab]# pear clear-cache
reading directory /var/cache/php-pear
302 cache entries cleared

[root@localhost purab]# pear install cakephp/CakePHP
Unknown remote channel: pear.phpunit.de
Did not download optional dependencies: channel://pear.phpunit.de/PHPUnit, use –alldeps to download automatically
cakephp/CakePHP can optionally use package “channel://pear.phpunit.de/PHPUnit” (version >= 3.5.0)
downloading CakePHP-2.4.2.tgz …
Starting to download CakePHP-2.4.2.tgz (1,377,541 bytes)
……………done: 1,377,541 bytes
install ok: channel://pear.cakephp.org/CakePHP-2.4.2
[root@localhost purab]#

Use following command command for solve the issue.
#pear clear-cache

create self signed certificate for website and use in linux

Within in 5 minutes you can can create self signed certificate on linux machine. First you need to open console and execute following command. Before executing following command first check openssl utility is installed on your linux machine.

# openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mysitename.key -out mysitename.crt

Then open your apache configuration file and put following code in that file.

NameVirtualHost *:443

#purabtech.in

  ServerAdmin purabtech@gmail.com
  DocumentRoot /home/purab/public_html/purabtech.in/
  ServerName purabtech.in

  <Directory "/home/purab/public_html/purabtech.in/">
    Order Deny,Allow
    Allow from all
    AllowOverride All
  

  ErrorLog logs/purabtech.in-error_log
  CustomLog logs/purabtech.in-access_log combined
  RewriteLog logs/purabtech.in-rewrite_log

  SSLEngine on
  SSLCertificateFile /home/purab/projects/purabtech.in/self-sign/mysitename.crt
  SSLCertificateKeyFile /home/purab/projects/purabtech.in/self-sign/mysitename.key
  SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown
  CustomLog logs/ssl_request_log "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

Additional:
For gettting pem certificate from ssl cert.
openssl x509 -in mysitename.crt -out mysitename.pem -outform PEM

Increase Blog Traffic Using Facebook

Facebook is top social networking website in world so many people are using facebook for social marketing. Here we discussed about Increase Blog Traffic Using Facebook. Here are 10 great wordpress plugins for facebook. In earlier article I talked about SEO and wordpress and website building.

Increase Blog Traffic Using Facebook

Imagine checking your blog’s traffic stats and finding loads of referral traffic from Facebook! What a wonderful prospect that would be! What if I say that achieving this feat is very much possible. Yes, all you have to do is read this post and execute the strategies I’ve mentioned!

 

I love taking risks, calculated ones of course! Being a blogger, I know that just relying on organic traffic is a ‘huge risk’, which I can’t afford. It is like putting all the eggs in the same basket. And with Search Engines being that ‘basket’, things get a bit too risky! A single algorithm update can wreak havoc with traffic stats of a blog! This is when social sites like Facebook, with good referral traffic, comes to our aid.

If you have facebook account than create vanity facebook URL.

Panda, Penguin and Hummingbird are not adorable animals, when it comes to bloggers! These updates have managed to reduce traffic of sites and blogs by as much as 60% in many cases! That’s why many webmasters now prefer a healthy mixture of organic and referral traffic.

When one source dries up, the other one makes sure that there still is a decent flow of traffic to the blog! Here, I’ll share with you some strategies to help drive more traffic and visitors to your blog from Facebook.

Things to do on Facebook to get more traffic to blog

#1 Create a decent, engaging Facebook fan page (must have)

A facebook fan (of your blog) is like your blog’s spokesperson on facebook! It is the main source through which fans and readers get a glimpse of your blog’s latest posts, your personal updates, tips etc.

 how to generate Facebook fan code

In short, it is a vital ‘extension’ of your blog, a must have entity! Make it engaging, active and appealing. If you treat your blog like a brand, I recommend that you treat its facebook fan page similarly. Here are some tips to create/renovate it-

+ Appealing graphics

Make sure that you use the ‘logo’ of your blog on the fan page. An aspect that many bloggers overlook is the cover photo. Cover photo can be used creatively to garner attention.

Why not put some testimonials/impressive stats and figures about your blog on the cover picture? Well, it is just a suggestion from my side. In short, cover pictures can be used to market your services, build reputation, show off useful posts etc.

+ Consistency

As I said earlier, fan pages are like spokesperson. We use them to update our latest blog posts, thoughts, helpful tips etc. A tinge of consistency in doing these updates will work wonders!

Make sure that you post useful updates throughout the day at regular intervals. A static fan page won’t garner much attention, neither will it drive traffic to your blog!

+ Good Interaction with users

Okay, I agree that you are the admin, you are freaking busy and all that. But that doesn’t forbids you from engaging with your fans! Come on, reply to their queriesask them questionsask for suggestions. Take interaction to the next level!

The prime motive of interaction should be to lend a helping hand! I bet this will make your fans feel ‘closer’ to your blog. And they’ll soon become a part of your loyal reader base.

Another way to boost interaction is by hosting little contests, polls etc on the fan page.

#2 Use Images cleverly

We all know that images have a knack of grabbing our attention easily. It is how our brain works. It has a special ‘liking’ towards images and pictures.

Why not exploit this trait of human brain to our advantage? Hell yes, I guess we all should exploit this opportunity! Whenever you share your blog posts on facebook, try adding relevant, attractive images along with it.

I’ve tried it and found that the ‘reach’ of such posts increased. The reach was much more than the normal reach I would usually get. The more the reach, the more the click through rate will be!

#3 Find that perfect time to share your posts

This is a tricky affair. Timing is very important for a blog post to get noticed and clicked upon. What is the use of sharing posts at a time when no one is online to read it? So, how to find the perfect time for sharing your posts?

Big question is how to add facebook share or like button to your website.  In this article you will get instruction to add like button for your wordpress website.

There are many articles available, which discusses this topic. But let me tell you one thing. The perfect time varies from place to place. It can be found with the help of a bit of observation. Here’s how you should observe-

+ Know your audience

Yes, know who constitutes your audience base. Try to follow their pattern of using facebook. Share posts throughout the day and see when it garners most likes, shares and comments. Do this for a while and you can zero in on a ‘good time’ to share your posts.

#4 Find, Join and Make use of groups

Facebook groups are good places to start sharing your posts. Make sure that you join and share posts on groups related to your blog/site’s niche. There is no point in sharing a blog post related to gardening in a tech group!

I’m a happy member of this group! Don’t just share your own posts in groups. Take time to read others’ posts, share them and build bonds there.

#5 Making use of Hash tags

Facebook too jumped into the hash tag bandwagon. Okay, Facebook couldn’t create quite a revolution with it. But still, hash tags can bring in traffic when used cleverly.

Using hash tag to highlight keywords is a good old strategy. Further, using hash tags to take a dig at trending topics will garner much more attention and reach for your blog posts.

#6 Networking

I see facebook as the best platform for networking. I interact with fellow bloggers and influencers of my niche using facebook.

Networking has a lot to do with give and take. Make it a point to share and promote others’ content generously. You’ll be rewarded for your deeds. Further, it helps build bonds that lasts long!

And if your content manages to impress an influencer, you’re all set to go on a wild ride! If your posts get shared by them, it will ensure some spike in referral traffic. But that ultimately depends on the quality of your blog post!

Things to do off facebook to get more traffic from it

So far, we talked about what can be done on facebook to get more visitors. Now let us take a look at some of the important off site factors.

#1 Sharing Buttons (almost all of us have them)

I know, I know, you all have got those fancy set of social sharing buttons. I appreciate that. Still, I felt it is my duty to list this tip here. The ‘recommended by friends’ plugin is also handy to keep visitors engaged.

As we all know, when a visitor likes/shares a blog’s content using these buttons, it starts off a ripple. This ripple will let his friends know of our blog post, prompting him/her to visit it. Hopefully this ‘ripple’ will go on (depends on the quality of your post and the next tip).

#2 Use catchy (but non- misleading) titles

The above mentioned ripple effect works like a charm when coupled with a catchy title. But please don’t go for a misleading title though, I repeat, don’t go for misleading titles.

I’ve got something for you to ponder upon-

+ Outsourcing Facebook activities

At the beginning, I described that ‘consistency’ in promoting your content on facebook is important. I also suggested you to take ‘interaction’ on fan page to the next level!

I know that it takes time and effort. That’s why I’ve decided to put this extra piece of information, about outsourcing. Why not outsource simple tasks related to facebook activities? If you are willing to shell out some bucks, you may hire someone to take care of social media activities altogether!

What about going for a little ‘free’ outsourcing spree? Why not entrust some simple tasks like updating new posts etc to your friends, family members etc? It is just a little suggestion from my side.

+ Automating facebook activities

There are many tools that automate the process of social sharing. I’m not a fan of automating sharing and social media activities. But still, these tools come handy when you want to share posts on social sites at unworldly hours, such as late night, early morning etc.

HootSuite, Social Oomph etc are some of the many useful tools for automating these processes. But don’t depend on these tools only. Make it a point to use them only when you are time stricken.

Over to you

So, do you guys make use of facebook to its fullest? With the right techniques, one can drive huge traffic to his/her blog from facebook! I’ve been getting good traffic to my blog from facebook, so can you, using these methods. Waiting for your valuable feedback.