Menu

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

How to declare two classes for element with SCSS?

Below is an example of SCSS code using that we are generating two classes that are being use for the same html element.

SCSS code

.image-text {
@media(max-width:600px){
        &--celebrate-page .image-text {
            &__htext.image-text__htext {
                
                &--v {
                    &-center {
                        margin-top: -20%;
                    }
                }
            }
        }
    }
}


Result in CSS

@media (max-width: 600px) {
	 .image-text--celebrate-page .image-text__htext.image-text__htext--v-center {
		 margin-top: -20%;
	}
}
 

Nested if else in Bash Shell scripting

Today in this tutorial we will see how to write if else and nested if else in Bash Shell scripting.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# Program in Bash Shell

CHECK_SOURCE="[main] INFO com.dobe.jcr.checknode.existence.App - Node  exists"

echo $CHECK_SOURCE | grep -w -o -i 'Node exists'

if [ $? == 0 ]; then

    echo " Node Exists"

    echo $CHECK_SOURCE | grep -w -o -i 'checknode'

    if [ $? == 0 ]; then

        echo "checknode exist"

        echo $CHECK_SOURCE | grep -w -o -i 'adobe'

            if [ $? == 0  ]; then

                echo "Adobe exist"

            else

                echo "Adobe doesnot Exist"

            fi

    else

        echo "checknode doesnot Exist"

    fi

else

    echo "Node doesnot Exists"

fi

You may download the raw from Gist: https://gist.github.com/RashidJorvee/9e9de5c6f8fd2303d0438b492ee9ad33

Convert date-time from 12 to 24 hours of format

Today we are going to see, how we can convert a 12 hour time format into 24 hour(military) time format.
For example we have date like 12 Aug, 2018 07:05 PM or 04/03/1965 02:06:45 AM or just only have time 07:15:00 AM or 08:50:25 PM which we want to convert in 24 hours format and remove the AM and PM from the date.

Here I have written a simple program which help us to understand the process and what steps do we need to perform to convert a string time into 24 hours of time format. 
Below are the code snippet.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package jorvee;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class timeFormet {

 public static void main(String[] args) throws ParseException {
  String time="07:05:45 PM";
  /*
   * This dateFormat will help you to first convert your string time into DateTime format.
   */
  DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss aa");
  Date date24=dateFormat.parse(time);
  /*
   * Convert your time into 24 hours date format
   */
  DateFormat outFormat = new SimpleDateFormat( "HH:mm:ss");
  System.out.println(outFormat.format(date24));

 }
}

Output:

19:05:45

Pass by reference and pass by value in Java

Today in this tutorial of Java program we will see how to work with pass by value and pass by reference. 

Below is code snippet.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56

package com.rashid.jorvee;


public class ValueRef {

 public static void main(String[] args) {

  Employee emp=new Employee();

  ValueRef valref=new ValueRef();

  emp.setSalary(12000.00);

  System.out.println("Employee emp salary: " +emp.getSalary());

  valref.salary(emp);

 }

 public void salary(Employee em){

  em.setSalary(14000.00);

  em=new Employee();

  em.setSalary(15000.0);

  System.out.println("Employee em salary: " +em.getSalary());

 }

}



class Employee{

 double salary;

 public double getSalary() {

  return salary;

 }


 public void setSalary(double salary) {

  this.salary = salary;

 }
}

Output:
Employee emp salary: 12000.0
Employee em salary: 15000.0 

If else condition in shell script with $? and grep command

In shell script condition check is very easy and simple using if else statements. Here is a example which we would like to discuss with our readers.

Scenario: We have a variable that contains long string value, user wants to find matching value from given string and perform check whether that text/character has matched from string value or or not.


#Program in Bash Shell
Line 1: CHECK_SOURCE="[main] INFO com.adobe.jcr.checknode.existence - Node does not exist"
line 2: echo $CHECK_SOURCE | grep -w -o -i 'Node exists'
Line 3: if [ $? == 0 ]; then
Line 4:        echo " matched"
Line 5: else 
Line 6: echo "not matched" 
Line 7: fi 

Explanation:

In line 1 we have declared a variable CHECK_SOURCE which have some value.
In line 2 we are finding text "Node exists" in value of variable CHECK_SOURCE using grep command.
In line 3 using if statement we are checking number of matches from last executed statement. $? sign will return number of matches. If text passed in grep command will find some matching text in variable then $? will number of matching otherwise it will return zero. 



How to show related posts in blogger with thumbnail view

In this post we are going to show you people hot to show related or relevant posts in your blog (Google blogger) with thumbnail view. I tried my best to make it simple and easy so you can easily add make this changes in your blogger and show related posts to your users.

First we will see how this will appear on your blog. below is the screen shot of its appearance.

Related content thumbnail view

Now lets start to achieve this and without and delay show the relevant posts to your users so they can easily find the relevant content and also it will make your site more visible in terms of impression.

Step 1: login into Blogger account and select the TEMPLATE option from the left side of menu.

Step 2: On right panel a preview of your blog will appear showing the CUSTOMIZE and EDIT HTML option. Go with EDIT HTML option.

Step 3: A new coding snippet window will appear. Click inside the code window and then go to find option by press Ctrl+F

Step 4: Search for the text </head>.

Step 5: Copy paste the below code above the tag </head>.
<!--Show related posts in blogger START--><style type='text/css'>
#related-posts{float:left;width:auto;}
#related-posts a{border-right: 1px dotted #eaeaea;}
#related-posts h4{margin-top: 10px;background:none;font:18px Oswald;padding:3px;color:#999999; text-transform:uppercase;}
#related-posts .related_img {margin:5px;border:2px solid #f2f2f2;object-fit: cover;width:110px;height:100px;-webkit-border-radius: 5px;-moz-border-radius: 5px; border-radius: 5px; }
#related-title {color:#333;text-align:center;text-transform:capitalize;padding: 0px 5px 10px;font-size:12px;width:110px; height: 40px;}
</style>
<script type='text/javascript'>
var relatedTitles=new Array();var relatedTitlesNum=0;var relatedUrls=new Array();var thumburl=new Array();function related_results_labels_thumbs(json){for(var i=0;i<json.feed.entry.length;i++){var entry=json.feed.entry[i];relatedTitles[relatedTitlesNum]=entry.title.$t;try{thumburl[relatedTitlesNum]=entry.gform_foot.url}catch(error){s=entry.content.$t;a=s.indexOf("<img");b=s.indexOf("src=\"",a);c=s.indexOf("\"",b+5);d=s.substr(b+5,c-b-5);if((a!=-1)&&(b!=-1)&&(c!=-1)&&(d!="")){thumburl[relatedTitlesNum]=d}else thumburl[relatedTitlesNum]='http://2.bp.blogspot.com/-ex3V86fj4dQ/UrCQQa4cLsI/AAAAAAAAFdA/j2FCTmGOrog/s1600/no-thumbnail.png'}if(relatedTitles[relatedTitlesNum].length>35)relatedTitles[relatedTitlesNum]=relatedTitles[relatedTitlesNum].substring(0,35)+"...";for(var k=0;k<entry.link.length;k++){if(entry.link[k].rel=='alternate'){relatedUrls[relatedTitlesNum]=entry.link[k].href;relatedTitlesNum++}}}}function removeRelatedDuplicates_thumbs(){var tmp=new Array(0);var tmp2=new Array(0);var tmp3=new Array(0);for(var i=0;i<relatedUrls.length;i++){if(!contains_thumbs(tmp,relatedUrls[i])){tmp.length+=1;tmp[tmp.length-1]=relatedUrls[i];tmp2.length+=1;tmp3.length+=1;tmp2[tmp2.length-1]=relatedTitles[i];tmp3[tmp3.length-1]=thumburl[i]}}relatedTitles=tmp2;relatedUrls=tmp;thumburl=tmp3}function contains_thumbs(a,e){for(var j=0;j<a.length;j++)if(a[j]==e)return true;return false}function printRelatedLabels_thumbs(){for(var i=0;i<relatedUrls.length;i++){if((relatedUrls[i]==currentposturl)||(!(relatedTitles[i]))){relatedUrls.splice(i,1);relatedTitles.splice(i,1);thumburl.splice(i,1);i--}}var r=Math.floor((relatedTitles.length-1)*Math.random());var i=0;if(relatedTitles.length>0)document.write('<h4>'+relatedpoststitle+'</h4>');document.write('<div style="clear: both;"/>');while(i<relatedTitles.length&&i<20&&i<maxresults){document.write('<a style="text-decoration:none;margin:0 4px 10px 0;float:left;');if(i!=0)document.write('"');else document.write('"');document.write(' href="'+relatedUrls[r]+'"><img class="related_img" src="'+thumburl[r]+'"/><br/><div id="related-title">'+relatedTitles[r]+'</div></a>');if(r<relatedTitles.length-1){r++}else{r=0}i++}document.write('</div>');relatedUrls.splice(0,relatedUrls.length);thumburl.splice(0,thumburl.length);relatedTitles.splice(0,relatedTitles.length)}
</script>
<!--Show related posts in blogger END-->
Step 6: Again search for the text <div class='post-footer'> and add the below mentioned code before this tag.

<!--Show related posts in blogger START-->
<div id='related-posts'>
<b:loop values='data:post.labels' var='label'>
<b:if cond='data:label.isLast != &quot;true&quot;'>
</b:if>
<script expr:src='&quot;/feeds/posts/default/-/&quot; + data:label.name + &quot;?alt=json-in-script&amp;callback=related_results_labels_thumbs&amp;max-results=5&quot;' type='text/javascript'/></b:loop>
<script type='text/javascript'>
var currentposturl=&quot;<data:post.url/>&quot;;
var maxresults=5;
var relatedpoststitle=&quot;<b>Related Posts:</b>&quot;;
removeRelatedDuplicates_thumbs();
printRelatedLabels_thumbs();
</script>
</div><div class='clear'/><div style="font-size: 9px;float: right; margin: 5px;">
<a  style="font-size: 9px; text-decoration: none;" href="http://rashidjorvee.blogspot.in/2017/11/how-to-show-related-posts-in-your.html" rel="nofollow" >Grab this Widget</a></div>
<!--Show related posts in blogger END-->
Step 7: Code changes has been completed now you save your template from above SAVE TEMPLATE button.

Note: Go for your site and verify the changes and see how many related posts are appearing in your blog.
If you would like to change the number of related posts and its thumbnail view then go to step 6 and change the value for maxresults=5 to number which you wants.

If you face any issue while implementing this change in your blog, please comment your queries, we will definitely help you.

Cannot make a static reference to the non-static method

Cannot make a static reference to the non-static method display(String) from the type RunAndTest.
We cannot access or call a non static method or variable from a static method or main method(which is also a static method) of a class. Since non-static method and variables belongs to the instance of the class and we call them instance variable and method, but static method and variable are directly belongs to class which we called member variable and method.
We can access a non-static variable and method in static method only using the instance of the class. But if you want to access any non-static variable and method in non-static method of the same class then we can access them without instance of the class.


Why we can not access? 

As soon as our program loaded into memory at the same time all static variable, method and block get loaded in the memory as well, and JVM will maintain only single copy of those static thing through all over the class. And all non-static components will get loaded into the memory when we create instance of that class that why we called them instance variable/method, and when you create another instance of that class then a new and separate memory will be get allocated for all those variables and methods for that instance.

In case if you will write a code to access a non-static member in static method without instance of that class then compiler will through the error "Cannot make a static reference to the non-static method".

Below is a code sample which you could just copy and paste in your IDE and understand the concept of this static and non-static.

Compilation fail while accessing a non-static method in static method.


package coreJava;
public class RunAndTest {
public static void main(String[] args) {
display("string"); //This line of code will through compile time error "cannot make a static reference to the non-static method display(String) from the type RunAndTest"
}
void display(RunAndTest rt){
System.out.println("Test");
display("sdj");
}
void display(String string){
System.out.println("String method");
}
}

Access a non-static method in static method, with the help of object of the class.


package coreJava;public class RunAndTest { public static void main(String[] args) { RunAndTest rt=new RunAndTest(); rt.display("string"); 
} void display(RunAndTest rt){ System.out.println("Test"); display("sdj"); } void display(String string){ System.out.println("String method"); }} 

How to set property of a bean from external source file using Spring framework

Today in this tutorial we are going to discuss how to set property of a bean from external source file using Spring framework.

As we already know Spring is a very powerful framework to inject the dependency at get the value at run time in the form of beans. But what happen if we don't have value for those beans in our ApplicationContext.xml file and we need to fetch value from some external file or data source and assign those values to beans. We will see these all in a sample example program.

Files used in this example:


  1. Apple.java
  2. myApp.properties
  3. AppContextRashid.xml
  4. ClassHer.java


First we will create a java POJO calss "Apple.java" in this class we will create two String variables and their getters and setters. Also we will create a method whoareyou() with return type String.
Below is the code:
package rashidtest;
public class Apple  {
String name1, desc1="not yet set";
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getDesc1() {
return desc1;
}
public void setDesc1(String desc1) {
this.desc1 = desc1;
}
public String whoareyou() {
String result= name1 + desc1;
if(desc1 == null) return name1;
else if(name1 == null) return desc1;
else return result;
}
}

Second we will create a property file which contains the value for name1 and desc1 variables. to do so we will create a file "myApp.properties" in a xmlBeans package in our source directory which have some values. below is the example file.

def-desc=I am a fruit and my color is Red.
def-name=Apple.

Third we will create a xml bean file "AppContextRashid.xml" in which we will to include namespace "xmlns:context="http://www.springframework.org/schema/context" to read the data from external source.

To read the external property or value from file we will provide the location in property placeholder. e.g. <context:property-placeholder location="xmlBeans/myApp.properties"/> 

Then in Bean property tag we will assign values from file to POJO class variables. To get the value from properties file we will write "${name of the property}". 
e.g. <property name="desc1" value="${def-desc}"></property> 
In the above statement we are fetching value for property "def-desc" from .property file and assigning its value to "desc1" variable in Apple class.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:property-placeholder location="xmlBeans/myApp.properties"/> 
<bean id="apple" class="rashidtest.Apple">
<property name="desc1" value="${def-desc}"></property>
<property name="name1" value="${def-name}"></property>
</bean>
</beans>

Fourth and final we will create a implementer class which have main method, instance of ApplicationContext and inject the value from bean to class using setter injection. to achieve this we will create a java file "ClassHer.java". Below is the complete class.

package rashidtest;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ClassHer {
public static void main(String[] args) {
ApplicationContext appContext=new ClassPathXmlApplicationContext("rashidtest/AppContextRashid.xml");
Apple apple=appContext.getBean("apple", Apple.class);
System.out.println("Apple class have property: " +apple.whoareyou());
}
}

What is Sling and why have multiple scripts/renderers for a Component?


Apache Sling is one of the technology stack of AEM/CQ5 CMS on which AEM is built on. Sling is a Web application framework based on REST principles that provides easy development of content-oriented applications. In general terms we can say Sling is used to resolve the resources or URI in our application. Sling uses a JCR repository, such as Apache Jackrabbit or Day's CRX, as its data  store.
Sling maps HTTP request URLs to content resources based on the request's path, extension and selectors.

The Resource is one of the central parts of Sling. Extending from JCR, Everything is Content, and Sling assumes that Everything is a Resource.

Apache Sling is included in the installation of CQ5. Sling has since been contributed to the Apache Software Foundation - further information can be found at Apache Sling.
Using Apache Sling, the type of content to be rendered is not the first processing consideration. Instead the main consideration is whether the URL resolves to a content object for which a script can then be found to perform the rendering. This provides excellent support for Web content authors to build
Pages which are easily customized to their requirements.
The advantages of this flexibility are apparent in applications with a wide range of different content elements, or when you need Pages that can be easily customized/viewed differently.


How sling used to resolve a URL (Resource) in AEM? and How sling works internally?

The following diagram explains the Sling script resolution. It shows how to get from HTTP request to content node, from content node to resource type, from resource type to script and what scripting variables are available.

how sling resolve a resource in AEM. Adobe CQ, AEM sling resource resolver, how sling works.
Sling Resource resolver


The following diagram explains all the hidden, but powerful request parameters you can use when dealing with the SlingPostServlet, the default handler for all POST requests that gives you endless options for creating, modifying, deleting, copying and moving nodes in the repository.

We will now see how sling resolve a URL by using the above resolution diagram.

1. Actual URL get divided into the following chunks. e.g. we have a URL " www.rashidjorvee.blogspot.com/blog/post/aboutrashid.print.html/printable?height=400,width=200" and now we will see how sling will resolve my URL.
  • Request Method: This information comes in request header.
  • Content Path: [/blog/post/aboutrashid] 
  • Seletor: [print]
  • Extension: [html]
  • Suffix:
  • Query parameter : [height=400,width=200]
2. Sling will go to the requested content path.

3. Then it will check whether that content path or component has property sling:resourceSuperType or sling:resourceType. If request found any of these property in that node then sling request move to that path which is present in the sling:resourceType or sling:resourceSuperType.


sling:resourceType is used to render to script files.

sling:resourceSuperType is used to overload or inherit a existing component.



4. Then render to the path given in resourceType and resourceSuperType property to load the script or inherit the functionality. To resolve this first sling will find the path under apps directory, in case that content path is not available in apps then request will move under libs directory. 


5.  In this step sling will look for script name and try to match with the exact request URL with requested selector and extension. There is a set of rules which sling follow to match the selector and extension. Following are the rules:

  • Folders (i.e. nodes of type nt:folder) take precedence over jsp file names when resolving using selectors, at least for the first selector.
  • Only one selector in a file name has any effect - any files with names containing two selectors don't ever get selected, but names of folders can be used to match the selectors in the request.
  • Scripts with HTTP method names (e.g.,GET.jsp) is selected as a last resort, (after the default script: jobs.jsp, in this case).
  • Scripts with names that include HTTP methods in addition to another selector or extension in a .jsp file name are never selected.



Date and Time classes in Java

Today in this tutorial we will look how to work with date and times in Java programming.

Date and time is very important for every application and managing that date and time in your specified format, specified time zone and readable format as you want to get fetch from java program.

We are going to use some methods of LocalDate, LocalTime and LocalDateTime classes.

now() : This method return the current system date and time. If you call this now() using the LocalDate then it will give you date only not time stamp. But the same now if you call using the object of LocalTime then that will return time stamp only not date.

minusMonths() :  This method will reduce number of months from your given date. e.g. if your date is 2017-06-06 and when you will use minusMonths(2) then your date will become 2017-04-06.

plusMonths() : This method will add number of more months in your given date. e.g. if your date is 2017-04-06 and when you will use plusMonths(2) then your date will become 2017-06-06.

getDayOfWeek(): This method will return name of the day on a given time.

isBefore(): this getBefore method will return true or false by comparing the two given dates. e.g birthDate.isBefore(date.now()); here this will compare your birthdate is before current date or not. in the same way you can use the isAfter() as well.

Below is the complete example (ready to use) which you can just copy and paste  in your eclipse and execute to see how different Date methods are working in Java.


package abctest;

import java.time.LocalDateTime;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static java.time.temporal.TemporalAdjusters.*; // this import we have used to use next()import static java.time.DayOfWeek.*;
public class DateEx {
//here we have created three objects of LocalDate class. LocalDate now, bDate, today;
public static void main(String[] args) {
DateEx dateex=new DateEx();
// here we have created object local date(ld) from LocalDateTime.
LocalDateTime ld=LocalDateTime.now();
System.out.println(ld);
String locaDate=ld.format(DateTimeFormatter.ISO_DATE);
System.out.println(locaDate);
dateex.setNow(LocalDate.now());
dateex.dateMethods();
}
public void dateMethods(){
System.out.println("Date Methods:");
System.out.println("Date: " +getNow());
 //below line is to fetch the local time from your system.
System.out.println("Time: " +LocalTime.now());
//minusMonths() is to minus the number of months from a given date.
bDate=getNow().minusMonths(12);
//isBefore() method is used to compare the earlier date from two given dates.
System.out.println("Birthaday: "+bDate +" Is dbirthday before current date? "+bDate.isBefore(now));
//To get the name of the for a date.
System.out.println("He born on day: " +bDate.getDayOfWeek());
//On what date next Monday will be from a given date.
System.out.println("Next Monday will be on " +getNow().with(next(MONDAY)));
//From which era your date belongs from either BCE or AD.
System.out.println("Era: "+bDate.getEra());
}
public LocalDate getNow() {
return now;
}
public void setNow(LocalDate now) {
this.now = now;
}
}

Simple Spring project example

Create a implementation class ImplCode.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import org.springframework.context.ApplicationContext;

import org.springframework.context.support.FileSystemXmlApplicationContext;

public class ImplCode {

 public static void main(String[] args) {

  ApplicationContext appContext=new FileSystemXmlApplicationContext("AppContextBeanFile.xml");

  Fruit fruit=appContext.getBean("fruit", Fruit.class);

  Vegetable veg=(Vegetable) appContext.getBean("veg");

  System.out.println(fruit.whoareyou());

  System.out.println(veg.whoareyou());

 }

}

Create a bean class Vegetable.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package rashiddemo;

public class Vegetable {

 public String whoareyou() {

  String intro="I am vegetable!!";

  return intro;

 }

}

Create another bean class Fruit.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
package rashiddemo;

public class Fruit {

 public String whoareyou() {

  String intro="I am fruit!";

  return intro;

 }

}

Create a AppContextBeanFile.xml and add your bean classes using bean tag.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="fruit" class="rashiddemo.Fruit"></bean>

 <bean id="veg" class="rashiddemo.Vegitable"></bean>

</beans>