Apache Utilities At Work V5

2,288 views

Published on

You're on another typical JavaEE-based project, and you find yourself writing the same old infrastructure code. Are you wondering if there's a quicker way to incorporate the basics such as configuration, logging, and email into your application? If so, then this presentation is for you. By using a number of Apache utilities from
Commons, Logging, and other areas, you can learn how to stop re-inventing the wheel.

We'll start with a simple Struts 2 application and iteratively add the ability to:
• Use Commons Lang for String and Date utilities.
• Use Commons Property Configuration to setup and use application Properties.
• Use Commons Logging and Log4J to log messages.
• Generate Excel spreadsheets with POI.
• Use Velocity Templates and Commons Email to format and send email messages.
• Use HttpClient to invoke web apps with HTTP/S.
• Use Commons IOUtils to simplify accessing web content.

Published in: Technology
0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,288
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
69
Comments
0
Likes
4
Embeds 0
No embeds

No notes for slide

Apache Utilities At Work V5

  1. 1. Apache Utilities at Work Tom Marrs
  2. 2. Who am I? <ul><li>Background </li></ul><ul><ul><li>Co-author of JBoss At Work: A Practical Guide (O’Reilly, November 2005) </li></ul></ul><ul><ul><ul><li>Currently working on 2 nd ed. </li></ul></ul></ul><ul><ul><li>User Groups </li></ul></ul><ul><ul><ul><li>Founding President of DOSUG </li></ul></ul></ul><ul><ul><ul><li>Past President of DJUG </li></ul></ul></ul><ul><ul><li>Related Experience </li></ul></ul><ul><ul><ul><li>I’ve been on several bad projects </li></ul></ul></ul><ul><ul><ul><li>I hate re-inventing the wheel </li></ul></ul></ul>
  3. 3. Learning Objectives <ul><li>As a result of this presentation you will learn: </li></ul><ul><ul><li>To research Open Source utilities before coding </li></ul></ul><ul><ul><li>To avoid re-inventing the wheel </li></ul></ul><ul><ul><li>What common utilities are available on Apache </li></ul></ul><ul><ul><li>How to use Apache utilities on your project </li></ul></ul><ul><ul><li>How to hide the details </li></ul></ul>
  4. 4. Prerequisites <ul><li>Core Java SE </li></ul><ul><li>The right mindset </li></ul><ul><ul><li>Leverage existing utilities </li></ul></ul>
  5. 5. Session Non-Agenda <ul><li>In this Session, we will not discuss: </li></ul><ul><li>JavaEE </li></ul><ul><li>A full-blown application </li></ul><ul><li>Other cool Apache projects: </li></ul><ul><ul><li>Web Services (Axis 2) </li></ul></ul><ul><ul><li>CXF </li></ul></ul><ul><ul><li>XMLBeans </li></ul></ul><ul><ul><li>Geronimo </li></ul></ul><ul><ul><li>ServiceMix </li></ul></ul><ul><ul><li>ActiveMQ </li></ul></ul><ul><ul><li>Camel </li></ul></ul><ul><ul><li>Struts </li></ul></ul><ul><ul><li>Beehive </li></ul></ul>
  6. 6. Session Agenda <ul><li>In this Session we will discuss: </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  7. 7. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  8. 8. Like Nails on a Blackboard … <ul><li>if (myString == null || myString.length() == 0) { // Ugh!! </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>// OR only slightly better. </li></ul><ul><li>public class MyUtils { </li></ul><ul><li>… </li></ul><ul><li>public static boolean isNullOrEmpty(String stringToCheck) { </li></ul><ul><li>boolean retValue = false; </li></ul><ul><li>if (stringToCheck == null) { </li></ul><ul><li>retValue = true; </li></ul><ul><li>} else if (stringToCheck.length() == 0) { </li></ul><ul><li>retValue = true; </li></ul><ul><li>} </li></ul><ul><li>return retVal; </li></ul><ul><li>} </li></ul>
  9. 9. Commons Lang Overview <ul><li>Enhanced methods and classes for core Java SE ( java.lang ) </li></ul><ul><ul><li>http:// commons.apache.org/lang </li></ul></ul><ul><li>Includes String, numerical, date/time methods </li></ul><ul><li>Useful: StopWatch (simple timing test) </li></ul><ul><li>My favorite – StringUtils: </li></ul><ul><ul><li>isBlank() </li></ul></ul><ul><ul><li>isEmpty() </li></ul></ul><ul><ul><li>isNotBlank() </li></ul></ul><ul><ul><li>isNotEmpty() </li></ul></ul>
  10. 10. With StringUtils <ul><li>// Usage </li></ul><ul><li>if (StringUtils.isEmpty(myString)) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>if (StringUtils.isBlank(myString)) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul>
  11. 11. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  12. 12. Getting Properties – What we want <ul><li>String emailTo = MyPropertyUtil.getProperty(EMAIL_TO); </li></ul>
  13. 13. Rolling Your Own Properties <ul><li>public class MyPropertyUtil { </li></ul><ul><li>private static final String MY_PROPS_FILE_NAME = “…”; // Use –D to set this at startup. </li></ul><ul><li> … </li></ul><ul><li>public static String getProperty(String key) throws MyPropertyUtilException { </li></ul><ul><li>Properties props = null; </li></ul><ul><li>String value = “”, </li></ul><ul><li>propsFileName = System.getProperty(MY_PROPS_FILE_NAME); </li></ul><ul><li>if (StringUtils.isNotBlank(key) && </li></ul><ul><li>StringUtils.isNotBlank(propsFileName) { </li></ul><ul><li>try { </li></ul><ul><li>// FIXMEE: Move Props File Name & Properties Load to static initializer. </li></ul><ul><li> </li></ul><ul><li> // The Thread Context ClassLoader is the ClassLoader used by the creator </li></ul><ul><li> // of the Thread that runs your code. By using the Thread Context ClassLoader, </li></ul><ul><li> // we’re guaranteed to load the resource (class or property file) as long as </li></ul><ul><li> // it's on the application's CLASSPATH. </li></ul><ul><li>ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader(); </li></ul><ul><li>URL myUrl = myClassLoader.getResource(name); </li></ul><ul><li>props.load(url.openStream()); </li></ul><ul><li>value = props.getProperty(key); </li></ul><ul><li>} catch (Throwable th) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>return value; </li></ul><ul><li>} </li></ul>
  14. 14. Commons Configuration Overview <ul><li>A clean way to configure your application </li></ul><ul><ul><li>http:// commons.apache.org /configuration </li></ul></ul><ul><li>It loads the configuration data for you </li></ul><ul><li>Configuration/Factory (main class) can work with: </li></ul><ul><ul><li>Properties files </li></ul></ul><ul><ul><li>XML files </li></ul></ul><ul><ul><li>JNDI </li></ul></ul><ul><ul><li>JDBC DataSource </li></ul></ul><ul><ul><li>System Properties (JVM) </li></ul></ul><ul><ul><li>.INI files (Windows) </li></ul></ul>
  15. 15. Commons Configuration Overview … Cont’d <ul><li>It can handle hierarchical data </li></ul><ul><li>It can combine multiple data sources (composite): </li></ul><ul><li>CompositeConfiguration config = new CompositeConfiguration(); config.addConfiguration(new SystemConfiguration()); config.addConfiguration(new </li></ul><ul><li>PropertiesConfiguration(&quot;application.properties&quot;)); </li></ul>
  16. 16. Properties with Commons Configuration <ul><li>public class MyPropertyUtil { </li></ul><ul><li>private static final String MY_PROPS_FILE_NAME = “…”; // Use –D to set this at startup. </li></ul><ul><li> … </li></ul><ul><li>public static String getProperty(String key) throws MyPropertyUtilException { </li></ul><ul><li>Properties props = null; </li></ul><ul><li>String value = “”, </li></ul><ul><li>propsFileName = System.getProperty(MY_PROPS_FILE_NAME); </li></ul><ul><li>if (StringUtils.isNotBlank(key) && </li></ul><ul><li>StringUtils.isNotBlank(propsFileName) { </li></ul><ul><li>try { </li></ul><ul><li>// FIXMEE: Move Props File Name & Constructor call to static initializer. </li></ul><ul><li>Configuration config = new PropertiesConfiguration(propsFileName); </li></ul><ul><li>value = props.getString(key); </li></ul><ul><li>} catch (Throwable th) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>return value; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  17. 17. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  18. 18. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  19. 19. POI Overview <ul><li>API to access MS file formats </li></ul><ul><ul><li>Word </li></ul></ul><ul><ul><li>PowerPoint </li></ul></ul><ul><ul><li>Outlook </li></ul></ul><ul><ul><li>Visio </li></ul></ul><ul><ul><li>Publisher </li></ul></ul><ul><ul><li>Excel (HSSF) </li></ul></ul><ul><ul><li>http:// poi.apache.org </li></ul></ul>
  20. 20. Generate an Excel File with POI <ul><li>private static void populateExcelWorksheet(Collection rows, FileOutputStream fileOut) { </li></ul><ul><li>try { </li></ul><ul><li>if (rows.size() > 0) { </li></ul><ul><li>HSSFWorkbook workBook = new HSSFWorkbook(); </li></ul><ul><li>HSSFSheet workSheet = workBook.createSheet(); //Create new workSheet </li></ul><ul><li>Iterator rowDataIterator = rows.iterator(); </li></ul><ul><li>int rowNum = 0, </li></ul><ul><li>maxColumnSize = 0; </li></ul><ul><li>while (rowDataIterator.hasNext()) { </li></ul><ul><li>LinkedList rowStringsList = (LinkedList) rowDataIterator.next(); </li></ul><ul><li>if (rowStringsList.size() > 0) { </li></ul><ul><li>HSSFRow row = workSheet.createRow(rowNum); </li></ul><ul><li>// Create header ONLY once </li></ul><ul><li>if (rowNum == 0) { </li></ul><ul><li>maxColumnSize = ExcelUtil.createColumnHeaders(rowStringsList, workBook, row); </li></ul><ul><li>} else { </li></ul><ul><li>maxColumnSize = ExcelUtil.fillRowCellValue(rowStringsList, workBook, row); </li></ul><ul><li>} </li></ul><ul><li>rowNum++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  21. 21. Generate an Excel File with POI … Cont’d <ul><li>workBook.write(fileOut); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>catch (IOException e) { </li></ul><ul><li>... </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  22. 22. Generate an Excel File with POI … Cont’d <ul><li>private static short createColumnHeaders(LinkedList stringList, HSSFWorkbook workBook, HSSFRow row) { </li></ul><ul><li>short columnNum = 0; </li></ul><ul><li>Iterator iter = stringList.iterator(); </li></ul><ul><li>while (iter.hasNext()) { </li></ul><ul><li>String value = (String) iter.next(); </li></ul><ul><li>// Create a new font and alter it. </li></ul><ul><li>HSSFFont font = workBook.createFont(); </li></ul><ul><li>//Customize font </li></ul><ul><li>customizeExcelFont(font); </li></ul><ul><li>// Fonts are set into a style so create a new one to use. </li></ul><ul><li>HSSFCellStyle style = workBook.createCellStyle(); </li></ul><ul><li>style.setFont(font); </li></ul><ul><li>HSSFCell cell = null; </li></ul><ul><li>cell = row.createCell(columnNum); </li></ul><ul><li>cell.setCellStyle(style); </li></ul><ul><li>cell.setCellValue(value); </li></ul><ul><li>columnNum++; </li></ul><ul><li>} </li></ul><ul><li>return columnNum; </li></ul><ul><li>} </li></ul>
  23. 23. Generate an Excel File with POI … Cont’d <ul><li>private static short fillRowCellValue(LinkedList stringList, HSSFWorkbook workBook, HSSFRow row) { </li></ul><ul><li>short columnNum = 0; </li></ul><ul><li>Iterator iter = stringList.iterator(); </li></ul><ul><li>while (iter.hasNext()) { </li></ul><ul><li>String value = (String) iter.next(); </li></ul><ul><li>HSSFCellStyle style = workBook.createCellStyle(); </li></ul><ul><li>HSSFCell cell = null; </li></ul><ul><li>// Set background color with light &quot;foreground&quot; </li></ul><ul><li>// foreground being the filled, not the font color. </li></ul><ul><li>style.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index); </li></ul><ul><li>style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); </li></ul><ul><li>cell = row.createCell(columnNum); </li></ul><ul><li>cell.setCellStyle(style); </li></ul><ul><li>cell.setCellValue(value); </li></ul><ul><li>columnNum++; </li></ul><ul><li>} </li></ul><ul><li>return columnNum; </li></ul><ul><li>} </li></ul>
  24. 24. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  25. 25. Commons Email Overview <ul><li>Simple API for sending email </li></ul><ul><ul><li>http:// commons.apache.org /email </li></ul></ul><ul><li>Based on JavaMail API (but easier to use) </li></ul><ul><li>Key Areas: </li></ul><ul><ul><li>Text </li></ul></ul><ul><ul><li>HTML </li></ul></ul><ul><ul><li>Attachments </li></ul></ul>
  26. 26. Using JavaMail <ul><li>public void send(MyEmailParams emailParams) throws EmailException { // Send Text </li></ul><ul><li>try { </li></ul><ul><li>Session session = getDefaultSession(); </li></ul><ul><li>InternetAddress[] recipientsArr = (InternetAddress[]) </li></ul><ul><li>emailParams.getRecipients().toArray(new InternetAddress[0]); </li></ul><ul><li>MimeMessage msg = new MimeMessage(session); </li></ul><ul><li>msg.setFrom(emailParams.getSender()); </li></ul><ul><li>msg.setRecipients(Message.RecipientType.TO, recipientsArr); </li></ul><ul><li>if (!emailParams.getCcRecipients.isEmpty(){ </li></ul><ul><li>InternetAddress[] ccRecipientsArr = (InternetAddress[]) </li></ul><ul><li>emailParams.getCcRecipients().toArray(newInternetAddress[0]); </li></ul><ul><li>msg.setRecipients(Message.RecipientType.CC, ccRecipientsArr); </li></ul><ul><li>} </li></ul>
  27. 27. Using JavaMail … Cont’d <ul><li>msg.setSubject(emailParams.getSubject()); </li></ul><ul><li>msg.setText(emailParams.getBody()); </li></ul><ul><li>Transport.send(msg); // Send message </li></ul><ul><li>} catch (MessagingException me) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>private Session getDefaultSession() throws EmailException { </li></ul><ul><li>Properties props = new Properties(); </li></ul><ul><li>String mailSmtpHost = MyPropertyUtil.getProperty(MAIL_SMTP_HOST), </li></ul><ul><li>mailSmtpPort = MyPropertyUtil.getProperty(MAIL_SMTP_PORT), </li></ul><ul><li>mailDebug = MyPropertyUtil.getProperty(MAIL_DEBUG, FALSE); </li></ul><ul><li>props.setProperty(MAIL_TRANSPORT_PROTOCOL, SMTP); </li></ul><ul><li>props.setProperty(MAIL_SMTP_HOST, mailSmtpPort); </li></ul><ul><li>props.setProperty(MAIL_SMTP_HOST, mailSmtpHost); </li></ul><ul><li>props.setProperty(MAIL_DEBUG, mailDebug); </li></ul><ul><li>Session session = Session.getDefaultInstance(props); </li></ul><ul><li>return session; </li></ul><ul><li>} </li></ul>
  28. 28. Using Commons Email <ul><li>public static void sendSimpleEmail(EmailParams emailParams) </li></ul><ul><li> throws MyEmailUtilException { // Send text. </li></ul><ul><li>try { </li></ul><ul><li>SimpleEmail email = new SimpleEmail(); </li></ul><ul><li>String hostName = MyPropertyUtil.getProperty(MY_SMTP_SERVER); </li></ul><ul><li>Iterator toAddrIter = emailParams.getToRecipients().iterator(), </li></ul><ul><li>ccAddrIter = emailParams.getCcRecipients().iterator(); </li></ul><ul><li>email.setHostName(hostName); </li></ul><ul><li>email.setFrom(emailParams.getFromEmailAddr(), emailParams.getFromName()); </li></ul><ul><li>while (toAddrIter.hasNext()) { </li></ul><ul><li>email.addTo((String) toAddrIter.next()); </li></ul><ul><li>} </li></ul><ul><li>while (ccAddrIter.hasNext()) { </li></ul><ul><li>email.addCc((String) ccAddrIter.next()); </li></ul><ul><li>} </li></ul><ul><li>email.setSubject(emailParams.getSubject()); </li></ul><ul><li>email.setMsg(emailParams.getMessage()); </li></ul><ul><li>email.send(); </li></ul><ul><li>} catch (EmailException e) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  29. 29. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  30. 30. Velocity Overview <ul><li>Templating Engine </li></ul><ul><ul><li>http://velocity.apache.org </li></ul></ul><ul><li>Other good tools exist: </li></ul><ul><ul><li>FreeMarker – http://freemarker.sourceforge.net/ </li></ul></ul>
  31. 31. Using the Velocity API <ul><li>VelocityEngine velocityEngine = new VelocityEngine(); </li></ul><ul><li>Properties props = new Properties(); </li></ul><ul><li>Template template = null; </li></ul><ul><li>VelocityContext velocityContext = new VelocityContext(); </li></ul><ul><li>props.setProperty(VelocityEngine.RESOURCE_LOADER, &quot;classpath&quot;); </li></ul><ul><li>props.setProperty(&quot;classpath.&quot; + VelocityEngine.RESOURCE_LOADER + </li></ul><ul><li>&quot;.class&quot;, ClasspathResourceLoader.class.getName()); </li></ul><ul><li>velocityEngine.init(props); </li></ul><ul><li>try { </li></ul><ul><li>StringWriter writer = new StringWriter(); </li></ul><ul><li>template = velocityEngine.getTemplate(MY_TEMPLATE); </li></ul><ul><li>velocityContext.put(RECIPIENT_NAME, recipientName); </li></ul><ul><li>velocityContext.put(POLICY_NUMBER, policyNumber); </li></ul><ul><li>velocityContext.put(REFUND_AMOUNT, refundAmount); </li></ul><ul><li>template.merge(velocityContext, writer); </li></ul><ul><li>} catch (…) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul>
  32. 32. Velocity Template <ul><li><HTML> </li></ul><ul><li><BODY> </li></ul><ul><li><p> </li></ul><ul><li>Dear $recipientName, </li></ul><ul><li>Due to your safe driving record, we are refunding $refundAmount on your auto policy ($policyNumber). </li></ul><ul><li></p> </li></ul><ul><li></BODY> </li></ul><ul><li></HTML> </li></ul>
  33. 33. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  34. 34. Commons HttpClient Overview <ul><li>API to help develop an HTTP Client </li></ul><ul><ul><li>GET / POST </li></ul></ul><ul><ul><li>Authentication </li></ul></ul><ul><ul><li>Redirect </li></ul></ul><ul><ul><li>Proxy </li></ul></ul><ul><ul><li>Encodings </li></ul></ul><ul><ul><li>Cookies </li></ul></ul><ul><li>In its final release (3.x) </li></ul><ul><ul><li>http://hc.apache.org/httpclient-3.x/index.html </li></ul></ul><ul><li>To be replaced by HttpComponents: </li></ul><ul><ul><li>http://hc.apache.org </li></ul></ul><ul><ul><li>Still in Beta </li></ul></ul><ul><ul><li>“ Not yet, grasshopper” </li></ul></ul>
  35. 35. HttpClient Example <ul><li>public class MyHttpClient { </li></ul><ul><li>… </li></ul><ul><li>public static String sendPostRequest(MyRequestDto myRequestDto) </li></ul><ul><li>throws MyHttpClientException { </li></ul><ul><li>String responseString = null; </li></ul><ul><li>PostMethod httpPost = null; </li></ul><ul><li>HttpClient httpClient = new HttpClient(); </li></ul><ul><li>MyHttpClient.setupProxy(httpClient); </li></ul><ul><li>try { </li></ul><ul><li>// Create and send the HTTP Request. </li></ul><ul><li>httpPost = MyHttpClient.setupHttpPostRequest(myRequestDto); </li></ul><ul><li>httpClient.executeMethod(httpPost); </li></ul><ul><li>// Get the HTTP Status. </li></ul><ul><li>if (httpPost.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) { </li></ul><ul><li>MyHttpClient.handleRedirect(httpClient, httpPost); </li></ul><ul><li>} </li></ul><ul><li>//Get HTTP response. </li></ul><ul><li>responseString = MyHttpClient.getHttpResponse(httpPost); </li></ul><ul><li>… </li></ul>
  36. 36. HttpClient Example … Cont’d <ul><li>} catch (HttpException he) { </li></ul><ul><li>… </li></ul><ul><li>} catch (IOException ioe) { </li></ul><ul><li>… </li></ul><ul><li>} finally { </li></ul><ul><li>httpPost.releaseConnection(); </li></ul><ul><li>} </li></ul><ul><li>return responseString; </li></ul><ul><li>} </li></ul><ul><li>private static void setupProxy(HttpClient httpClient) { // Tunnel through a proxy. </li></ul><ul><li>String useProxy = MyPropertyUtil.getProperty(USE_PROXY); </li></ul><ul><li>if (StringUtils.isNotBlank(useProxy) && useProxy.equalsIgnoreCase(YES)) { </li></ul><ul><li>String proxyHost = MyPropertyUtil.getProperty(MY_PROXY_HOST), </li></ul><ul><li>proxyPort = MyPropertyUtil.getProperty(MY_PROXY_PORT), </li></ul><ul><li>proxyRealm = MyPropertyUtil.getProperty(MY_PROXY_REALM), </li></ul><ul><li>proxyUser = MyPropertyUtil.getProperty(MY_PROXY_USER), </li></ul><ul><li>proxyPassword = MyPropertyUtil.getProperty(MY_PROXY_PASSWORD); </li></ul><ul><li>httpClient.getHostConfiguration().setProxy(proxyHost, </li></ul><ul><li>Integer.parseInt(proxyPort)); </li></ul><ul><li>httpClient.getState().setProxyCredentials(proxyRealm, proxyHost, </li></ul><ul><li>new UsernamePasswordCredentials(proxyUser, proxyPassword)); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  37. 37. HttpClient Example … Cont’d <ul><li>private static PostMethod setupHttpPostRequest(MyRequestDto myRequestDto) { </li></ul><ul><li>String myUrl = MyPropertyUtil.getProperty(ConfigConstants.CONFIG_MY_URL); </li></ul><ul><li>PostMethod httpPost = new PostMethod(myUrl); </li></ul><ul><li>// Populate HTTP Post Parameters. </li></ul><ul><li>httpPost.addParameter(REDIR_KEY, REDIR_VALUE); </li></ul><ul><li>httpPost.addParameter(FIRST_NAME_KEY, myRequestDto.getFirstName()); </li></ul><ul><li>… </li></ul><ul><li>return httpPost; </li></ul><ul><li>} </li></ul><ul><li>private static void handleRedirect(HttpClient httpclient, PostMethod httpPost) </li></ul><ul><li>throws MyHttpClientException { </li></ul><ul><li>try { </li></ul><ul><li>Header locationHeader = </li></ul><ul><li>httpPost.getResponseHeader(HTTP_RESPONSE_LOCATION_HEADER); </li></ul><ul><li>if locationHeader != null) { </li></ul><ul><li>String redirectLocation = locationHeader.getValue(); </li></ul><ul><li>httpPost.setURI(redirectLocation); </li></ul><ul><li>httpClient.executeMethod(httpPost); </li></ul><ul><li>} </li></ul><ul><li>} catch (URIException ue) { </li></ul><ul><li>… </li></ul><ul><li>} // 2 others – HttpException, IOException </li></ul><ul><li>} </li></ul>
  38. 38. HttpClient Example … Cont’d <ul><li>private static String getHttpResponse(PostMethod httpPost) </li></ul><ul><li>throws MyHttpClientException { </li></ul><ul><li>String responseString = null; </li></ul><ul><li>InputStream is = null; </li></ul><ul><li>try { </li></ul><ul><li>is = httpPost.getResonseBodyAsStream(); </li></ul><ul><li>BufferedReader br = new BufferedReader(new InputStreamReader(is)); </li></ul><ul><li>StringBuffer responseBuffer = new StringBuffer(); </li></ul><ul><li>String line = null; </li></ul><ul><li>boolean done = false; </li></ul><ul><li>while (!done) { </li></ul><ul><li>line = br.readLine(); </li></ul><ul><li>done = (line == null); </li></ul><ul><li>if (!done) { </li></ul><ul><li>responseBuffer.append(line); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>responseString – responseBuffer.toString().trim(); </li></ul><ul><li>} catch (IOException ioe) { </li></ul><ul><li>… </li></ul>
  39. 39. HttpClient Example … Cont’d <ul><li>} finally { </li></ul><ul><li>if (is != null) { </li></ul><ul><li>try { </li></ul><ul><li>is.close(); </li></ul><ul><li>} catch (…) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>return responseString; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  40. 40. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul>
  41. 41. Commons IO Overview <ul><li>API to simplify IO processing </li></ul><ul><ul><li>http://commons.apache.org/io </li></ul></ul><ul><li>Key Areas </li></ul><ul><ul><li>Utility classes – Perform common tasks </li></ul></ul><ul><ul><li>Filters – File filter implementations </li></ul></ul><ul><ul><li>Comparators – For comparing lists of files </li></ul></ul><ul><ul><li>Streams – Stream, Reader and Writer implementations </li></ul></ul><ul><li>My Favorite – IOUtils </li></ul>
  42. 42. Stream I/O without Commons IO <ul><li>private static String getHttpResponse(PostMethod httpPost) </li></ul><ul><li>throws MyHttpClientException { </li></ul><ul><li>String responseString = null; </li></ul><ul><li>InputStream is = null; </li></ul><ul><li>try { </li></ul><ul><li>is = httpPost.getResonseBodyAsStream(); </li></ul><ul><li>BufferedReader br = new BufferedReader(new InputStreamReader(is)); </li></ul><ul><li>StringBuffer responseBuffer = new StringBuffer(); </li></ul><ul><li>String line = null; </li></ul><ul><li>boolean done = false; </li></ul><ul><li>while (!done) { </li></ul><ul><li>line = br.readLine(); </li></ul><ul><li>done = (line == null); </li></ul><ul><li>if (!done) { </li></ul><ul><li>responseBuffer.append(line); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>responseString – responseBuffer.toString().trim(); </li></ul><ul><li>} catch (IOException ioe) { </li></ul><ul><li>… </li></ul>
  43. 43. Stream I/O without Commons IO … Cont’d <ul><li>} finally { </li></ul><ul><li>if (is != null) { </li></ul><ul><li>try { </li></ul><ul><li>is.close(); </li></ul><ul><li>} catch (…) { </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>return responseString; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  44. 44. Stream I/O with Commons IO <ul><li>private static String getHttpResponse(PostMethod httpPost) </li></ul><ul><li>throws MyHttpClientException { </li></ul><ul><li>String responseString = null; </li></ul><ul><li>InputStream is = null; </li></ul><ul><li>try { </li></ul><ul><li>is = httpPost.getResonseBodyAsStream(); </li></ul><ul><li>responseString = IOUtils.toString(is); </li></ul><ul><li>} catch (IOExeception ioe) { </li></ul><ul><li>… </li></ul><ul><li>} finally { </li></ul><ul><li>IOUtils.closeQuietly(is); </li></ul><ul><li>} </li></ul><ul><li>return responseString; </li></ul><ul><li>} </li></ul>
  45. 45. Session Roadmap <ul><li>Where are we? </li></ul><ul><li>Commons Lang </li></ul><ul><li>Commons Configuration </li></ul><ul><li>Commons Logging and Log4J </li></ul><ul><li>POI </li></ul><ul><li>Commons Email </li></ul><ul><li>Velocity </li></ul><ul><li>HttpClient </li></ul><ul><li>Commons IO </li></ul><ul><li>Summary </li></ul><ul><ul><li>Conclusions </li></ul></ul><ul><ul><li>Questions </li></ul></ul><ul><ul><li>Resources </li></ul></ul>
  46. 46. Conclusions <ul><li>Apache has a wealth of useful APIs </li></ul><ul><li>SourceForge (and others) also have great APIs </li></ul><ul><li>Use thin wrappers to hide the details </li></ul><ul><li>Research Open Source before coding </li></ul><ul><ul><li>Don’t re-invent the wheel </li></ul></ul><ul><ul><li>Google, anyone?  </li></ul></ul>
  47. 47. Questions? <ul><li>Tom Marrs </li></ul><ul><li>Principal Architect </li></ul><ul><li>[email_address] </li></ul>
  48. 48. Resources <ul><li>Apache Main Page: http:// www.apache.org </li></ul><ul><li>Apache Commons: http://commons.apache.org </li></ul><ul><ul><li>Lang: http://commons.apache.org/lang </li></ul></ul><ul><ul><li>Configuration: http://commons.apache.org/configuration </li></ul></ul><ul><ul><li>Logging: http:// commons.apache.org /logging </li></ul></ul><ul><ul><li>Email: http://commons.apache.org/email </li></ul></ul><ul><ul><li>IO: http://commons.apache.org/io </li></ul></ul><ul><ul><li>HttpClient: http://hc.apache.org/httpclient-3.x/index.html </li></ul></ul><ul><li>Apache Log4J: http://logging.apache.org/log4j/1.2/index.html </li></ul><ul><li>Apache Velocity: http://velocity.apache.org </li></ul><ul><li>FreeMarket: http://freemarker.sourceforge.net </li></ul><ul><li>Apache POI: http://poi.apache.org </li></ul><ul><li>Apache HttpComponents: http:// hc.apache.org </li></ul>

×