Sparkles

that were shone when I got tempered!

Posts Tagged ‘eclipse

Install java 8, changing the versions and set up eclipse

leave a comment »

1. Install java 8

	$ sudo add-apt-repository ppa:webupd8team/java
	$ sudo apt-get update
	$ sudo apt-get install oracle-java8-installer
	

2. Verify the java version by using the following command

	$ java -version
	

3. You can set the default version by using the below command

	sudo apt-get install oracle-java8-set-default
	

4. Changing the java version when there are multiple versions.
4.1 Check the avilable java versions

	$ sudo update-alternatives --display java

	namal@namal:~$ sudo update-alternatives --display java
	[sudo] password for namal: 
	java - auto mode
	  link currently points to /usr/lib/jvm/java-8-oracle/jre/bin/java
	/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java - priority 1071
	  slave java.1.gz: /usr/lib/jvm/java-7-openjdk-amd64/jre/man/man1/java.1.gz
	/usr/lib/jvm/java-8-oracle/jre/bin/java - priority 1072
	  slave java.1.gz: /usr/lib/jvm/java-8-oracle/man/man1/java.1.gz
	Current 'best' version is '/usr/lib/jvm/java-8-oracle/jre/bin/java'.
	

4.2 Config to use another java version

	$ sudo update-alternatives --config java

	namal@namal:~$ sudo update-alternatives --config java
	There are 2 choices for the alternative java (providing /usr/bin/java).

	  Selection    Path                                            Priority   Status
	------------------------------------------------------------
	* 0            /usr/lib/jvm/java-8-oracle/jre/bin/java          1072      auto mode
	  1            /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java   1071      manual mode
	  2            /usr/lib/jvm/java-8-oracle/jre/bin/java          1072      manual mode

	Press enter to keep the current choice[*], or type selection number: 
	

4.3 Double check the java version

	$ java -version

	namal@namal:~$ java -version
	java version "1.8.0_91"
	Java(TM) SE Runtime Environment (build 1.8.0_91-b14)
	Java HotSpot(TM) 64-Bit Server VM (build 25.91-b14, mixed mode)
	

5. Change the java version using by the IDE ( eg: eclipse)
-vm
/usr/lib/jvm/java-8-oracle/jre/bin
-vmargs
-Dosgi.requiredJavaVersion=1.8

 

References 

 

Advertisements

Written by Namal Fernando

June 16, 2016 at 6:59 am

Posted in Eclipse, Java, Linux, TroubleShooting

Tagged with , ,

Import Project from Remote Repository to the eclipse

leave a comment »

1. Go to [File] > [Import]

1

Select project from Git (type “git” in the search field if needed)

{Git} > {Project from Git} > [ Next ]

2

Click on [Clone URI] and hit [Next]

1

2. Copy the Cloned URL from remote GIT repository.

2

3. Paste it in the URI area in eclipse window. (Of course you need the authentication details)

3

It will get the branch information. Select a branch (or master), click [Next]

Configure the local storage location for the Project.

Screenshot from 2015-04-10 07:50:33

After this step it will take you to the same path that can be followed to import a project from local git repository.

Written by Namal Fernando

April 10, 2015 at 7:54 am

Posted in Eclipse, GIT

Tagged with ,

How to Add Existing local Git repositories to the eclipse view

leave a comment »

1. Open GIT perspective in eclipse
GoTo [Window] > {Open Perspective} > [Other]

1

Select [Git] > [OK]
2

This will take the Git Repositories view with the perspective to the eclipse.

2. Add Existing Git repositories
Click on the [Git and + mark] icon with the tooltip saying “Add Existing local Git repositories to this view”.
3

Browse the project converted to the Git and hit [OK]
4

In the big white textArea the .git with yellow icon will be selected (In the screen shot it is not there since the project is already added. Feel a bit lazy to create another and add ūüėČ )
5

Then it will add the project to the git repo view

6

If you can see the navigator, it will be also in there with the GIT information in square brackets.

7

If your project is not yet opened in eclipse…
Check post on How to import a GIT project from local Git repositories to the eclipse

Written by Namal Fernando

April 10, 2015 at 6:45 am

Posted in Eclipse, GIT

Tagged with ,

Linking eclipse debugging with a remote jetty application

leave a comment »

1. Start jetty with the agent.


 java -Xdebug -agentlib:jdwp=transport=dt_socket,address=9999,server=y,suspend=n -jar start.jar

This port (9999) will be the port that expose the VM to eclipse.

2. It will start like this :

It must start with something like “Listening for transport dt_socket at address: 9999” if the remote agent started successfully.


namal@namal:/rezsystem/aventura/jetty-distribution-9.2.6.v20141205$ java -Xdebug -agentlib:jdwp=transport=dt_socket,address=9999,server=y,suspend=n -jar start.jar
 Listening for transport dt_socket at address: 9999
 2015-02-07 19:14:33.756:INFO::main: Logging initialized @1139ms
 2015-02-07 19:14:33.983:WARN:oejs.HomeBaseWarning:main: This instance of Jetty is not running from a separate {jetty.base} directory, this is not recommended. See documentation at http://www.eclipse.org/jetty/documentation/current/startup.html
 2015-02-07 19:14:34.214:INFO:oejs.Server:main: jetty-9.2.6.v20141205
 2015-02-07 19:14:34.241:INFO:oejdp.ScanningAppProvider:main: Deployment monitor [file:/rezsystem/aventura/jetty-distribution-9.2.6.v20141205/webapps/] at interval 1
 2015-02-07 19:14:34.968:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@114a0de{/jsp,file:/rezsystem/aventura/jetty-distribution-9.2.6.v20141205/webapps/jsp/,AVAILABLE}{/jsp}
 2015-02-07 19:14:35.230:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@deaa44{/test-java,file:/tmp/jetty-0.0.0.0-8080-test-java.war-_test-java-any-4585236154727991456.dir/webapp/,AVAILABLE}{/test-java.war}
 2015-02-07 19:14:35.567:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@b6b7e3{/Connectors,file:/tmp/jetty-0.0.0.0-8080-Connectors.war-_Connectors-any-1112909290356820486.dir/webapp/,AVAILABLE}{/Connectors.war}
 2015-02-07 19:14:35.830:INFO:oejsh.ContextHandler:main: Started o.e.j.w.WebAppContext@55de3b{/LoginExample,file:/tmp/jetty-0.0.0.0-8080-LoginExample.war-_LoginExample-any-1704502924819382641.dir/webapp/,AVAILABLE}{/LoginExample.war}
 2015-02-07 19:14:35.880:INFO:oejs.ServerConnector:main: Started ServerConnector@db16d7{HTTP/1.1}{0.0.0.0:8080}
 2015-02-07 19:14:35.880:INFO:oejs.Server:main: Started @3263ms

3. Start Remote Debug

[Run] Debug As > [Debug Configurations…]

debug01

[Remote Java Application] > TestClassName
[Connect]

  • Project – This will be mentioned to initiate the debug points. It will not link with a particular project, but with the entire eclipse. it will ask for the particular project if the source couldn’t be located successfully.
  • Host – This may be a localhost or a remote IP
  • Port – This is the port that the VM agent was configured.

[Debug]

debug_2

4. Launch the Java application.

5. Trouble shooting and improvements.

If the eclipse can’t list the source for the remotely executing class, it will ask you to select the source. You can mention it using the Attaching the source as a Java Project or a relevant other option.

References :

Written by Namal Fernando

February 8, 2015 at 10:28 am

Posted in Eclipse, Java

Tagged with , ,

Demo REST project with Camel CXF

leave a comment »

1. Create a .war project (java 1.7 or above) using Maven as follows.

Here we are using the eclipse as the IDE and the Maven. The prefered java version is 1.7 or greater.

1-create_maven_war_prj

2. This is the folder structure of it once it is created.

2-folderStructure

3. Include the necessary dependencies to the pom.xml file as follows.

Here, we’re mainly include the Apache Camel (including camel cxf jars), Apache Common IO and SLF4j jars. Camel is using Common IO internally so it must be also used. And spring jars are also used in here. Springs are used to load the ApplicationContexts automatically.


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>demo.restapi</groupId>
<artifactId>demo.restapi</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>Rest API demo project</name>
<description>Rest API demo project</description>

<properties>
<camel-web>2.5.0</camel-web>
<camel-version>2.12.0</camel-version>
<xbean-spring-version>3.5</xbean-spring-version>
</properties>

<dependencies>

<!-- Spring + Camel jars -->

<dependency>
<groupId>org.apache.xbean</groupId>
<artifactId>xbean-spring</artifactId>
<version>${xbean-spring-version}</version>
</dependency>

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring</artifactId>
<version>${camel-version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-jms</artifactId>
<version>${camel-version}</version>
</dependency>

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-stream</artifactId>
<version>${camel-version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
<version>${camel-version}</version>
</dependency>

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf-transport</artifactId>
<version>${camel-version}</version>
</dependency>

<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>2.7.6</version>
</dependency>

<!-- Other jars (logging, io etc) -->

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>

</dependencies>

</project>

4. Add the below configurations to the WEB-INF/web.xml

Here, we are adding the applicationContext.xml as the contextConfigLocation and the listener classes. Package of the  all routers implementation classes must be mentioned in the applicationContext.xml.


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 <context-param>
 <param-name>test</param-name>
 <param-value>true</param-value>
 </context-param>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>/WEB-INF/applicationContext.xml</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
</web-app>

5. Add the below configurations to the WEB-INF/applicationContext.xml.

The package containing all the routes must be specified in the camelContext/camel:package tag. Here in our demo project, the router is mentioned in the camel.route package.


<?xml version="1.0" encoding="UTF-8"?>
<!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor
 license agreements. See the NOTICE file distributed with this work for additional
 information regarding copyright ownership. The ASF licenses this file to
 You under the Apache License, Version 2.0 (the "License"); you may not use
 this file except in compliance with the License. You may obtain a copy of
 the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required
 by applicable law or agreed to in writing, software distributed under the
 License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 OF ANY KIND, either express or implied. See the License for the specific
 language governing permissions and limitations under the License. -->

<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"
 xmlns:camel="http://camel.apache.org/schema/spring" xmlns:p="http://www.springframework.org/schema/p"
 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.xsd
 http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
 ">

<bean id="contextApplicationContextProvider" class="conf.ApplicationCtxProvider"></bean>

 <camelContext xmlns="http://camel.apache.org/schema/spring"
 id="Demo-Camel">

 <!-- All the Routes should be created within below Package -->
 <camel:package>camel.route</camel:package>

 </camelContext>

</beans>

6. Add the ApplicationContext classes

These classes are loaded during the Spring-Initialization.

a. ApplicationCtxProvider

This class which implements ApplicationContextAware, is automatically loaded during Spring-Initialization.


package conf;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class ApplicationCtxProvider implements ApplicationContextAware {

@Override
public void setApplicationContext(ApplicationContext ctx)
throws BeansException {
ApplicationCtx.setApplicationContext(ctx);
}
}

b.ApplicationCtx.

This¬†is¬†injected from the class “ApplicationCtxProvider” which is automatically loaded during Spring-Initialization. This get access to the Spring ApplicationContext from everywhere in your Application.


package conf;

import org.springframework.context.ApplicationContext;

public class ApplicationCtx {

private static ApplicationContext ctx;

// Injected from the class "ApplicationCtxProvider" which is automatically loaded during Spring-Initialization.

public static void setApplicationContext(
ApplicationContext applicationContext) {
ctx = applicationContext;
}

// Get access to the Spring ApplicationContext from everywhere in your Application.

public static ApplicationContext getApplicationContext() {
return ctx;
}
}

7. Implement the Camel router (DemoRouteBuilder).

This class is the router that takes all the REST calls to our REST service. To be run automatically, this must be included in the camel.route as it is mentioned in the aplicationContext.xml. So, it will run automatically start to run when the server is starting. Here we are mentioning the cxfrs URI that will be considered as the Endpoint URI. Here we should specify the resourceClasses to point the request to the implementation. Here,  http://localhost:9003/rest is considered as the root URI for the REST service. Rest of the path will be defined in the resource classes. Here, MappingProcessor implements the Camel Process


package camel.route;

import org.apache.camel.builder.RouteBuilder;

import camel.process.MappingProcessor;
import rs.DemoRequestServiceImpl;

public class DemoRouteBuilder extends RouteBuilder {

private static final String REST_ENDPOINT_URI = "cxfrs://http://localhost:9003/rest?resourceClasses=rs.DemoRequestServiceImpl";

@Override
public void configure() {
errorHandler(noErrorHandler());

from(REST_ENDPOINT_URI)
.routeId("RestFulService")
.process(new MappingProcessor(new DemoRequestServiceImpl()));
}

}

8. Implement the Camel Processes (MappingProcessor).

Here, MappingProcessor implements the Camel Process. It takes the REST Impl instance and uses the reflection in the process method for it’s implementation as below.


package camel.process;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.cxf.common.message.CxfConstants;
public class MappingProcessor implements Processor {

private Class<?> beanClass;
private Object instance;

public MappingProcessor(Object obj) {
beanClass = obj.getClass();
instance = obj;
}

@Override
public void process(Exchange exchange) throws Exception {
String operationName = exchange.getIn().getHeader(CxfConstants.OPERATION_NAME, String.class);
Method method = findMethod(operationName,exchange.getIn().getBody(Object[].class));
try {
Object response = method.invoke(instance, exchange.getIn().getBody(Object[].class));
exchange.getOut().setBody(response);
} catch (InvocationTargetException e) {
throw (Exception) e.getCause();
}
}

private Method findMethod(String operationName, Object[] parameters)throws SecurityException, NoSuchMethodException {
return beanClass.getMethod(operationName,getParameterTypes(parameters));
}

private Class<?>[] getParameterTypes(Object[] parameters) {
if (parameters == null) {
return new Class[0];
}
Class<?>[] answer = new Class[parameters.length];
int i = 0;
for (Object object : parameters) {
answer[i] = object.getClass();
i++;
}
return answer;
}

}

9. Creating the Rest IMPL classes.

Here, this is the main IMPL classes of the REST implementation. Here the paths are defined by using the @Path annotation. Here, the main path is defined as the /hotelservice. So, each method defined in this class must be called starting from http://localhost:9003/rest/hotelservice. Each implementation methods is defined with dedicated paths.

Here,  getAvailabilityResults(Long id) will be called as http://localhost:9003/rest/hotelservice./hotels/10. Here this methods takes the Long path parameter as 10. And it will be forwarded to the concrete implementation in DemoRequestServiceImpl.java class. Here, getAvailabilityResults is defined as a GET method and getSearhResults(String request) as a POST methos.

a. IDemoRequestService.java

package rs;

import javax.jws.WebParam;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/hotelService")
@Consumes("application/json")
@Produces(MediaType.APPLICATION_JSON)
public interface IDemoRequestService {

 @GET
 @Path("/hotels/{id}")
 @Produces(MediaType.APPLICATION_JSON)
 Response getAvailabilityResults(@PathParam("id") Long id); 

 @POST
 @Path("/search")
 @Produces(MediaType.APPLICATION_JSON)
 String getSearhResults(@WebParam(name="request") String request); 

}

b. DemoRequestServiceImpl.java

package rs;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DemoRequestServiceImpl implements IDemoRequestService {

 final Logger logger = LoggerFactory.getLogger(DemoRequestServiceImpl.class);

 @Override
 public String getSearhResults(String request) {

 logger.info("getSearhResults().request : " + request);

 return "Hello request " + request;
 }

 @Override
 public Response getAvailabilityResults(Long id){

 logger.info("getSearhResults().Long : " + id);
 return Response.ok("Hello request ID :"+id).status(Status.OK).build();
 }

}

9. Final Folder structure.

3-final-folder-structure

10. Build the project by running the pom.xml through Maven.

Here, I have used clean install package as the maven goal. I executed the maven goals within the eclipse.

11. Deploy the demo.restapi-1.0.0.war in a web container like tomcat.

Here, I used the tomcat8 to deploy the REST service. When tomcat is starting, router is deployed automatically. Then the specified requests (GET ot POST) we are sent to the END POINT URI will be taken to process by the router.

12. Test the GET method.

Here, we can test the GET method using the browser as follows

Hit http://localhost:9003/rest/hotelService/hotels/17 in the browser and get the response as “Hello request ID :17”

13. Test the POST method

– Await !!!

Written by Namal Fernando

June 29, 2014 at 5:18 pm

How to recover eclipse?

leave a comment »

Follow this if your eclipse got crashed.

  • Delete the .lock file in the workspace/.metadata folder and restart the IDE
  • If this is not working delete the .snap file in the workspace/.metadata/.plugins/org.eclipse.core.resources and restart the IDE
  • If this is also not working
    • cd .metadata/.plugins
    • mv org.eclipse.core.resources org.eclipse.core.resources.bak
    • Start eclipse. (It should show an error message or an empty workspace because no project is found.)
    • Close all open editors tabs.
    • Exit eclipse.
    • rm -rf org.eclipse.core.resources (Delete the newly created directory.)
    • mv org.eclipse.core.resources.bak/ org.eclipse.core.resources (Restore the original directory.)
    • Start eclipse and start working.

More about the .lock

Eclipse comes with a locking mechanism that is on a ‘per workspace’ basis to ensure that there is no data corruption; only one Eclipse instance can operate on a particular workspace at a time, and as such each workspace is locked while it is open for business.

So… how do you break in to Eclipse when you leave your keys on the dresser? Well, it’s actually quite simple. When a workspace is brought up by a particular instance, that Eclipse instance will produce a ‘¬†.lock¬†‘ file and store it in a special folder for that workspace. Each workspace captures unique settings in a ‘.metadata¬†‘ folder. As a side note, this is also where the unique Eclipse workspace settings are stored.

If you are on Eclipse 2.1, to get back in to Eclipse so you can do your needed work, simply delete your ‘¬†[Workspace Home]/.metadata/.lock¬†‘ file.

As of Eclipse 3.0, however, the existence of the file is no longer the relevant state. The¬†good¬†news is that reserved file locks should happen a lot less now due to the nature of the locking mechanism. The bad news is it is somewhat less apparent how to unlock the environment if something¬†does¬†go wrong. Eclipse 3.0 will attempt to use an operating system file lock on the¬†.lock¬†file (file lock on the lock file, that’s a mouthful). If, for some reason, Eclipse cannot lock this file, in 99% of the cases simply restarting your OS will clear up any file locks or file handles that may be in place. It also doesn’t hurt to delete the file, but chances are if you can delete the file, Eclipse could lock it – so this probably isn’t a plausible solution.

The remaining 1% of the cases are more than likely caused because you are fiddling with folder permissions, and Eclipse can’t write to the¬†.metadata¬†folder. Bad user!

More About .snap file

It looks like your eclipse platform is crashing quite often. Because otherwise, the snapshot files should not be there while the platform is not running. As the referenced page in roe’s comment explains, they are just needed for crash recovery and are deleted during normal shutdown of the platform. Deleting them will make eclipse think, that no crash occurred but then it can’t recover and you may have to refresh/rebuild your workspace (which may take the same time).

I’d not delete those files except eclipse won’t recover from a crash. Have a look at the eclipse workspace and platform log files if you have troubles with some plugins and fight the problem from this side (updating plugins or sending error reports) instead of deleting those files.

Written by Namal Fernando

November 6, 2013 at 4:25 pm

Posted in Eclipse

Tagged with , ,

Find/Replace in eclipse easily using regex

leave a comment »

This is a small but useful tip to use Find/Replace in eclipse easily using regex.

This example is to comment all the lines containing a word (selectedWord)

Steps : 

  • Ctrl + F
  • Find ^.*selectedWord.*$
  • Replace //$0
  • Options : Check Regular Expressions

Screenshot from 2014-06-29 08:17:52

Written by Namal Fernando

November 6, 2013 at 4:22 pm

Posted in Eclipse

Tagged with , , ,

Ruth's Reflections

Contemplations from quakey quirky Christchurch

TED Blog

The TED Blog shares interesting news about TED, TED Talks video, the TED Prize and more.

Ziplok

Learn and discover simple things

Meihta Dwiguna Saputra's Knowledge Base

~In learning you will teach and in teaching you will (re)learn~

The Java Blog

Thoughts, tips and tricks about the Java programming language

Sparkles

that were shone when I got tempered!