Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

How to set JAVA_HOME for Java permanently on Ubuntu Linux

You can set your JAVA_HOME in /etc/profile. But the preferred location for JAVA_HOME or any system variable is /etc/environment.

Open /etc/environment in any text editor like nano or gedit and add the following line:

JAVA_HOME="/usr/lib/jvm/open-jdk"

(java path could be different)

Use source to load the variables, by running this command:

source /etc/environment

Then check the variable, by running this command:

echo $JAVA_HOME

Update

Usually most linux systems source /etc/environment by default. If your system doesn't do that add the following line to ~/.bashrc

source /etc/environment

After that, run the below command to add the java_home to the path variable. 

export PATH="$PATH:$JAVA_HOME/bin"

If you want it permanent, then add the above line to ~/.profile

Now, running $ java -version would return your version.

Where is Java Installed on Mac OS X?

Use /usr/libexec/java_home -v 1.7 command on a terminal shell to figure out where is your java 1.7 home directory

Find if a string is a integer or not in Java

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

Java FileOutputStream Create File or Parent Folders if not exists

FileUtils from apache commons is a pretty good way to achieve this in a single line.
FileOutputStream s = FileUtils.openOutputStream("/home/nikhil/somedir/file.txt")
This will create parent folders if do not exist and create a file if not exists and throw a exception if file object is a directory or cannot be written to. This is equivalent to:
File file = new File("/home/nikhil/somedir/file.txt");
file.getParentFile().mkdirs(); // Will create parent directories if not exists
file.createNewFile();
FileOutputStream s = new FileOutputStream(file,false);
All the above operations will throw an exception if the current user is not permitted to do the operation.

Schedule a job using Quartz

import org.apache.log4j.Logger;
import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;

import com.ef.monitoring.FeedUpdaterTasklet;

public class FeedBackEmailScheduler implements Job {

private static Logger logger = Logger.getLogger(FeedBackEmailScheduler.class);

private static Scheduler scheduler;

public static void start() throws Exception {

scheduler = StdSchedulerFactory.getDefaultScheduler();

JobDetail jobDetail = new JobDetail("FeedBackEmailScheduler", Scheduler.DEFAULT_GROUP,
FeedBackEmailScheduler.class);

// Run job at each day 10.30 AM and 6.30 PM
CronTrigger cTrigger = new CronTrigger("FeedBackEmailScheduler", "MCC", "0 30 10,18 1/1 * ? *");

scheduler.scheduleJob(jobDetail, cTrigger);

scheduler.start();
}

public void execute(JobExecutionContext context) {
try {
FeedUpdaterTasklet feedUpdaterTasklet = (FeedUpdaterTasklet) SpringApplicationContextProvider
.getBean("feedUpdaterTasklet", FeedUpdaterTasklet.class);
feedUpdaterTasklet.run();
} catch (Exception e) {
logger.error("Error while monitoring the products", e);
}
}

public static void shutdown() {
try {
if (scheduler != null) {
scheduler.shutdown();
}
} catch (Exception ignore) {
}
}
}

SEVERE: Exception sending context initialized event to listener instance of class + Null Pointer Exception

If at all you are trying to load the bean before, use like below. This is also useful when you try to get a bean in @weblistener  as well.


@Override
public void contextInitialized(ServletContextEvent sce) {
    WebApplicationContextUtils
        .getRequiredWebApplicationContext(sce.getServletContext())
        .getAutowireCapableBeanFactory()
        .autowireBean(this);

    //your code goes here

}


Scheduler Job using Java8, Better than TimerJob


import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.springframework.web.context.support.WebApplicationContextUtils;

@WebListener
public class BackgroundJobManager implements ServletContextListener {

private ScheduledExecutorService scheduler;

@Override
public void contextInitialized(ServletContextEvent event) {

LocalDateTime localNow = LocalDateTime.now();
ZoneId currentZone = ZoneId.of("America/New_York");

ZonedDateTime zonedNow = ZonedDateTime.now(currentZone);

ZonedDateTime zonedNext1030AM = zonedNow.withHour(11).withMinute(49).withSecond(0);
ZonedDateTime zonedNext630PM = zonedNow.withHour(11).withMinute(50).withSecond(2);

System.out.println(zonedNow);
System.out.println(zonedNext1030AM);
System.out.println(zonedNext630PM);
System.out.println(localNow);

Duration duration1030AM = Duration.between(zonedNow, zonedNext1030AM);
long initalDelay1030AM = duration1030AM.getSeconds();

Duration duration630PM = Duration.between(zonedNow, zonedNext630PM);
long initalDelay630PM = duration630PM.getSeconds();

scheduler = Executors.newScheduledThreadPool(2);

XYZ object = (XYZ) WebApplicationContextUtils
.getRequiredWebApplicationContext(event.getServletContext()).getBean("XYZ");

scheduler.scheduleAtFixedRate(object, initalDelay1030AM, 24 * 60 * 60, TimeUnit.SECONDS);
scheduler.scheduleAtFixedRate(object, initalDelay630PM, 24 * 60 * 60, TimeUnit.SECONDS);
}

@Override
public void contextDestroyed(ServletContextEvent event) {
scheduler.shutdownNow();
}


}

How to Inject bean into a java Filter

Use WebApplicationContextUtils:

public void init(FilterConfig cfg) { 
    ApplicationContext ctx = WebApplicationContextUtils
      .getRequiredWebApplicationContext(cfg.getServletContext());
    this.bean = ctx.getBean(YourBeanType.class);
}

Get single or one line exception message from exception object in Java

Response.status(BAD_REQUEST).entity(ex.getCause().getMessage()).build();

Using exceptionObject.getCause().getMessage() will give us the single or one line error message.

This is very useful when you want to show the exact one line message to the user.

Builder pattern for super and sub classes

We got a problem while generalizing the Rewards class with builder pattern. The super class, Rewards class has a builder pattern and it's sub class AnthemRewards also has a builder pattern.

Now the problem is, we want to maintain the relationship or recurring pattern with builder. The below approach works for it.

Reference: http://www.artima.com/weblogs/viewpost.jsp?thread=133275

public class Rewards {

    private final int rewardId
    private final String rewardCode;
    
    private Rewards(Builder builder) {
    this.rewardId = builder.rewardId;
    this.rewardCode = builder.rewardCode;
    }

    public static class Builder<T extends Builder> {

        private int rewardId;
        private String rewardCode;

        public static getInstance() {
            return new Builder();
        }

        public T setRewardId(int rewardId) {
            this.rewardId = rewardId;
            return (T) this;
        }
        public T setRewardCode(String rewardCode) {
            this.rewardCode = rewardCode;
            return (T) this;
        }

        public Rewards build() { return new Rewards(this); }
    }
}

public class AnthemRewards extends Rewards {

    private final String rewardType;

    public static class Builder extends Rewards.Builder<Builder> {

    private final RewardType rewardType;

public static getInstance() {
            return new Builder();
        }

        public Builder AnthemRewards(RewardType rewardType) {
            this.rewardType = rewardType
            return this;
        }

        public AnthemReward build() { return new AnthemReward(this); }
    }

    protected AnthemReward(Builder builder) {
        super(builder);
        this.rewardType = builder.rewardType;
    }

}

Using Apache Commons EqualsBuilder and HashCodeBuilder for generating HashCode and Equals effectively

This is using Reflection, a bit performance lack.
But your code looks more readable. You can always use IDE generated equals or Guava ones for a trade off.

   @Override
   public String toString() {
      return ToStringBuilder.reflectionToString(this);
   }

   @Override
   public int hashCode() {
      return HashCodeBuilder.reflectionHashCode(this, false);
   }

   @Override
   public boolean equals(Object obj) {
      return EqualsBuilder.reflectionEquals(this, obj, false);
   }

How to call getClass() from a static method in Java?

Just use TheClassName.class instead of getClass().


Non-Static

InputStream inputStream = getClass().getClassLoader()
                    .getResourceAsStream(FILE_NAME);

 Static

InputStream inputStream = ClassName.class.getClassLoader()
                    .getResourceAsStream(FILE_NAME);

Using Scriplt variable in JSTL


<%
List<UserPublicProfile> top3Users = UserUtils.getTop3Users();
    pageContext.setAttribute("top3Users", top3Users);

pageContext.setAttribute("top3Users", top3Users);   

%>

 <c:forEach items="${top3Users}" var="user"> 
                        <td align="left" valign="top" width="76px" >
                        <c:set var="photoUrl" scope="page" value="https://${user.profilePhotoUrl}"/>                       
                           <img class="top_img" src="${photoUrl}" width="73" height="79">
                        </td>
                        <td align="left" valign="top"  class="top_data">
                           <label class="top_name">${user.name}</label><br>
                        <p class="rank_font">Rank :<label class="top_rank">${user.rank}</label></p>
                        <p class="rank_font">Votes :<label class="top_rank">${user.votes}</label></p>
                        </td>
                     </c:forEach>