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

Use of DateTimeFormatter

Posted on by Kim

Use DateTimeFormatter instead of SimpleDateFormat

DateTimeFormatter.ofPattern("yyyyMMdd_HHmm").format(LocalDateTime.now()));

Validate with java & Spring

Posted on by Kim

import javax.validation.constraints.NotNull;

public class Car {

    @NotNull
    private String name;
}
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;

@Service
@Validated
public class CarService {

    public save(@Valid Car car) {
        // TODO
    }
}

@Slf4j
@RequiredArgsConstructor
@Configuration
public class SslConfig {

    private final SslSettings sslSettings;

    @PostConstruct
    void init() {
        String truststore = sslSettings.getTruststore();
        if (truststore != null) {
            log.info("Setting truststore: {}", truststore);
            System.setProperty("javax.net.ssl.trustStore", truststore);
        } else if (System.getProperty("javax.net.ssl.trustStore") != null) {
            log.info("Using provided truststore: {}", System.getProperty("javax.net.ssl.trustStore"));
        } else {
            throw new IllegalStateException("No truststore found!");
        }
    }
}

findbugs

Posted on by Kim

Used with : @SuppressFBWarnings("EQ_OTHER_NO_OBJECT")

http://findbugs.sourceforge.net/bugDescriptions.html#UUF_UNUSED_FIELD





XML to JAVA with @XmlType instead of @XmlRootElement

Posted on by Kim

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

...

private AssessResponse loadOpaResponseFromXmlFile(String file) throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(AssessResponse.class);
    InputStream is = getClass().getResourceAsStream(file);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    return unmarshaller.unmarshal(new StreamSource(is), AssessResponse.class).getValue();
}

----------------------

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AssessResponse", propOrder = {
    "versionInfo",
    "events",
    "globalInstance"})
public class AssessResponse
    implements Serializable
{

...

----------------------
<assess-response xmlns="http://oracle.com/determinations/server/12.2.1/rulebase/assess/types">
    <global-instance>
        <entity id="month" inferred="false">
            <instance id="xxx">

...

Parse JSON with Java

Posted on by Kim

Using cxf to parse JSON

ChangeService changeService = JAXRSClientFactory.create(propertiesInterface.getServerUrl(),
        ChangeService.class, Collections.singletonList(new JacksonJaxbJsonProvider()),
        propertiesInterface.getUserName(), propertiesInterface.getPassword(), null);
Where ChangeService is
@Path("/change_request")
@Produces(MediaType.APPLICATION_JSON)
public interface ChangeService {

    @GET    public Changes getChangesByAssignedTo(
            @QueryParam("sysparm_query") String userSysId);
And maven dependency

    org.apache.cxf
    cxf-rt-rs-client
    ${cxf.version}
    provided


    org.codehaus.jackson
    jackson-jaxrs
    ${jackson.version}
    provided


    org.codehaus.jackson
    jackson-xc
    ${jackson.version}
    test

Split a URL into protocol, domain, port and uri using regular expressions

Posted on by Kim

// Split URL into protocol, domain, port and URI
Pattern pattern = ~/(https?:\/\/)([^:^\/]*)(:\d*)?(.*)?/
Matcher matcher = pattern.matcher url
matcher.find()

String protocol = matcher.group 1
String domain = matcher.group 2
String port = matcher.group 3
String uri = matcher.group 4

Encode url (Change spaces etc.)

Posted on by Kim

URL url = new URL(urlStr)
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef())
url = uri.toURL()

Quartz

Posted on by Kim

Example of creating multiple triggers for the same job. Plus example of job that just to run once

Maven Dependency

 <dependency>
  <groupId>org.quartz-scheduler</groupId>
  <artifactId>quartz</artifactId>
  <version>2.2.2</version>
 </dependency>

The Alarm job


package as.moes.job;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

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

public class AlarmJob implements Job {

    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        if (null != jobExecutionContext.getNextFireTime())
            System.out.println("Trigger key..:" + jobExecutionContext.getTrigger().getKey().getName() + " "
                    + sdf.format(new Date()) + " "
                    + sdf.format(jobExecutionContext.getNextFireTime()) + " "
            );
        else
            System.out.println("Trigger key..:" + jobExecutionContext.getTrigger().getKey().getName() + " "
                    + sdf.format(new Date()) + " "
                    + "null "
            );

    }
}

The setup


    public static void setupAlarmJob(Date date, String identity, String... cronScheduleArray) throws SchedulerException {
        JobDetail job = JobBuilder.newJob(AlarmJob.class)
                .withIdentity(identity, identity)
                .build();

        Set triggerList = new HashSet();
        if (null != date)
            triggerList.add(
            TriggerBuilder
                    .newTrigger()
                    .startAt(date)
                    .build()
            );


        for (String cronSchedule : cronScheduleArray) {
            triggerList.add(setupAlarmTrigger(cronSchedule));
        }

        Map> map = new HashMap>();
        map.put(job, triggerList);

        scheduler = new StdSchedulerFactory().getScheduler();
        scheduler.start();
        scheduler.scheduleJobs(map, true);
    }

    public static void setupAlarmJob(String identity, String... cronScheduleArray) throws SchedulerException {
        setupAlarmJob(null, identity, cronScheduleArray);
    }

    public static Trigger setupAlarmTrigger(String cronSchedule) throws SchedulerException {
        return TriggerBuilder
                .newTrigger()
                .withIdentity(cronSchedule)
                .withSchedule(CronScheduleBuilder.cronSchedule(cronSchedule))
                .build();
    }

Sample Gradle, Groovy Project on IntelliJ

Posted on by Kim

Change the build.gradle Add mavenLocal and right plugins...

See: The Groovy Plugin

group 'as.moes.gradletest'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'idea'
apply plugin: 'jetty'
apply plugin: 'war'

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    compile 'org.codehaus.groovy:groovy-all:2.3.11'

    testCompile group: 'junit', name: 'junit', version: '4.11'
}

Groovy Spock test form Java Maven project

Posted on by Kim

Setup in maven


    
        junit
        junit
        4.12
        test
    
    
        org.spockframework
        spock-core
        1.0-groovy-2.4
        test
    
    
        org.codehaus.groovy
        groovy-all
        2.4.4
        test
    
    
        com.athaydes
        spock-reports
        1.2.7
        test
    



    org.apache.maven.plugins
    maven-compiler-plugin
    
        UTF-8
        1.8
        ${jdk.target.version}
    


    org.codehaus.gmavenplus
    gmavenplus-plugin
    1.5
    
        
            
                addTestSources
                testCompile
            
        
    


    org.apache.maven.plugins
    maven-surefire-plugin
    2.18.1
    
        
            **/*Test.java
            **/*Spec.java
        
    

See : Writing Unit Tests With Spock Framework: Creating a Maven Project Thanks to Petri Kainulainen

Reads an InputStream and converts it to a String

Posted on by Kim

    private String readIt(InputStream stream) throws IOException {
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        for(String line = reader.readLine(); line != null; line = reader.readLine()) 
            builder.append(line);
        reader.close();
        return builder.toString();
    }

Tika Autodetect Parser

Posted on by Kim

final InputStream is = new ByteArrayInputStream(binary);
Metadata md = new MetaData();
// Need to add filename to metadata, since office docs header elements are ambiguous and Tika determines the exact minetype by looking at the file extension
md.add(Metadata.RESOURCE_NAME_KEY, filename);
String mimetype = new DefaultDetector(MimeTypes.getDefaultMimeTypes()).detect(is, md).toString();

Simple fix to missing tools.jar in JDK on Mac OS X

Posted on by Kim

THANKS to David B. Knickerbocker for this

Simple fix to missing tools.jar in JDK on Mac OS X

Today I ran into a situation where a 3rd-party pom.xml had a dependency on tools.jar.  I'm stuck using Java 6, due to project requirements, which means I have to use the Apple supplied JDK.  The problem is Apple bundled all the classes normally found in tools.tar into classes.jar.  Since I couldn't modify the pom file, I simply creating a symbolic link to classes.jar.

 $> sudo ln -s /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/tools.jar  
 $> sudo ln -s /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/lib  

Unicode

Posted on by Kim

To write country-specific letters:

public static void main(String[] args) {
    System.out.println("æ...:" + Integer.toString('æ', 16));
    System.out.println("ø...:" + Integer.toString('ø', 16));
    System.out.println("å...:" + Integer.toString('å', 16));
    System.out.println("Æ...:" + Integer.toString('Æ', 16));
    System.out.println("Ø...:" + Integer.toString('Ø', 16));
    System.out.println("Å...:" + Integer.toString('Å', 16));

    System.out.println("ä...:" + Integer.toString('ä', 16));
    System.out.println("Ä...:" + Integer.toString('Ä', 16));
    System.out.println("ö...:" + Integer.toString('ö', 16));
    System.out.println("Ö...:" + Integer.toString('Ö', 16));

    System.out.println("\u00e6" == "æ");
}

JRebel

Posted on by Kim

How to setup JRebel i 2 min.
  • unzip
  • in bin run .sh
  • change /usr/.jrebel/jrebel.properties
    • rebel.license.url=http://.....
    • rebel.log.file=/usr/kim/.jrebel/jrebel.log
  • In server-setup add -javaagent:/java/jrebel/jrebel.jar
  • Add file rebel.xml in classpath. See jrebel/doc/rebel.xml.html for help




TCP/IP Monitor

Posted on by Kim

For testing call in Eclipse I use TCP/IP Monitor

Enum

Posted on by Kim

    public enum Sex {
        MALE("M", "Male"), FIMALE("F", "Fimale"), UNISEX("U", "Unisex");

        private final String sex;
        private final String name; // in meters

        Sex(String sex, String name) {
            this.sex = sex;
            this.name = name;
        }

        public String getSex() {
            return sex;
        }

        public String getName() {
            return this.name;
        }
    }

Method to preetyPrint Document in java

Posted on by Kim

public static void write(org.dom4j.Document document) {
        try {
            // Pretty print the document to System.out
            org.dom4j.io.OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
            org.dom4j.io.XMLWriter writer = new org.dom4j.io.XMLWriter(new FileWriter("C:\\output.xml"), format);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Nice framework for testing (equals) xml: XmlUnit

Easy sort a list of SelectItem's

Posted on by Kim

Easy way to sort a Collection for e.g. dropdown.

Collections.sort(<Collection of SecletItem's>, new SecletItemComparator());

// Inner class
public class SecletItemComparator implements Comparator {
@Override
public int compare(SelectItem s1, SelectItem s2) {
return s1.getLabel().compareTo(s2.getLabel());
}
}