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.shindig.gadgets;
 
 import  com.google.common.collect.ImmutableList;
 import  com.google.common.collect.Lists;
 import  com.google.common.collect.Maps;
 import  com.google.inject.Inject;
 
 
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
Provides a mechanism for loading a group of js features from a directory. All directories from the given input will be checked recursively for files named "feature.xml" Usage: GadgetFeatureRegistry registry = // get your feature registry. JsFeatureLoader loader = new JsFeatureLoader(fetcher); loader.loadFeatures("res://features/", registry); loader.loadFeatures("/home/user/my-features/", registry);
 
 public class JsFeatureLoader {
 
   public final static char FILE_SEPARATOR = ',';
 
   private final HttpFetcher fetcher;
 
   private static final Logger logger
       = Logger.getLogger("org.apache.shindig.gadgets");

  

Parameters:
fetcher
 
   @Inject
   public JsFeatureLoader(HttpFetcher fetcher) {
     this. = fetcher;
   }
  
  
Loads all of the gadgets in the directory specified by path. Invalid features will not cause this to fail, but passing an invalid path will.

Parameters:
path The file or directory to load the feature from. If feature.xml is passed in directly, it will be loaded as a single feature. If a directory is passed, any features in that directory (recursively) will be loaded. If res://*.txt is passed, we will look for named resources in the text file. If path is prefixed with res://, the file is treated as a resource, and all references are assumed to be resources as well. Multiple locations may be specified by separating them with a comma.
Throws:
GadgetException If any of the files can't be read.
 
   public void loadFeatures(String pathGadgetFeatureRegistry registry)
       throws GadgetException {
     List<ParsedFeaturefeatures = Lists.newLinkedList();
     try {
       for (String location : StringUtils.split(path)) {
         if (location.startsWith("res://")) {
           location = location.substring(6);
           .info("Loading resources from: " + location);
           if (location.endsWith(".txt")) {
             List<Stringresources = Lists.newArrayList();
             for (String resource : ResourceLoader.getContent(location).split("[\r\n]+")) {
               // Skip blank/commented lines
               if (StringUtils.trim(resource).length() > 0 && resource.charAt(0) != '#') {
                resources.add(StringUtils.trim(resource));
              }
            }
            loadResources(resourcesfeatures);
          } else {
            loadResources(ImmutableList.of(location), features);
          }
        } else {
          .info("Loading files from: " + location);
          File file = new File(location);
          loadFiles(new File[]{file}, features);
        }
      }
    } catch (IOException e) {
      throw new GadgetException(..e);
    }
    for (ParsedFeature feature : features) {
      GadgetFeature gadgetFeature
          = new GadgetFeature(feature.namefeature.librariesfeature.deps);
      registry.register(gadgetFeature);
    }
  }

  
Parses and registers a single feature xml. Used for testing.

Parameters:
xml
Returns:
The parsed feature.
      throws GadgetException {
    ParsedFeature parsed = parse(xml""false);
    GadgetFeature feature
        = new GadgetFeature(parsed.nameparsed.librariesparsed.deps);
    registry.register(feature);
    return feature;
  }

  
Loads features from directories recursively.

Parameters:
files The files to examine.
features The set of all loaded features
Throws:
GadgetException
  private void loadFiles(File[] filesList<ParsedFeaturefeatures)
      throws GadgetException {
    for (File file : files) {
      if (file.isDirectory()) {
        loadFiles(file.listFiles(), features);
      } else if (file.getName().toLowerCase(.).endsWith(".xml")) {
        if (!file.exists()) {
            throw new GadgetException(..,
                                      "The file '" + file.getAbsolutePath() + "' doesn't exist.");
        }
        ParsedFeature feature = processFile(file);
        if (feature != null) {
          features.add(feature);
        }
      } else {
          if (.isLoggable(.)) .finest(file.getAbsolutePath() + " doesn't seem to be an XML file.");
      }
    }
  }

  
Loads resources recursively.

Parameters:
paths The base paths to look for feature.xml
features The set of all loaded features
Throws:
GadgetException
  private void loadResources(List<StringpathsList<ParsedFeaturefeatures)
      throws GadgetException {
    try {
      for (String file : paths) {
        if (.isLoggable(.)) .fine("Processing resource: " + file);
        String content = ResourceLoader.getContent(file);
        String parent = file.substring(0, file.lastIndexOf('/') + 1);
        ParsedFeature feature = parse(contentparenttrue);
        if (feature != null) {
          features.add(feature);
        } else {
          .warning("Failed to parse feature: " + file);
        }
      }
    } catch (IOException e) {
      throw new GadgetException(..e);
    }
  }

  
Loads a single feature from a file. If the file can't be loaded, an error will be generated but no exception will be thrown.

Parameters:
file The file that contains the feature description.
Returns:
The parsed feature.
  private ParsedFeature processFile(File file) {
    .info("Loading file: " + file.getName());
    ParsedFeature feature = null;
    if (file.canRead()) {
      try {
        feature = parse(ResourceLoader.getContent(file),
                        file.getParent() + '/',
                        false);
      } catch (IOException e) {
        .warning("Error reading file: " + file.getAbsolutePath());
      } catch (GadgetException e) {
        .warning("Failed parsing file: " + file.getAbsolutePath());
      }
    } else {
      .warning("Unable to read file: " + file.getAbsolutePath());
    }
    return feature;
  }

  
Parses the input into a dom tree.

Parameters:
xml
path The path the file was loaded from.
isResource True if the file was a resource.
Returns:
A dom tree representing the feature.
Throws:
GadgetException
  private ParsedFeature parse(String xmlString pathboolean isResource)
      throws GadgetException {
    Element doc;
    try {
      doc = XmlUtil.parse(xml);
    } catch (XmlException e) {
    }
    ParsedFeature feature = new ParsedFeature();
    feature.basePath = path;
    feature.isResource = isResource;
    NodeList nameNode = doc.getElementsByTagName("name");
    if (nameNode.getLength() != 1) {
          "No name provided");
    }
    feature.name = nameNode.item(0).getTextContent();
    NodeList gadgets = doc.getElementsByTagName("gadget");
    for (int i = 0, j = gadgets.getLength(); i < j; ++i) {
      processContext(feature, (Element)gadgets.item(i),
          .);
    }
    NodeList containers = doc.getElementsByTagName("container");
    for (int i = 0, j = containers.getLength(); i < j; ++i) {
      processContext(feature, (Element)containers.item(i),
          .);
    }
    NodeList dependencies = doc.getElementsByTagName("dependency");
    for (int i = 0, j = dependencies.getLength(); i < j; ++i) {
      feature.deps.add(dependencies.item(i).getTextContent());
    }
    return feature;
  }

  
Processes <gadget> and <container> tags and adds new libraries to the feature.

Parameters:
feature
context
renderingContext
Throws:
GadgetException
  private void processContext(ParsedFeature featureElement context,
                              RenderingContext renderingContext)
      throws GadgetException {
    String container = XmlUtil.getAttribute(context"container",
    NodeList libraries = context.getElementsByTagName("script");
    for (int i = 0, j = libraries.getLength(); i < j; ++i) {
      Element script = (Element)libraries.item(i);
      boolean inlineOk = XmlUtil.getBoolAttribute(script"inline"true);
      String source = XmlUtil.getAttribute(script"src");
      String content;
      JsLibrary.Type type;
      if (source == null) {
        type = ..;
        content = script.getTextContent();
      } else {
        content = source;
        if (content.startsWith("http://")) {
          type = ..;
        } else if (content.startsWith("//")) {
          type = ..;
          content = content.substring(1);
        } else if (content.startsWith("res://")) {
          content = content.substring(6);
          type = ..;
        } else if (feature.isResource) {
          // Note: Any features loaded as resources will assume that their
          // paths point to resources as well.
          content = feature.basePath + content;
          type = ..;
        } else {
          content = feature.basePath + content;
          type = ..;
        }
      }
      JsLibrary library = createJsLibrary(
          typecontentfeature.nameinlineOk ?  : null);
      for (String cont : container.split(",")) {
        feature.addLibrary(renderingContextcont.trim(), library);
      }
    }
  }
  
  protected JsLibrary createJsLibrary(JsLibrary.Type typeString contentString feature,
      HttpFetcher fetcherthrows GadgetException {
    return JsLibrary.create(typecontentfeaturefetcher);
  }
Temporary structure to represent the intermediary parse state.
  public String name = "";
  public String basePath = "";
  public boolean isResource = false;
  final List<Stringdeps;
  public ParsedFeature() {
        RenderingContext.class);
     = Lists.newLinkedList();
  }
  public void addLibrary(RenderingContext ctxString contJsLibrary library) {
    Map<StringList<JsLibrary>> ctxLibs = .get(ctx);
    if (ctxLibs == null) {
      ctxLibs = Maps.newHashMap();
      .put(ctxctxLibs);
    }
    List<JsLibrarycontainerLibs = ctxLibs.get(cont);
    if (containerLibs == null) {
      containerLibs = Lists.newLinkedList();
      ctxLibs.put(contcontainerLibs);
    }
    containerLibs.add(library);
  }
New to GrepCode? Check out our FAQ X