WidgetServiceImpl.java :  » JPA » open-tides » org » opentides » service » impl » Java Open Source

Java Open Source » JPA » open tides 
open tides » org » opentides » service » impl » WidgetServiceImpl.java
/*
   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.    
 */
package org.opentides.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.Logger;
import org.opentides.bean.Widget;
import org.opentides.service.WidgetService;
import org.opentides.util.SecurityUtil;
import org.opentides.util.StringUtil;
import org.opentides.util.UrlUtil;
import org.springframework.transaction.annotation.Transactional;

/**
 * This is the service implementation for Widget.
 * Auto generated by high tides.
 * @author hightides
 *
 */
public class WidgetServiceImpl extends BaseCrudServiceImpl<Widget>
    implements WidgetService {
//-- Start custom codes. Do not delete this comment line.

  private static Logger _log = Logger
      .getLogger(WidgetServiceImpl.class);
  
  private String widgetColumn;
  
  private static Pattern pattern = Pattern.compile("<img\\s[^>]*src=\"?(.*?)[\" ]",
      Pattern.CASE_INSENSITIVE|Pattern.MULTILINE);

  class ResponseObject {
    public String responseType;
    public byte[] responseBody;
  }
  
  @Transactional(readOnly = true)
  public Widget findByName(String name) {
    Widget example = new Widget();
    example.setName(name);
    List<Widget> dashboardList = getDao().findByExample(example, true);
    if (dashboardList != null && dashboardList.size() > 0) {
      return dashboardList.get(0);
    }
    return null;
  }
  
  @Transactional(readOnly = true)
  public Widget findByUrl(String url) {
    Widget example = new Widget();
    example.setUrl(url);
    List<Widget> dashboardList = getDao().findByExample(example, true);
    if (dashboardList != null && dashboardList.size() > 0) {
      return dashboardList.get(0);
    }
    return null;
  }

  /*
   * (non-Javadoc)
   * 
   * @see
   * org.opentides.service.WidgetService#requestWidget(java.lang
   * .String)
   */
  public Widget requestWidget(String widgetUrl, String name, HttpServletRequest req) {
    Widget settings = findByName(name);
    if (settings != null) {
      long now = System.currentTimeMillis();
      Date lastCacheDate = settings.getLastCacheUpdate();

      boolean useCache = false;
      // check if we should use cache or not
      if (lastCacheDate != null) {
        long expire = settings.getLastCacheUpdate().getTime()
            + settings.getCacheDuration() * 1000;
        if (settings.getCacheType().startsWith(
            Widget.TYPE_IMAGE)
            || now < expire)
          useCache = true;
      }
      if (settings.getCacheDuration() < 0) {
        // means that we don't want to support caching...
        return settings;
      } else if (useCache) {
        _log.debug("Reusing widget [" + settings.getName()
            + "] from cache...");
        // retrieve from cache
        return settings;
      } else {
        // retrieve from url
        String url = settings.getUrl();
        if (!UrlUtil.hasProtocol(url)) {
          String slash = "/";
          if (!url.startsWith("/")) {
            url = slash + url;
          }
          url = req.getContextPath().toString() + url;
          if (req.getServerPort() != 80) {
            url = ":" + Integer.toString(req.getServerPort()) + url;
          }
          url = UrlUtil.ensureProtocol(req.getServerName() + url);
        }
        ResponseObject response = getHttpRequest(url);
        if (response==null)
          return null;
        if (response.responseType
            .startsWith(Widget.TYPE_IMAGE)) {
          _log.debug("Retrieving image [" + settings.getName()
              + "] from url [" + settings.getUrl() + "]...");
          settings.setCacheType(response.responseType);
          settings.setCache(response.responseBody);
          settings.setLastCacheUpdate(new Date());
          save(settings);
          _log.debug("Saved image [" + settings.getName()
              + "] to cache...");
          return settings;
        } else {
          _log.debug("Retrieving widget [" + settings.getName()
              + "] from url [" + settings.getUrl() + "]...");
          settings.setCacheType(response.responseType);
          // check for image inside the html
          String html = new String(response.responseBody);
          String hostname = UrlUtil.getHostname(url);
          Matcher matcher = pattern.matcher(html);
          while (matcher.find()) {
            // add image link to cache
            String imageUrl = matcher.group(1);
            String cacheUrl = imageUrl;
            if (!UrlUtil.hasProtocol(cacheUrl)) {
              if (!imageUrl.startsWith("/")) { 
                cacheUrl = "http://" + hostname + "/" + imageUrl;
              } else {
                cacheUrl = "http://" + hostname  + imageUrl;
              }
            }
            String imageName = this.addCache(cacheUrl, settings);
            // replace html that reference to image with cached image
            String newUrl = widgetUrl+"?name="+imageName;
            html = html.replace(imageUrl, newUrl);
          }
          settings.setCache(html.getBytes());
          settings.setLastCacheUpdate(new Date());
          save(settings);
          _log.debug("Saved widget [" + settings.getName()
              + "] to cache...");
          return settings;
        }
      }
    }
    return null;
  }

  /**
   * Private helper to save image cache.
   * 
   * @param imageUrl
   * @return
   */
  private String addCache(String url, Widget parentSettings) {
    Widget settings = this.findByUrl(url);
    if (settings == null)
      settings = new Widget(url, parentSettings);
    ResponseObject response = getHttpRequest(url);
    if (response.responseType.startsWith(Widget.TYPE_IMAGE))
      settings.setCacheType(Widget.TYPE_IMAGE);
    else
      settings.setCacheType(Widget.TYPE_HTML);
    settings.setCache(response.responseBody);
    this.save(settings);
    settings.setName(""+settings.getId());
    this.save(settings);
    return settings.getName();
  }
  
  /**
   * Returns all the widgets that are available and accessible
   * to the current user.
   * @return
   */
  @Transactional(readOnly=true)
  public List<Widget> getCurrentUserWidgets() {
    Widget example = new Widget();
    example.setIsUserDefined(true);
    List<Widget> widgets = new ArrayList<Widget>();
    for (Widget widget:findByExample(example, true)) {
      if (StringUtil.isEmpty(widget.getAccessCode()))
        widgets.add(widget);
      else if (SecurityUtil.currentUserHasPermission(widget.getAccessCode())) 
        widgets.add(widget);          
    }
    return widgets;
  }

  /**
   * Consider moving this method as public helper (if useful for others)
   * 
   * @param url
   * @return
   */
  @Transactional(readOnly=true)
  private ResponseObject getHttpRequest(final String url) {
    // Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance
    String httpUrl = UrlUtil.ensureProtocol(url);
    GetMethod method = new GetMethod(httpUrl);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
        new DefaultHttpMethodRetryHandler(3, false));

    try {
      // Execute the method.
      int statusCode = client.executeMethod(method);

      if (statusCode != HttpStatus.SC_OK) {
        _log.error("Method failed: " + method.getStatusLine());
        return null;
      }

      // Read the response body.
      ResponseObject response = new ResponseObject();
      response.responseBody = method.getResponseBody();
      response.responseType = method.getResponseHeader("Content-Type").getValue();
      return response;
    } catch (HttpException e) {
      _log.error("Fatal protocol violation: " + e.getMessage(), e);
      return null;
    } catch (IOException e) {
      _log.error("Fatal transport error: " + e.getMessage(), e);
      return null;
    } finally {
      // Release the connection. 
      try { 
        method.releaseConnection();
      } catch(Exception ignore) {return null; };
    }
  }
  
  public void setWidgetColumn(String widgetColumn) {
    this.widgetColumn = widgetColumn;
  }
  
  public String getWidgetColumn() {
    return widgetColumn;
  }

  public int getColumnConfig() {
    return StringUtil.convertToInt(getWidgetColumn(),2);
  }
  //-- End custom codes. Do not delete this comment line.
  
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.