War Util : Web INF XML « Servlets « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » Servlets » Web INF XMLScreenshots 
War Util
        
/*
 * Copyright 2005-2010 the original author or authors.
 * Licensed 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 sdloader.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

/**
 * WarUtil
 
 @author c9katayama
 */
public class WarUtil {

  //private static SDLoaderLog log = SDLoaderLogFactory.getLog(WarUtil.class);

  private static final String LAST_MODIFIED_FILE = ".warlastmodified";

  /**
   * War?????????
   
   @param warFileName
   @return
   */
  public static String getArchiveName(final String warFileName) {
    return warFileName.substring(0, warFileName.length() ".war".length());
  }

  private static long readLastModifiled(File file) {
    if (file.exists()) {
      BufferedReader reader = null;
      try {
        reader = new BufferedReader(new FileReader(file));
        return Long.valueOf(reader.readLine());
      catch (Exception e) {
      //  log.debug(e.getMessage(), e);
      }
    }
    return 0;
  }

  private static void writeLastModifiled(File file, long time) {
    BufferedWriter writer = null;
    try {
      if (!file.exists()) {
        file.createNewFile();
      }
      writer = new BufferedWriter(new FileWriter(file));
      writer.write(Long.toString(time));
      writer.flush();
    catch (Exception e) {
      
    
  }

  /**
   * WAR???????????
   
   @param warFile
   @param directory
   @throws IOException
   */
  public static void extractWar(File warFile, File directory)
      throws IOException {
    try {
      long timestamp = warFile.lastModified();
      File warModifiedTimeFile = new File(directory, LAST_MODIFIED_FILE);
      long lastModified = readLastModifiled(warModifiedTimeFile);

      if (timestamp == lastModified) {
    //    log.info("war file " + warFile.getName() + " not modified.");
        return;
      }
      if (directory.exists()) {
  //      IOUtil.forceRemoveDirectory(directory);
        directory.mkdir();
      }

//      log.info("war extract start. warfile=" + warFile.getName());

      JarInputStream jin = new JarInputStream(new BufferedInputStream(
          new FileInputStream(warFile)));
      JarEntry entry = null;

      while ((entry = jin.getNextJarEntry()) != null) {
        File file = new File(directory, entry.getName());

        if (entry.isDirectory()) {
          if (!file.exists()) {
            file.mkdirs();
          }
        else {
          File dir = new File(file.getParent());
          if (!dir.exists()) {
            dir.mkdirs();
          }

          FileOutputStream fout = null;
          try {
            fout = new FileOutputStream(file);
            ResourceUtil.copyStream(jin, fout);
          finally {
            fout.flush();
            fout.close();
            fout = null;
          }

          if (entry.getTime() >= 0) {
            file.setLastModified(entry.getTime());
          }
        }
      }

      writeLastModifiled(warModifiedTimeFile, timestamp);

      //log.info("war extract success. lastmodified=" + timestamp);
    catch (IOException ioe) {
      //log.info("war extract fail.");
      throw ioe;
    }
  }
}
class ResourceUtil {

  private static final int DEFAULT_BUFFER_SIZE = 16 1024;

  private static final String SLASH = "/";
  private static final String FILE_PROTOCOL = "file";

  public static String stripFirstProtocolPart(String path) {
    return path.substring(path.indexOf(":"1, path.length());
  }

  public static String stripExtension(String value) {
    int dot = value.lastIndexOf(".");
    if (dot >= 0) {
      value = value.substring(0, dot);
    }
    return value;
  }

  public static URL createURL(final String url) {
    try {
      return new URL(url);
    catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
  }

  public static URL createURL(final URL baseURL, String relativeURL) {
    try {
      String protocol = baseURL.getProtocol();
      relativeURL = relativeURL.replace("\\", SLASH);
      // TODO
      if (protocol.startsWith(FILE_PROTOCOL)) {
        if (relativeURL.startsWith(SLASH)) {
          relativeURL = relativeURL
              .substring(1, relativeURL.length());
        }
        return new URL(baseURL, relativeURL);
      else {
        // TODO
        String baseArchivePath = baseURL.toExternalForm();
        if (baseArchivePath.endsWith(SLASH)) {
          baseArchivePath = baseArchivePath.substring(0,
              baseArchivePath.length() 1);
        }
        if (baseArchivePath.endsWith("!")) {
          baseArchivePath = baseArchivePath.substring(0,
              baseArchivePath.length() 1);
        }
        if (!relativeURL.startsWith(SLASH)) {
          relativeURL = SLASH + relativeURL;
        }
        return new URL(baseArchivePath + "!" + relativeURL);
      }
    catch (MalformedURLException e) {
      throw new RuntimeException(e);
    }
  }

  public static boolean isAbsoluteURL(String url) {
    return (url.indexOf(":/"!= -1);
  }

  public static boolean isResourceExist(URL resource) {
    if (resource.getProtocol().equals(FILE_PROTOCOL)) {
      try {
        File file = new File(resource.toURI());
        return file.exists();
      catch (URISyntaxException e) {
        return false;
      }
    }
    InputStream is = null;
    try {
      is = resource.openStream();
      return (is != null);
    catch (Exception ioe) {
      return false;
    
  }

  public static boolean isFileResource(URL resource) {
    return !resource.toExternalForm().endsWith(SLASH);
  }

  public static boolean isDirectoryResource(URL resource) {
    return resource.toExternalForm().endsWith(SLASH);
  }

  public static Properties loadProperties(String path, Class<?> caller) {
    InputStream is = getResourceAsStream(path, caller);
    if (is == null) {
      return null;
    }
    Properties p = new Properties();
    try {
      p.load(is);
    catch (IOException ioe) {
      return null;
    }
    return p;
  }

  /**
   * ?????????????????
   
   @param path
   @param caller
   @return
   */
  public static InputStream getResourceAsStream(String path, Class<?> caller) {

    String resource = path;
    if (resource.startsWith(SLASH)) {
      resource = resource.substring(1);
    }

    InputStream is = null;
    File file = new File(path);
    if (file.exists() && file.isFile()) {
      try {
        is = new FileInputStream(file);
      catch (FileNotFoundException e) {
      }
    }
    if (is == null) {
      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
      if (tcl != null) {
        is = tcl.getResourceAsStream(resource);
      }
    }
    if (is == null) {
      is = caller.getResourceAsStream(path);
    }
    if (is == null) {
      is = ClassLoader.class.getResourceAsStream(path);
    }
    if (is == null) {
      is = ClassLoader.getSystemResourceAsStream(resource);
    }

    return is;
  }

  /**
   * ?????????????
   
   @param in
   @param out
   @param ???????
   @return ?????????
   @throws IOException
   */
  public static final long copyStream(InputStream in, OutputStream out)
      throws IOException {
    return copyStream(in, out, DEFAULT_BUFFER_SIZE);
  }

  /**
   * ?????????????
   
   @param in
   @param out
   @return ?????????
   @throws IOException
   */
  public static final long copyStream(InputStream in, OutputStream out,
      int bufferSizethrows IOException {
    byte[] buf = new byte[bufferSize];
    long totalSize = 0;
    int s = -1;
    while ((s = in.read(buf)) != -1) {
      out.write(buf, 0, s);
      totalSize += s;
    }
    buf = null;
    return totalSize;
  }

  /**
   * InputStream??byte[]???????
   
   @param is
   @return
   @throws IOException
   */
  public static final byte[] getBytes(InputStream isthrows IOException {
    ByteDataBuffer buf = new ByteDataBuffer();
    copyStream(is, buf.getOutputStream());
    return buf.toByteArray();
  }
}

   
    
    
    
    
    
    
    
  
Related examples in the same category
1.Using Initialization Parameters Servlet
2.Init Param Servlet
3.Servlet Mapping In Web XML
4.A WebAppConfig object is a wrapper around a DOM tree for a web.xml file
5.Define welcome files for web application
6.Parse a web.xml file using the SAX2 API
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.