25.02.2015 Views

Introducing Spring Framework

Introducing Spring Framework

Introducing Spring Framework

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 13 ■ Adding E-mail and Scheduling Tasks<br />

Listing 13-10. DocumentScheduler.java<br />

package com.apress.isf.spring.scheduler;<br />

import java.io.IOException;<br />

import java.net.HttpURLConnection;<br />

import java.net.URL;<br />

import java.util.List;<br />

import org.slf4j.Logger;<br />

import org.slf4j.LoggerFactory;<br />

import org.springframework.beans.factory.annotation.Autowired;<br />

import org.springframework.scheduling.annotation.Scheduled;<br />

import org.springframework.stereotype.Component;<br />

import com.apress.isf.java.model.Document;<br />

import com.apress.isf.java.model.Type;<br />

import com.apress.isf.java.service.DocumentService;<br />

@Component<br />

public class DocumentScheduler {<br />

private static Logger log = LoggerFactory.getLogger(DocumentScheduler.class);<br />

private static int HTTP_NOT_FOUND_CODE = 404;<br />

private static int HTTP_OK_CODE = 200;<br />

}<br />

@Autowired<br />

DocumentService documentService;<br />

private Type webType = new Type("WEB",".url");<br />

@Scheduled(cron="*/10 * * * * ?")<br />

public void urlCheck() throws IOException{<br />

log.debug("@@ Checking valid WEB type Document's URL...");<br />

URL url = null;<br />

HttpURLConnection connection = null;<br />

int responseCode = 0;<br />

List documents = documentService.findByType(webType);<br />

for(Document document : documents){<br />

url = new URL(document.getLocation());<br />

connection = (HttpURLConnection)url.openConnection();<br />

connection.setRequestMethod("GET");<br />

connection.connect();<br />

responseCode = connection.getResponseCode();<br />

log.debug("Name lookup: " + document.getName());<br />

log.debug("Code: " + Integer.toString(responseCode));<br />

if(HTTP_OK_CODE == responseCode)<br />

log.info("URL is still valid!!");<br />

else<br />

log.error("URL INVALID! Code: " + HTTP_NOT_FOUND_CODE + ". Please let<br />

the Administrator know");<br />

}<br />

}<br />

191

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!