Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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.apache.felix.webconsole.internal.misc;
 
 
 import java.net.URL;
 
 
LicenseServlet provides the licenses plugin that browses through the bundles, searching for common license files. TODO: add support for 'Bundle-License' manifest header
 
 public final class LicenseServlet extends SimpleWebConsolePlugin implements OsgiManagerPlugin
 {
     // common names (without extension) of the license files.
     static final String LICENSE_FILES[] =
         { "README""DISCLAIMER""LICENSE""NOTICE""DEPENDENCIES" };
 
     static final String LABEL = "licenses";
     static final String TITLE = "%licenses.pluginTitle";
     static final String CSS[] = { "/res/ui/license.css" };
 
     // templates
     private final String TEMPLATE;

    
Default constructor
 
     public LicenseServlet()
     {
         super();
 
         // load templates
          = readTemplateFile"/templates/license.html" );
     }

    
 
     protected void doGet(HttpServletRequest requestHttpServletResponse response)
         throws ServletExceptionIOException
     {
         final PathInfo pathInfo = PathInfo.parserequest.getPathInfo() );
         if ( pathInfo != null )
         {
             if ( !sendResourcepathInforesponse ) )
             {
                 response.sendError."Cannot send data .." );
             }
         }
         else
         {
             super.doGetrequestresponse );
         }
     }


    
    protected void renderContentHttpServletRequest requestHttpServletResponse res ) throws IOException
    {
        Bundle[] bundles = getBundleContext().getBundles();
        Util.sortbundlesrequest.getLocale() );
        // prepare variables
        DefaultVariableResolver vars = ( ( DefaultVariableResolver ) WebConsoleUtil.getVariableResolverrequest ) );
        vars.put"__data__"getBundleDatabundlesrequest.getLocale() ).toString());
        res.getWriter().print();
    }
    private static final JSONArray getBundleData(Bundle[] bundlesLocale localethrows IOException
    {
        JSONArray ret = new JSONArray();
        try
        {
            for (int i = 0; i < bundles.lengthi++)
            {
                Bundle bundle = bundles[i];
                JSONObject files = findResource(bundle);
                addLicensesFromHeader(bundlefiles);
                if (files.length() > 0)
                { // has resources
                    JSONObject data = new JSONObject();
                    data.put"bid"bundle.getBundleId() );
                    data.put"title", Util.getNamebundlelocale ) );
                    data.put"files"files );
                    ret.putdata );
                }
            }
        }
        catch (JSONException je)
        {
            throw new IOException(je.toString());
        }
        return ret;
    }
    private static final String getNameString path )
    {
        return path.substringpath.lastIndexOf'/' ) + 1 );
    }
    private static final JSONObject addLicensesFromHeader(Bundle bundleJSONObject files)
        throws JSONException
    {
        String target = (Stringbundle.getHeaders("").get("Bundle-License");
        if (target != null)
        {
            Clause[] licenses = Parser.parseHeader(target);
            for (int i = 0; licenses != null && i < licenses.lengthi++)
            {
                final String name = licenses[i].getName();
                if (!"<<EXTERNAL>>".equals(name))
                {
                    final String link = licenses[i].getAttribute("link");
                    final String path;
                    final String url;
                    if (link == null)
                    {
                        path = name;
                        url = getName(name);
                    }
                    else
                    {
                        path = link;
                        url = name;
                    }
                    // skip entry URL is bundle resources, but doesn't exists
                    if (path.indexOf("://") == -1 && null == bundle.getEntry(path))
                        continue;
                    JSONObject entry = new JSONObject();
                    entry.put("path"path);
                    entry.put("url"url);
                    files.append("__res__"entry);
                }
            }
        }
        return files;
    }
    private static final JSONObject findResourceBundle bundleString[] patterns ) throws IOExceptionJSONException
    {
        JSONObject ret = new JSONObject();
        for ( int i = 0; i < patterns.lengthi++ )
        {
            Enumeration entries = bundle.findEntries"/"patterns[i] + "*"true );
            if ( entries != null )
            {
                while ( entries.hasMoreElements() )
                {
                    URL url = ( URL ) entries.nextElement();
                    JSONObject entry = new JSONObject();
                    entry.put"path"url.getPath() );
                    entry.put"url"getNameurl.getPath() ) );
                    ret.append"__res__"entry );
                }
            }
        }
        Enumeration entries = bundle.findEntries"/""*.jar"true );
        if ( entries != null )
        {
            while ( entries.hasMoreElements() )
            {
                URL url = ( URL ) entries.nextElement();
                final String resName = getNameurl.getPath() );
                InputStream ins = null;
                try
                {
                    ins = url.openStream();
                    ZipInputStream zin = new ZipInputStreamins );
                    for ( ZipEntry zentry = zin.getNextEntry(); zentry != nullzentry = zin.getNextEntry() )
                    {
                        String name = zentry.getName();
                        // ignore directory entries
                        if ( name.endsWith"/" ) )
                        {
                            continue;
                        }
                        // cut off path and use file name for checking against patterns
                        name = name.substringname.lastIndexOf'/' ) + 1 );
                        for ( int i = 0; i < patterns.lengthi++ )
                        {
                            if ( name.startsWithpatterns[i] ) )
                            {
                                JSONObject entry = new JSONObject();
                                entry.put"jar"url.getPath() );
                                entry.put"path"zentry.getName() );
                                entry.put"url"getNamename ) );
                                ret.appendresNameentry );
                            }
                        }
                    }
                }
                finally
                {
                    IOUtils.closeQuietlyins );
                }
            }
        }
        return ret;
    }
    private boolean sendResourcefinal PathInfo pathInfofinal HttpServletResponse response ) throws IOException
    {
        final String name = pathInfo.licenseFile.substringpathInfo.licenseFile.lastIndexOf'/' ) + 1 );
        boolean isLicense = false;
        for ( int i = 0; !isLicense && i < .i++ )
        {
            isLicense = name.startsWith[i] );
        }
        final Bundle bundle = getBundleContext().getBundlepathInfo.bundleId );
        if ( bundle == null )
        {
            return false;
        }
        // prepare the response
        WebConsoleUtil.setNoCacheresponse );
        response.setContentType"text/plain" );
        if ( pathInfo.innerJar == null )
        {
            URL resource = bundle.getEntrypathInfo.licenseFile );
            if ( resource == null)
            {
                resource = bundle.getResourcepathInfo.licenseFile );
            }
        
            
            if ( resource != null )
            {
                final InputStream input = resource.openStream();
                try
                {
                    IOUtils.copyinputresponse.getWriter() );
                    return true;
                }
                finally
                {
                    IOUtils.closeQuietlyinput );
                }
            }
        }
        else
        {
            // license is in a nested JAR
            final URL zipResource = bundle.getResourcepathInfo.innerJar );
            if ( zipResource != null )
            {
                final InputStream input = zipResource.openStream();
                ZipInputStream zin = null;
                try
                {
                    zin = new ZipInputStreaminput );
                    for ( ZipEntry zentry = zin.getNextEntry(); zentry != nullzentry = zin.getNextEntry() )
                    {
                        if ( pathInfo.licenseFile.equalszentry.getName() ) )
                        {
                            IOUtils.copyzinresponse.getWriter() );
                            return true;
                        }
                    }
                }
                finally
                {
                    IOUtils.closeQuietlyzin );
                    IOUtils.closeQuietlyinput );
                }
            }
        }
        // throw new ServletException("License file:" + url + " not found!");
        return false;
    }
    // package private for unit testing of the parse method
    static class PathInfo
    {
        final long bundleId;
        final String innerJar;
        final String licenseFile;
        static PathInfo parsefinal String pathInfo )
        {
            if ( pathInfo == null || pathInfo.length() == 0 || !pathInfo.startsWith"/" +  + "/" ) )
            {
                return null;
            }
            // cut off label prefix including slashes around the label
            final String parts = pathInfo.substring.length() + 2 );
            int slash = parts.indexOf'/' );
            if ( slash <= 0 )
            {
                return null;
            }
            final long bundleId;
            try
            {
                bundleId = Long.parseLongparts.substring( 0, slash ) );
                if ( bundleId < 0 )
                {
                    return null;
                }
            }
            catch ( NumberFormatException nfe )
            {
                // illegal bundle id
                return null;
            }
            final String innerJar;
            int jarSep = parts.indexOf"!/"slash );
            if ( jarSep < 0 )
            {
                innerJar = null;
            }
            else
            {
                innerJar = parts.substringslashjarSep );
                slash = jarSep + 2; // ignore bang-slash
            }
            final String licenseFile = parts.substringslash );
            return new PathInfobundleIdinnerJarlicenseFile );
        }
        private PathInfofinal long bundleIdfinal String innerJarfinal String licenseFile )
        {
            this. = bundleId;
            this. = innerJar;
            this. = licenseFile;
        }
    }
New to GrepCode? Check out our FAQ X