Tag Archives: java

Install Oracle Java 8 on Ubuntu Linux

java8_logo
To install Oracle JDK 8 on Ubuntu you can choose one of two methods:
A. Automatic installation:

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java

sudo apt-get update

sudo apt-get install oracle-java8-installer

sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws

B. Manual installation:

Download oracle jdk at http://www.oracle.com/technetwork/java/javase/downloads/index.html

Extract archive into /usr/local/jdk1.8.0_65

Setup
sudo update-alternatives --install  /usr/bin/java java /usr/local/jdk1.8.0_65/bin/java 1
sudo update-alternatives --install  /usr/bin/javac javac /usr/local/jdk1.8.0_65/bin/javac 1
sudo update-alternatives --install  /usr/bin/javaws javaws /usr/local/jdk1.8.0_65/bin/javaws 1

sudo update-alternatives --set  java /usr/local/jdk1.8.0_65/bin/java
sudo update-alternatives --set  javac /usr/local/jdk1.8.0_65/bin/javac
sudo update-alternatives --set  javaws /usr/local/jdk1.8.0_65/bin/javaws

Thanx to http://stackoverflow.com/a/31869659

Exclude beans from tests in Spring Boot

springboot
Running unit tests bootstraps, for example, scheduling tasks (EnableScheduling, Scheduled).
To exclude automatic start up auto-configuration beans with annotation you can follow next instruction:

1. Create annotation:

public @interface ExcludeFromTests {
}

2. Annotate with it Application and Scheduled beans (or what you want to be skipper during tests):

@SpringBootApplication
@EnableAsync
@EnableScheduling
@ExcludeFromTests
public class BackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(BackendApplication.class, args);
    }
}
@Component
@ExcludeFromTests
public class AppScheduler {

    @Scheduled(fixedRateString = "1000000")
    public void do() {
      //...
    }
}

3. Create TestApplication class for tests and add ComponentScan.Filter:

@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromTests.class))
public class TestBackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestBackendApplication.class, args);
    }
}

4. Say Spring boot to use TestApplication class in tests:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestBackendApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SomeTest {
  
  @Test
  public void test1() throws Exception {
    //...
  }
}

5. Profit! -)

See also:
- http://www.concretepage.com/spring/spring-component-scan-include-and-exclude-filter-example-using-javaconfig-and-xml-with-annotation-assignable-aspect-and-regex-filter-types
- http://stackoverflow.com/questions/18992880/exclude-component-from-componentscan
- http://stackoverflow.com/questions/10725192/exclude-subpackages-from-spring-autowiring
- http://stackoverflow.com/questions/25550494/componentscan-excludefilters-not-working-in-spring-4-0-6-release
- http://farenda.com/spring/spring-component-scan-exclude/

Adding manifest attributes to existing JAR file

jar
To modify manifest in external existing JAR file in JAVA do:

<build>
    <plugins>
    ...
    
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.6</version>
            <executions>
                <execution>
                    <id>repack</id>
                    <phase>package</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <target>
                            <jar update="true" 
                                 file="${project.basedir}/some.jar">
                                <manifest>
                                    <attribute name="Class-Path" 
                                               value="jackson.jar"/>
                                </manifest>
                            </jar>
                        </target>
                    </configuration>
                </execution>
            </executions>
        </plugin>    
    
    </plugins>
</build>

Thanx to http://stackoverflow.com/a/20634999

Docs:
https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html
http://www.softlab.ntua.gr/facilities/documentation/unix/java/tutorial/jar/basics/mod.html
http://introcs.cs.princeton.edu/java/85application/jar/jar.html

The bad idea is to compress JAR file with ZIP: http://stackoverflow.com/a/7085511

Using keystore in JAVA for Self-Signed SSL certificates

screenshot.2016-03-12
You may observe the next error when working with domains with self-signed certificate:

sun.security.provider.certpath.SunCertPathBuilderException: 
unable to find valid certification path to requested target

In this case you have to do next steps to allow java program trust to the given domain:

1. Get SSL certiicate for domain:

openssl s_client -connect somedomain.com:443 > cert1.cert

2. Generate java keystore:

D:\runtime\jdk8u45x64\bin\keytool -import -v -trustcacerts 
-file cert1.cert -keystore cacerts1.jks 
-alias somealias -keypass "changeit" -storepass "changeit"

Type “yes” when promts to accept certificate.

3. Add JVM arguments to your program:

-Djavax.net.ssl.trustStore="D:\projects\my\cacerts3.jks"
-Djavax.net.ssl.trustStorePassword="changeit"

4. (Optional) debug arguments:

-Djava.security.debug=certpath
-Djavax.net.debug=trustmanager

Also available java arguments (in case of self signed certificates not useful):

-Djavax.net.ssl.keyStore="D:\projects\my\cacerts3.jks"
-Djavax.net.ssl.keyStorePassword="changeit"

Thanx to:
https://www.javacodegeeks.com/2014/07/java-keystore-tutorial.html
https://docs.oracle.com/cd/E29585_01/PlatformServices.61x/security/src/csec_ssl_jsp_start_server.html
http://stackoverflow.com/a/20190493
https://github.com/denimgroup/threadfix/wiki/Importing-Self-Signed-Certificates

Get ContentType for URL in java

content-type
To determine content type for certain URL you can use next:

package org.test;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class ContentType {

    public static void main(String[] args) throws IOException {
        getContentType("http://google.com");
        getContentType("http://www.orimi.com/pdf-test.pdf");
    }

    private static void getContentType(String uri) throws IOException {
        URL url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection)  url.openConnection();
        connection.setRequestMethod("HEAD");
        connection.connect();

        System.out.println(connection.getContentType() + ": " 
          + connection.getResponseCode() + " -> " + uri);
    }
}

The result:

text/html; charset=windows-1251: 200 -> http://google.com
application/pdf: 200 -> http://www.orimi.com/pdf-test.pdf

So, as you see to get content type it is need to send small HEAD request!
Thanx to http://stackoverflow.com/a/5802223

JRebel and JBoss integration with WAR file

jreb
You may know about JRebel project. It’s very helpful for development in java world.
The following steps describe how to use JRebel for Web application:

1. Install JRebel plugin for your IDE.

2. Create file descriptor rebel.xml with JRebel plugin in your IDE in WEB-INF\classes folder like:

<?xml version="1.0" encoding="UTF-8"?>
<application 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns="http://www.zeroturnaround.com" 
  xsi:schemaLocation="http://www.zeroturnaround.com 
    http://www.zeroturnaround.com/alderaan/rebel-2_0.xsd">

 <classpath>
   <dir name="D:/project/idea/out/production/projectUI">
   </dir>
 </classpath>

 <web>
   <link target="/">
   <dir name="D:/project/src/projectUI/src/main/webapp">
   </dir>
   </link>
 </web>

</application>

3. Add the argument to JBoss AS start script:

-javaagent:C:/Users/UserName/.IntelliJIdea14/config/plugins/jr-ide-idea/lib/jrebel/jrebel.jar

Here is the path to jrebel.jar file placed after installation.

4. Deploy your application on JBoss.

5. Change some code and make (recompile) the project.

6. See the changes! Profit!

Thanx, zeroturnaround!

Convert Java stacktrace to String

stacktrace
To present java stacktrace as string use next snippet:

Exception e = new Exception("EX!");

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);

String stacktraceAsString = sw.toString();

Thanx to http://stackoverflow.com/a/1149712