示例#1
0
 /**
  * @return an instanciation of the given content-type class name, or null if class wasn't found
  */
 public static ContentType getContentTypeFromClassName(String contentTypeClassName) {
   if (contentTypeClassName == null)
     contentTypeClassName = getAvailableContentTypes()[DEFAULT_CONTENT_TYPE_INDEX];
   ContentType ct = null;
   try {
     Class clazz = Class.forName(contentTypeClassName);
     ct = (ContentType) clazz.newInstance();
   } catch (ClassNotFoundException cnfex) {
     if (jpicedt.Log.DEBUG) cnfex.printStackTrace();
     JPicEdt.getMDIManager()
         .showMessageDialog(
             "The pluggable content-type you asked for (class "
                 + cnfex.getLocalizedMessage()
                 + ") isn't currently installed, using default instead...",
             Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"),
             JOptionPane.ERROR_MESSAGE);
   } catch (Exception ex) {
     if (jpicedt.Log.DEBUG) ex.printStackTrace();
     JPicEdt.getMDIManager()
         .showMessageDialog(
             ex.getLocalizedMessage(),
             Localizer.currentLocalizer().get("msg.LoadingContentTypeClass"),
             JOptionPane.ERROR_MESSAGE);
   }
   return ct;
 }
 /** Remove generated files */
 public void removeGeneratedFiles() {
   try {
     String classFileName = ctxt.getClassFileName();
     if (classFileName != null) {
       File classFile = new File(classFileName);
       if (log.isDebugEnabled()) log.debug("Deleting " + classFile);
       if (classFile.exists()) {
         if (!classFile.delete()) {
           log.warn(
               Localizer.getMessage(
                   "jsp.warning.compiler.classfile.delete.fail", classFile.getAbsolutePath()));
         }
       }
     }
   } catch (Exception e) {
     // Remove as much as possible, ignore possible exceptions
   }
   try {
     String javaFileName = ctxt.getServletJavaFileName();
     if (javaFileName != null) {
       File javaFile = new File(javaFileName);
       if (log.isDebugEnabled()) log.debug("Deleting " + javaFile);
       if (javaFile.exists()) {
         if (!javaFile.delete()) {
           log.warn(
               Localizer.getMessage(
                   "jsp.warning.compiler.javafile.delete.fail", javaFile.getAbsolutePath()));
         }
       }
     }
   } catch (Exception e) {
     // Remove as much as possible, ignore possible exceptions
   }
 }
示例#3
0
 @Test
 public void shouldLocalizeEnums() throws Exception {
   when(localizer.localize(anyString(), anyVararg())).thenReturn("ರಘುನಂದನ");
   assertThat(LocalizedMessage.messageFor(Enum.X).localize(localizer), is("ರಘುನಂದನ"));
   when(localizer.localize(anyString(), anyVararg())).thenReturn("ಪವನ");
   assertThat(LocalizedMessage.messageFor(Enum.yyy).localize(localizer), is("ಪವನ"));
 }
示例#4
0
  /*
   * Scans the given JarURLConnection for TLD files located in META-INF
   * (or a subdirectory of it), adding an implicit map entry to the taglib
   * map for any TLD that has a <uri> element.
   *
   * @param jarConn The JarURLConnection to the JAR file to scan
   *
   * Keep in sync with o.a.c.startup.TldConfig
   */
  private void tldScanJar(JarURLConnection jarConn) throws IOException {

    Jar jar = null;
    InputStream is;
    boolean foundTld = false;

    URL resourceURL = jarConn.getJarFileURL();
    String resourcePath = resourceURL.toString();

    try {
      jar = JarFactory.newInstance(jarConn.getURL());

      jar.nextEntry();
      String entryName = jar.getEntryName();
      while (entryName != null) {
        if (entryName.startsWith("META-INF/") && entryName.endsWith(".tld")) {
          is = null;
          try {
            is = jar.getEntryInputStream();
            foundTld = true;
            tldScanStream(resourcePath, entryName, is);
          } finally {
            if (is != null) {
              try {
                is.close();
              } catch (IOException ioe) {
                // Ignore
              }
            }
          }
        }
        jar.nextEntry();
        entryName = jar.getEntryName();
      }
    } finally {
      if (jar != null) {
        jar.close();
      }
    }

    if (!foundTld) {
      if (log.isDebugEnabled()) {
        log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar", resourcePath));
      } else if (showTldScanWarning) {
        // Not entirely thread-safe but a few duplicate log messages are
        // not a huge issue
        showTldScanWarning = false;
        log.info(Localizer.getMessage("jsp.tldCache.noTldSummary"));
      }
    }
  }
示例#5
0
  FunctionInfo createFunctionInfo(TreeNode elem) {

    String name = null;
    String klass = null;
    String signature = null;

    Iterator list = elem.findChildren();
    while (list.hasNext()) {
      TreeNode element = (TreeNode) list.next();
      String tname = element.getName();

      if ("name".equals(tname)) {
        name = element.getBody();
      } else if ("function-class".equals(tname)) {
        klass = element.getBody();
      } else if ("function-signature".equals(tname)) {
        signature = element.getBody();
      } else if ("display-name".equals(tname)
          || // Ignored elements
          "small-icon".equals(tname)
          || "large-icon".equals(tname)
          || "description".equals(tname)
          || "example".equals(tname)) {
      } else {
        if (log.isWarnEnabled()) {
          log.warn(Localizer.getMessage("jsp.warning.unknown.element.in.function", tname));
        }
      }
    }

    return new FunctionInfo(name, klass, signature);
  }
示例#6
0
 @Test
 public void shouldUseTheProvidedLocalizerToLocalizeWithArgs() {
   when(localizer.localize("ME", "for-real")).thenReturn("whateva");
   assertThat(
       LocalizedMessage.string("me", Arrays.asList("for-real")).localize(localizer),
       is("whateva"));
 }
示例#7
0
  public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
      throws SAXException {

    IslandSchema is = dispatcher.getSchemaProvider().getSchemaByNamespace(namespaceURI);
    if (is != null) {
      // find an island that has to be validated.
      // switch to the new IslandVerifier.
      IslandVerifier iv = is.createNewVerifier(namespaceURI, is.getElementDecls());
      dispatcher.switchVerifier(iv);
      iv.startElement(namespaceURI, localName, qName, atts);
      return;
    }

    boolean atLeastOneIsValid = false;

    for (int i = 0; i < exps.length; i++)
      if (exps[i] != null) {
        if (exps[i].getNameClass().accepts(namespaceURI, localName)) atLeastOneIsValid = true;
        else exps[i] = null; // this one is no longer valid.
      }

    if (!atLeastOneIsValid)
      // none is valid. report an error.
      dispatcher
          .getErrorHandler()
          .error(
              new SAXParseException(
                  Localizer.localize(ERR_UNEXPECTED_NAMESPACE, new Object[] {namespaceURI}),
                  locator));
  }
示例#8
0
 @Test
 public void shouldLocalizeDurations() throws Exception {
   Duration theDuration = new Duration(1000);
   String expected = "it took a long time";
   when(localizer.localize(theDuration)).thenReturn(expected);
   assertThat(LocalizedMessage.localizeDuration(theDuration).localize(localizer), is(expected));
 }
  /**
   * Create a JspRuntimeContext for a web application context.
   *
   * <p>Loads in any previously generated dependencies from file.
   *
   * @param context ServletContext for web application
   */
  public JspRuntimeContext(ServletContext context, Options options) {

    this.context = context;
    this.options = options;

    // Get the parent class loader
    parentClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
    if (parentClassLoader == null) {
      parentClassLoader = (URLClassLoader) this.getClass().getClassLoader();
    }

    if (log.isDebugEnabled()) {
      if (parentClassLoader != null) {
        log.debug(
            Localizer.getMessage(
                "jsp.message.parent_class_loader_is", parentClassLoader.toString()));
      } else {
        log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", "<none>"));
      }
    }

    initClassPath();

    if (context instanceof org.apache.jasper.servlet.JspCServletContext) {
      return;
    }

    if (Constants.IS_SECURITY_ENABLED) {
      initSecurity();
    }

    // If this web application context is running from a
    // directory, start the background compilation thread
    String appBase = context.getRealPath("/");
    if (!options.getDevelopment() && appBase != null && options.getCheckInterval() > 0) {
      lastCheck = System.currentTimeMillis();
    }
  }
示例#10
0
  /** Called when the broker is starting. */
  public XMLServiceImpl(Logger logger, FileSystem fileSystem) {
    log = logger;
    this.fileSystem = fileSystem;
    entityResolver = new CalthaEntityResolver(this, fileSystem, log);

    factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    log.info(Localizer.localize(MSG_PARSER, factory.getClass().getName()));

    xmlGrammarCache = new XMLGrammarCache(this, logger);

    // factory.setFeature("http://apache.org/xml/features/validation/dynamic",true);
    // log.info(Localizer.localize(MSG_DTDVALIDATION));
  }
示例#11
0
  /*
   * Parses the tag file directives of the given TagFile and turns them into a
   * TagInfo.
   *
   * @param elem The <tag-file> element in the TLD @param uri The location of
   * the TLD, in case the tag file is specified relative to it @param jarFile
   * The JAR file, in case the tag file is packaged in a JAR
   *
   * @return TagInfo correspoding to tag file directives
   */
  private TagFileInfo createTagFileInfo(TreeNode elem, String uri, URL jarFileUrl)
      throws JasperException {

    String name = null;
    String path = null;

    Iterator list = elem.findChildren();
    while (list.hasNext()) {
      TreeNode child = (TreeNode) list.next();
      String tname = child.getName();
      if ("name".equals(tname)) {
        name = child.getBody();
      } else if ("path".equals(tname)) {
        path = child.getBody();
      } else if ("example".equals(tname)) {
        // Ignore <example> element: Bugzilla 33538
      } else if ("tag-extension".equals(tname)) {
        // Ignore <tag-extension> element: Bugzilla 33538
      } else if ("icon".equals(tname)
          || "display-name".equals(tname)
          || "description".equals(tname)) {
        // Ignore these elements: Bugzilla 38015
      } else {
        if (log.isWarnEnabled()) {
          log.warn(Localizer.getMessage("jsp.warning.unknown.element.in.tagfile", tname));
        }
      }
    }

    if (path.startsWith("/META-INF/tags")) {
      // Tag file packaged in JAR
      // See https://issues.apache.org/bugzilla/show_bug.cgi?id=46471
      // This needs to be removed once all the broken code that depends on
      // it has been removed
      ctxt.setTagFileJarUrl(path, jarFileUrl);
    } else if (!path.startsWith("/WEB-INF/tags")) {
      err.jspError("jsp.error.tagfile.illegalPath", path);
    }

    TagInfo tagInfo =
        TagFileProcessor.parseTagFileDirectives(parserController, name, path, jarFileUrl, this);
    return new TagFileInfo(name, path, tagInfo);
  }
示例#12
0
  /*
   * Keep processing order in sync with o.a.c.startup.TldConfig
   *
   * This supports a Tomcat-specific extension to the TLD search
   * order defined in the JSP spec. It allows tag libraries packaged as JAR
   * files to be shared by web applications by simply dropping them in a
   * location that all web applications have access to (e.g.,
   * <CATALINA_HOME>/lib). It also supports some of the weird and
   * wonderful arrangements present when Tomcat gets embedded.
   *
   */
  private synchronized void init() throws JasperException {
    if (initialized) return;
    try {
      tldScanWebXml();
      tldScanResourcePaths(WEB_INF);

      JarScanner jarScanner = JarScannerFactory.getJarScanner(ctxt);
      if (jarScanner != null) {
        jarScanner.scan(
            ctxt,
            Thread.currentThread().getContextClassLoader(),
            new TldJarScannerCallback(),
            noTldJars);
      }

      initialized = true;
    } catch (Exception ex) {
      throw new JasperException(
          Localizer.getMessage("jsp.error.internal.tldinit", ex.getMessage()), ex);
    }
  }
示例#13
0
  String[] createInitParam(TreeNode elem) {
    String[] initParam = new String[2];

    Iterator list = elem.findChildren();
    while (list.hasNext()) {
      TreeNode element = (TreeNode) list.next();
      String tname = element.getName();
      if ("param-name".equals(tname)) {
        initParam[0] = element.getBody();
      } else if ("param-value".equals(tname)) {
        initParam[1] = element.getBody();
      } else if ("description".equals(tname)) {
        // Do nothing
      } else {
        if (log.isWarnEnabled()) {
          log.warn(Localizer.getMessage("jsp.warning.unknown.element.in.initParam", tname));
        }
      }
    }
    return initParam;
  }
示例#14
0
  TagVariableInfo createVariable(TreeNode elem) {
    String nameGiven = null;
    String nameFromAttribute = null;
    String className = "java.lang.String";
    boolean declare = true;
    int scope = VariableInfo.NESTED;

    Iterator list = elem.findChildren();
    while (list.hasNext()) {
      TreeNode element = (TreeNode) list.next();
      String tname = element.getName();
      if ("name-given".equals(tname)) nameGiven = element.getBody();
      else if ("name-from-attribute".equals(tname)) nameFromAttribute = element.getBody();
      else if ("variable-class".equals(tname)) className = element.getBody();
      else if ("declare".equals(tname)) {
        String s = element.getBody();
        if (s != null) declare = JspUtil.booleanValue(s);
      } else if ("scope".equals(tname)) {
        String s = element.getBody();
        if (s != null) {
          if ("NESTED".equals(s)) {
            scope = VariableInfo.NESTED;
          } else if ("AT_BEGIN".equals(s)) {
            scope = VariableInfo.AT_BEGIN;
          } else if ("AT_END".equals(s)) {
            scope = VariableInfo.AT_END;
          }
        }
      } else if ("description".equals(tname)
          || // Ignored elements
          false) {
      } else {
        if (log.isWarnEnabled()) {
          log.warn(Localizer.getMessage("jsp.warning.unknown.element.in.variable", tname));
        }
      }
    }
    return new TagVariableInfo(nameGiven, nameFromAttribute, className, declare, scope);
  }
示例#15
0
  public void start() {
    if (enabled) return;
    enabled = true;

    if (timer != null) {
      timer.cancel();
    }
    timer = new Timer();
    timer.schedule(
        new TimerTask() {
          @Override
          public void run() {
            stop();
            ScanAndDataMode.getInstance(context).start();
          }
        },
        makeBeaconPeriod());
    wifiHelper.setWifiEnabled(false);
    wifiHelper.setSoftApEnabled(true);

    // Magic
    Localizer.localize();
  }
示例#16
0
  private TagLibraryValidator createValidator(TreeNode elem) throws JasperException {

    String validatorClass = null;
    Map initParams = new Hashtable();

    Iterator list = elem.findChildren();
    while (list.hasNext()) {
      TreeNode element = (TreeNode) list.next();
      String tname = element.getName();
      if ("validator-class".equals(tname)) validatorClass = element.getBody();
      else if ("init-param".equals(tname)) {
        String[] initParam = createInitParam(element);
        initParams.put(initParam[0], initParam[1]);
      } else if ("description".equals(tname)
          || // Ignored elements
          false) {
      } else {
        if (log.isWarnEnabled()) {
          log.warn(Localizer.getMessage("jsp.warning.unknown.element.in.validator", tname));
        }
      }
    }

    TagLibraryValidator tlv = null;
    if (validatorClass != null && !validatorClass.equals("")) {
      try {
        Class tlvClass = ctxt.getClassLoader().loadClass(validatorClass);
        tlv = (TagLibraryValidator) tlvClass.newInstance();
      } catch (Exception e) {
        err.jspError("jsp.error.tlvclass.instantiation", validatorClass, e);
      }
    }
    if (tlv != null) {
      tlv.setInitParameters(initParams);
    }
    return tlv;
  }
示例#17
0
 @Test
 public void shouldUseCapitalizedNoSpaceKeyToFindStringLocalization() throws Exception {
   when(localizer.localize(anyString(), anyVararg())).thenReturn("helped!");
   String s = "Help me";
   assertThat(LocalizedMessage.string(s).localize(localizer), is("helped!"));
 }
示例#18
0
  /**
   * Compile the jsp file into equivalent servlet in .java file
   *
   * @return a smap for the current JSP page, if one is generated, null otherwise
   */
  protected String[] generateJava() throws Exception {

    String[] smapStr = null;

    long t1, t2, t3, t4;

    t1 = t2 = t3 = t4 = 0;

    if (log.isDebugEnabled()) {
      t1 = System.currentTimeMillis();
    }

    // Setup page info area
    pageInfo =
        new PageInfo(new BeanRepository(ctxt.getClassLoader(), errDispatcher), ctxt.getJspFile());

    JspConfig jspConfig = options.getJspConfig();
    JspConfig.JspProperty jspProperty = jspConfig.findJspProperty(ctxt.getJspFile());

    /*
     * If the current uri is matched by a pattern specified in a
     * jsp-property-group in web.xml, initialize pageInfo with those
     * properties.
     */
    if (jspProperty.isELIgnored() != null) {
      pageInfo.setELIgnored(JspUtil.booleanValue(jspProperty.isELIgnored()));
    }
    if (jspProperty.isScriptingInvalid() != null) {
      pageInfo.setScriptingInvalid(JspUtil.booleanValue(jspProperty.isScriptingInvalid()));
    }
    if (jspProperty.getIncludePrelude() != null) {
      pageInfo.setIncludePrelude(jspProperty.getIncludePrelude());
    }
    if (jspProperty.getIncludeCoda() != null) {
      pageInfo.setIncludeCoda(jspProperty.getIncludeCoda());
    }
    if (jspProperty.isDeferedSyntaxAllowedAsLiteral() != null) {
      pageInfo.setDeferredSyntaxAllowedAsLiteral(
          JspUtil.booleanValue(jspProperty.isDeferedSyntaxAllowedAsLiteral()));
    }
    if (jspProperty.isTrimDirectiveWhitespaces() != null) {
      pageInfo.setTrimDirectiveWhitespaces(
          JspUtil.booleanValue(jspProperty.isTrimDirectiveWhitespaces()));
    }
    // Default ContentType processing is deferred until after the page has
    // been parsed
    if (jspProperty.getBuffer() != null) {
      pageInfo.setBufferValue(jspProperty.getBuffer(), null, errDispatcher);
    }
    if (jspProperty.isErrorOnUndeclaredNamespace() != null) {
      pageInfo.setErrorOnUndeclaredNamespace(
          JspUtil.booleanValue(jspProperty.isErrorOnUndeclaredNamespace()));
    }
    if (ctxt.isTagFile()) {
      try {
        double libraryVersion =
            Double.parseDouble(ctxt.getTagInfo().getTagLibrary().getRequiredVersion());
        if (libraryVersion < 2.0) {
          pageInfo.setIsELIgnored("true", null, errDispatcher, true);
        }
        if (libraryVersion < 2.1) {
          pageInfo.setDeferredSyntaxAllowedAsLiteral("true", null, errDispatcher, true);
        }
      } catch (NumberFormatException ex) {
        errDispatcher.jspError(ex);
      }
    }

    ctxt.checkOutputDir();
    String javaFileName = ctxt.getServletJavaFileName();

    ServletWriter writer = null;
    try {
      /*
       * The setting of isELIgnored changes the behaviour of the parser
       * in subtle ways. To add to the 'fun', isELIgnored can be set in
       * any file that forms part of the translation unit so setting it
       * in a file included towards the end of the translation unit can
       * change how the parser should have behaved when parsing content
       * up to the point where isELIgnored was set. Arghh!
       * Previous attempts to hack around this have only provided partial
       * solutions. We now use two passes to parse the translation unit.
       * The first just parses the directives and the second parses the
       * whole translation unit once we know how isELIgnored has been set.
       * TODO There are some possible optimisations of this process.
       */
      // Parse the file
      ParserController parserCtl = new ParserController(ctxt, this);

      // Pass 1 - the directives
      Node.Nodes directives = parserCtl.parseDirectives(ctxt.getJspFile());
      Validator.validateDirectives(this, directives);

      // Pass 2 - the whole translation unit
      pageNodes = parserCtl.parse(ctxt.getJspFile());

      // Leave this until now since it can only be set once - bug 49726
      if (pageInfo.getContentType() == null && jspProperty.getDefaultContentType() != null) {
        pageInfo.setContentType(jspProperty.getDefaultContentType());
      }

      if (ctxt.isPrototypeMode()) {
        // generate prototype .java file for the tag file
        writer = setupContextWriter(javaFileName);
        Generator.generate(writer, this, pageNodes);
        writer.close();
        writer = null;
        return null;
      }

      // Validate and process attributes - don't re-validate the
      // directives we validated in pass 1
      Validator.validateExDirectives(this, pageNodes);

      if (log.isDebugEnabled()) {
        t2 = System.currentTimeMillis();
      }

      // Collect page info
      Collector.collect(this, pageNodes);

      // Compile (if necessary) and load the tag files referenced in
      // this compilation unit.
      tfp = new TagFileProcessor();
      tfp.loadTagFiles(this, pageNodes);

      if (log.isDebugEnabled()) {
        t3 = System.currentTimeMillis();
      }

      // Determine which custom tag needs to declare which scripting vars
      ScriptingVariabler.set(pageNodes, errDispatcher);

      // Optimizations by Tag Plugins
      TagPluginManager tagPluginManager = options.getTagPluginManager();
      tagPluginManager.apply(pageNodes, errDispatcher, pageInfo);

      // Optimization: concatenate contiguous template texts.
      TextOptimizer.concatenate(this, pageNodes);

      // Generate static function mapper codes.
      ELFunctionMapper.map(pageNodes);

      // generate servlet .java file
      writer = setupContextWriter(javaFileName);
      Generator.generate(writer, this, pageNodes);
      writer.close();
      writer = null;

      // The writer is only used during the compile, dereference
      // it in the JspCompilationContext when done to allow it
      // to be GC'd and save memory.
      ctxt.setWriter(null);

      if (log.isDebugEnabled()) {
        t4 = System.currentTimeMillis();
        log.debug(
            "Generated "
                + javaFileName
                + " total="
                + (t4 - t1)
                + " generate="
                + (t4 - t3)
                + " validate="
                + (t2 - t1));
      }

    } catch (Exception e) {
      if (writer != null) {
        try {
          writer.close();
          writer = null;
        } catch (Exception e1) {
          // do nothing
        }
      }
      // Remove the generated .java file
      File file = new File(javaFileName);
      if (file.exists()) {
        if (!file.delete()) {
          log.warn(
              Localizer.getMessage(
                  "jsp.warning.compiler.javafile.delete.fail", file.getAbsolutePath()));
        }
      }
      throw e;
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (Exception e2) {
          // do nothing
        }
      }
    }

    // JSR45 Support
    if (!options.isSmapSuppressed()) {
      smapStr = SmapUtil.generateSmap(ctxt, pageNodes);
    }

    // If any proto type .java and .class files was generated,
    // the prototype .java may have been replaced by the current
    // compilation (if the tag file is self referencing), but the
    // .class file need to be removed, to make sure that javac would
    // generate .class again from the new .java file just generated.
    tfp.removeProtoTypeFiles(ctxt.getClassFileName());

    return smapStr;
  }
示例#19
0
  /*
   * @param ctxt The JSP compilation context @param uri The TLD's uri @param
   * in The TLD's input stream @param jarFileUrl The JAR file containing the
   * TLD, or null if the tag library is not packaged in a JAR
   */
  private void parseTLD(JspCompilationContext ctxt, String uri, InputStream in, URL jarFileUrl)
      throws JasperException {
    Vector tagVector = new Vector();
    Vector tagFileVector = new Vector();
    Hashtable functionTable = new Hashtable();

    // Create an iterator over the child elements of our <taglib> element
    ParserUtils pu = new ParserUtils();
    TreeNode tld = pu.parseXMLDocument(uri, in);

    // Check to see if the <taglib> root element contains a 'version'
    // attribute, which was added in JSP 2.0 to replace the <jsp-version>
    // subelement
    this.jspversion = tld.findAttribute("version");

    // Process each child element of our <taglib> element
    Iterator list = tld.findChildren();

    while (list.hasNext()) {
      TreeNode element = (TreeNode) list.next();
      String tname = element.getName();

      if ("tlibversion".equals(tname) // JSP 1.1
          || "tlib-version".equals(tname)) { // JSP 1.2
        this.tlibversion = element.getBody();
      } else if ("jspversion".equals(tname) || "jsp-version".equals(tname)) {
        this.jspversion = element.getBody();
      } else if ("shortname".equals(tname) || "short-name".equals(tname))
        this.shortname = element.getBody();
      else if ("uri".equals(tname)) this.urn = element.getBody();
      else if ("info".equals(tname) || "description".equals(tname)) this.info = element.getBody();
      else if ("validator".equals(tname)) this.tagLibraryValidator = createValidator(element);
      else if ("tag".equals(tname)) tagVector.addElement(createTagInfo(element, jspversion));
      else if ("tag-file".equals(tname)) {
        TagFileInfo tagFileInfo = createTagFileInfo(element, uri, jarFileUrl);
        tagFileVector.addElement(tagFileInfo);
      } else if ("function".equals(tname)) { // JSP2.0
        FunctionInfo funcInfo = createFunctionInfo(element);
        String funcName = funcInfo.getName();
        if (functionTable.containsKey(funcName)) {
          err.jspError("jsp.error.tld.fn.duplicate.name", funcName, uri);
        }
        functionTable.put(funcName, funcInfo);
      } else if ("display-name".equals(tname)
          || // Ignored elements
          "small-icon".equals(tname)
          || "large-icon".equals(tname)
          || "listener".equals(tname)) {;
      } else if ("taglib-extension".equals(tname)) {
        // Recognized but ignored
      } else {
        if (log.isWarnEnabled()) {
          log.warn(Localizer.getMessage("jsp.warning.unknown.element.in.taglib", tname));
        }
      }
    }

    if (tlibversion == null) {
      err.jspError("jsp.error.tld.mandatory.element.missing", "tlib-version", uri);
    }
    if (jspversion == null) {
      err.jspError("jsp.error.tld.mandatory.element.missing", "jsp-version", uri);
    }

    this.tags = new TagInfo[tagVector.size()];
    tagVector.copyInto(this.tags);

    this.tagFiles = new TagFileInfo[tagFileVector.size()];
    tagFileVector.copyInto(this.tagFiles);

    this.functions = new FunctionInfo[functionTable.size()];
    int i = 0;
    Enumeration enumeration = functionTable.elements();
    while (enumeration.hasMoreElements()) {
      this.functions[i++] = (FunctionInfo) enumeration.nextElement();
    }
  }
示例#20
0
 @Test
 public void shouldUseTheProvidedLocalizerToLocalize() {
   when(localizer.localize(anyString(), anyVararg())).thenReturn("whateva");
   assertThat(LocalizedMessage.string("me").localize(localizer), is("whateva"));
 }
示例#21
0
  private TagInfo createTagInfo(TreeNode elem, String jspVersion) throws JasperException {

    String tagName = null;
    String tagClassName = null;
    String teiClassName = null;

    /*
     * Default body content for JSP 1.2 tag handlers (<body-content> has
     * become mandatory in JSP 2.0, because the default would be invalid for
     * simple tag handlers)
     */
    String bodycontent = "JSP";

    String info = null;
    String displayName = null;
    String smallIcon = null;
    String largeIcon = null;
    boolean dynamicAttributes = false;

    Vector attributeVector = new Vector();
    Vector variableVector = new Vector();
    Iterator list = elem.findChildren();
    while (list.hasNext()) {
      TreeNode element = (TreeNode) list.next();
      String tname = element.getName();

      if ("name".equals(tname)) {
        tagName = element.getBody();
      } else if ("tagclass".equals(tname) || "tag-class".equals(tname)) {
        tagClassName = element.getBody();
      } else if ("teiclass".equals(tname) || "tei-class".equals(tname)) {
        teiClassName = element.getBody();
      } else if ("bodycontent".equals(tname) || "body-content".equals(tname)) {
        bodycontent = element.getBody();
      } else if ("display-name".equals(tname)) {
        displayName = element.getBody();
      } else if ("small-icon".equals(tname)) {
        smallIcon = element.getBody();
      } else if ("large-icon".equals(tname)) {
        largeIcon = element.getBody();
      } else if ("icon".equals(tname)) {
        TreeNode icon = element.findChild("small-icon");
        if (icon != null) {
          smallIcon = icon.getBody();
        }
        icon = element.findChild("large-icon");
        if (icon != null) {
          largeIcon = icon.getBody();
        }
      } else if ("info".equals(tname) || "description".equals(tname)) {
        info = element.getBody();
      } else if ("variable".equals(tname)) {
        variableVector.addElement(createVariable(element));
      } else if ("attribute".equals(tname)) {
        attributeVector.addElement(createAttribute(element, jspVersion));
      } else if ("dynamic-attributes".equals(tname)) {
        dynamicAttributes = JspUtil.booleanValue(element.getBody());
      } else if ("example".equals(tname)) {
        // Ignored elements
      } else if ("tag-extension".equals(tname)) {
        // Ignored
      } else {
        if (log.isWarnEnabled()) {
          log.warn(Localizer.getMessage("jsp.warning.unknown.element.in.tag", tname));
        }
      }
    }

    TagExtraInfo tei = null;
    if (teiClassName != null && !teiClassName.equals("")) {
      try {
        Class teiClass = ctxt.getClassLoader().loadClass(teiClassName);
        tei = (TagExtraInfo) teiClass.newInstance();
      } catch (Exception e) {
        err.jspError("jsp.error.teiclass.instantiation", teiClassName, e);
      }
    }

    TagAttributeInfo[] tagAttributeInfo = new TagAttributeInfo[attributeVector.size()];
    attributeVector.copyInto(tagAttributeInfo);

    TagVariableInfo[] tagVariableInfos = new TagVariableInfo[variableVector.size()];
    variableVector.copyInto(tagVariableInfos);

    TagInfo taginfo =
        new TagInfo(
            tagName,
            tagClassName,
            bodycontent,
            info,
            this,
            tei,
            tagAttributeInfo,
            displayName,
            smallIcon,
            largeIcon,
            tagVariableInfos,
            dynamicAttributes);
    return taginfo;
  }
示例#22
0
  private void processWebDotXml() {

    // Very, very unlikely but just in case...
    if (ctxt.getEffectiveMajorVersion() < 2) {
      defaultIsELIgnored = "true";
      defaultDeferedSyntaxAllowedAsLiteral = "true";
      return;
    }
    if (ctxt.getEffectiveMajorVersion() == 2) {
      if (ctxt.getEffectiveMinorVersion() < 5) {
        defaultDeferedSyntaxAllowedAsLiteral = "true";
      }
      if (ctxt.getEffectiveMinorVersion() < 4) {
        defaultIsELIgnored = "true";
        return;
      }
    }

    JspConfigDescriptor jspConfig = ctxt.getJspConfigDescriptor();

    if (jspConfig == null) {
      return;
    }

    jspProperties = new Vector<>();
    Collection<JspPropertyGroupDescriptor> jspPropertyGroups = jspConfig.getJspPropertyGroups();

    for (JspPropertyGroupDescriptor jspPropertyGroup : jspPropertyGroups) {

      Collection<String> urlPatterns = jspPropertyGroup.getUrlPatterns();

      if (urlPatterns.size() == 0) {
        continue;
      }

      JspProperty property =
          new JspProperty(
              jspPropertyGroup.getIsXml(),
              jspPropertyGroup.getElIgnored(),
              jspPropertyGroup.getScriptingInvalid(),
              jspPropertyGroup.getPageEncoding(),
              jspPropertyGroup.getIncludePreludes(),
              jspPropertyGroup.getIncludeCodas(),
              jspPropertyGroup.getDeferredSyntaxAllowedAsLiteral(),
              jspPropertyGroup.getTrimDirectiveWhitespaces(),
              jspPropertyGroup.getDefaultContentType(),
              jspPropertyGroup.getBuffer(),
              jspPropertyGroup.getErrorOnUndeclaredNamespace());

      // Add one JspPropertyGroup for each URL Pattern.  This makes
      // the matching logic easier.
      for (String urlPattern : urlPatterns) {
        String path = null;
        String extension = null;

        if (urlPattern.indexOf('*') < 0) {
          // Exact match
          path = urlPattern;
        } else {
          int i = urlPattern.lastIndexOf('/');
          String file;
          if (i >= 0) {
            path = urlPattern.substring(0, i + 1);
            file = urlPattern.substring(i + 1);
          } else {
            file = urlPattern;
          }

          // pattern must be "*", or of the form "*.jsp"
          if (file.equals("*")) {
            extension = "*";
          } else if (file.startsWith("*.")) {
            extension = file.substring(file.indexOf('.') + 1);
          }

          // The url patterns are reconstructed as the following:
          // path != null, extension == null:  / or /foo/bar.ext
          // path == null, extension != null:  *.ext
          // path != null, extension == "*":   /foo/*
          boolean isStar = "*".equals(extension);
          if ((path == null && (extension == null || isStar)) || (path != null && !isStar)) {
            if (log.isWarnEnabled()) {
              log.warn(
                  Localizer.getMessage("jsp.warning.bad.urlpattern.propertygroup", urlPattern));
            }
            continue;
          }
        }

        JspPropertyGroup propertyGroup = new JspPropertyGroup(path, extension, property);

        jspProperties.addElement(propertyGroup);
      }
    }
  }
示例#23
0
  /*
   * Returns the next unquoted character and sets the lastChEscaped flag to
   * indicate if it was quoted/escaped or not.
   * &apos; is always unquoted to '
   * &quot; is always unquoted to "
   * \" is always unquoted to "
   * \' is always unquoted to '
   * \\ is always unquoted to \
   * \$ is unquoted to $ if EL is not being ignored
   * \# is unquoted to # if EL is not being ignored
   * <\% is always unquoted to <%
   * %\> is always unquoted to %>
   */
  private char nextChar() {
    lastChEscaped = false;
    char ch = input.charAt(i);

    if (ch == '&') {
      if (i + 5 < size
          && input.charAt(i + 1) == 'a'
          && input.charAt(i + 2) == 'p'
          && input.charAt(i + 3) == 'o'
          && input.charAt(i + 4) == 's'
          && input.charAt(i + 5) == ';') {
        ch = '\'';
        i += 6;
      } else if (i + 5 < size
          && input.charAt(i + 1) == 'q'
          && input.charAt(i + 2) == 'u'
          && input.charAt(i + 3) == 'o'
          && input.charAt(i + 4) == 't'
          && input.charAt(i + 5) == ';') {
        ch = '\"';
        i += 6;
      } else {
        ++i;
      }
    } else if (ch == '\\' && i + 1 < size) {
      ch = input.charAt(i + 1);
      if (ch == '\\'
          || ch == '\"'
          || ch == '\''
          || (!isELIgnored && (ch == '$' || (!isDeferredSyntaxAllowedAsLiteral && ch == '#')))) {
        i += 2;
        lastChEscaped = true;
      } else {
        ch = '\\';
        ++i;
      }
    } else if (ch == '<'
        && (i + 2 < size)
        && input.charAt(i + 1) == '\\'
        && input.charAt(i + 2) == '%') {
      // Note this is a hack since nextChar only returns a single char
      // It is safe since <% does not require special treatment for EL
      // or for literals
      result.append('<');
      i += 3;
      return '%';
    } else if (ch == '%'
        && i + 2 < size
        && input.charAt(i + 1) == '\\'
        && input.charAt(i + 2) == '>') {
      // Note this is a hack since nextChar only returns a single char
      // It is safe since %> does not require special treatment for EL
      // or for literals
      result.append('%');
      i += 3;
      return '>';
    } else if (ch == quote && strict) {
      String msg = Localizer.getMessage("jsp.error.attribute.noescape", input, "" + quote);
      throw new IllegalArgumentException(msg);
    } else {
      ++i;
    }

    return ch;
  }
示例#24
0
  TagAttributeInfo createAttribute(TreeNode elem, String jspVersion) {
    String name = null;
    String type = null;
    String expectedType = null;
    String methodSignature = null;
    boolean required = false,
        rtexprvalue = false,
        reqTime = false,
        isFragment = false,
        deferredValue = false,
        deferredMethod = false;

    Iterator list = elem.findChildren();
    while (list.hasNext()) {
      TreeNode element = (TreeNode) list.next();
      String tname = element.getName();

      if ("name".equals(tname)) {
        name = element.getBody();
      } else if ("required".equals(tname)) {
        String s = element.getBody();
        if (s != null) required = JspUtil.booleanValue(s);
      } else if ("rtexprvalue".equals(tname)) {
        String s = element.getBody();
        if (s != null) rtexprvalue = JspUtil.booleanValue(s);
      } else if ("type".equals(tname)) {
        type = element.getBody();
        if ("1.2".equals(jspVersion)
            && (type.equals("Boolean")
                || type.equals("Byte")
                || type.equals("Character")
                || type.equals("Double")
                || type.equals("Float")
                || type.equals("Integer")
                || type.equals("Long")
                || type.equals("Object")
                || type.equals("Short")
                || type.equals("String"))) {
          type = "java.lang." + type;
        }
      } else if ("fragment".equals(tname)) {
        String s = element.getBody();
        if (s != null) {
          isFragment = JspUtil.booleanValue(s);
        }
      } else if ("deferred-value".equals(tname)) {
        deferredValue = true;
        type = "javax.el.ValueExpression";
        TreeNode child = element.findChild("type");
        if (child != null) {
          expectedType = child.getBody();
          if (expectedType != null) {
            expectedType = expectedType.trim();
          }
        } else {
          expectedType = "java.lang.Object";
        }
      } else if ("deferred-method".equals(tname)) {
        deferredMethod = true;
        type = "javax.el.MethodExpression";
        TreeNode child = element.findChild("method-signature");
        if (child != null) {
          methodSignature = child.getBody();
          if (methodSignature != null) {
            methodSignature = methodSignature.trim();
          }
        } else {
          methodSignature = "java.lang.Object method()";
        }
      } else if ("description".equals(tname)
          || // Ignored elements
          false) {;
      } else {
        if (log.isWarnEnabled()) {
          log.warn(Localizer.getMessage("jsp.warning.unknown.element.in.attribute", tname));
        }
      }
    }

    if (isFragment) {
      /*
       * According to JSP.C-3 ("TLD Schema Element Structure - tag"),
       * 'type' and 'rtexprvalue' must not be specified if 'fragment' has
       * been specified (this will be enforced by validating parser).
       * Also, if 'fragment' is TRUE, 'type' is fixed at
       * javax.servlet.jsp.tagext.JspFragment, and 'rtexprvalue' is fixed
       * at true. See also JSP.8.5.2.
       */
      type = "javax.servlet.jsp.tagext.JspFragment";
      rtexprvalue = true;
    }

    if (!rtexprvalue && type == null) {
      // According to JSP spec, for static values (those determined at
      // translation time) the type is fixed at java.lang.String.
      type = "java.lang.String";
    }

    return new TagAttributeInfo(
        name,
        required,
        type,
        rtexprvalue,
        isFragment,
        null,
        deferredValue,
        deferredMethod,
        expectedType,
        methodSignature);
  }
示例#25
0
  /** Compile the servlet from .java file to .class file */
  @Override
  protected void generateClass(String[] smap)
      throws FileNotFoundException, JasperException, Exception {

    long t1 = 0;
    if (log.isDebugEnabled()) {
      t1 = System.currentTimeMillis();
    }

    String javaEncoding = ctxt.getOptions().getJavaEncoding();
    String javaFileName = ctxt.getServletJavaFileName();
    String classpath = ctxt.getClassPath();

    String sep = System.getProperty("path.separator");

    StringBuilder errorReport = new StringBuilder();

    StringBuilder info = new StringBuilder();
    info.append("Compile: javaFileName=" + javaFileName + "\n");
    info.append("    classpath=" + classpath + "\n");

    // Start capturing the System.err output for this thread
    SystemLogHandler.setThread();

    // Initializing javac task
    getProject();
    Javac javac = (Javac) project.createTask("javac");

    // Initializing classpath
    Path path = new Path(project);
    path.setPath(System.getProperty("java.class.path"));
    info.append("    cp=" + System.getProperty("java.class.path") + "\n");
    StringTokenizer tokenizer = new StringTokenizer(classpath, sep);
    while (tokenizer.hasMoreElements()) {
      String pathElement = tokenizer.nextToken();
      File repository = new File(pathElement);
      path.setLocation(repository);
      info.append("    cp=" + repository + "\n");
    }

    if (log.isDebugEnabled())
      log.debug("Using classpath: " + System.getProperty("java.class.path") + sep + classpath);

    // Initializing sourcepath
    Path srcPath = new Path(project);
    srcPath.setLocation(options.getScratchDir());

    info.append("    work dir=" + options.getScratchDir() + "\n");

    // Initialize and set java extensions
    String exts = System.getProperty("java.ext.dirs");
    if (exts != null) {
      Path extdirs = new Path(project);
      extdirs.setPath(exts);
      javac.setExtdirs(extdirs);
      info.append("    extension dir=" + exts + "\n");
    }

    // Add endorsed directories if any are specified and we're forking
    // See Bugzilla 31257
    if (ctxt.getOptions().getFork()) {
      String endorsed = System.getProperty("java.endorsed.dirs");
      if (endorsed != null) {
        Javac.ImplementationSpecificArgument endorsedArg = javac.createCompilerArg();
        endorsedArg.setLine("-J-Djava.endorsed.dirs=" + quotePathList(endorsed));
        info.append("    endorsed dir=" + quotePathList(endorsed) + "\n");
      } else {
        info.append("    no endorsed dirs specified\n");
      }
    }

    // Configure the compiler object
    javac.setEncoding(javaEncoding);
    javac.setClasspath(path);
    javac.setDebug(ctxt.getOptions().getClassDebugInfo());
    javac.setSrcdir(srcPath);
    javac.setTempdir(options.getScratchDir());
    javac.setOptimize(!ctxt.getOptions().getClassDebugInfo());
    javac.setFork(ctxt.getOptions().getFork());
    info.append("    srcDir=" + srcPath + "\n");

    // Set the Java compiler to use
    if (options.getCompiler() != null) {
      javac.setCompiler(options.getCompiler());
      info.append("    compiler=" + options.getCompiler() + "\n");
    }

    if (options.getCompilerTargetVM() != null) {
      javac.setTarget(options.getCompilerTargetVM());
      info.append("   compilerTargetVM=" + options.getCompilerTargetVM() + "\n");
    }

    if (options.getCompilerSourceVM() != null) {
      javac.setSource(options.getCompilerSourceVM());
      info.append("   compilerSourceVM=" + options.getCompilerSourceVM() + "\n");
    }

    // Build includes path
    PatternSet.NameEntry includes = javac.createInclude();

    includes.setName(ctxt.getJavaPath());
    info.append("    include=" + ctxt.getJavaPath() + "\n");

    BuildException be = null;

    try {
      if (ctxt.getOptions().getFork()) {
        javac.execute();
      } else {
        synchronized (javacLock) {
          javac.execute();
        }
      }
    } catch (BuildException e) {
      be = e;
      log.error(Localizer.getMessage("jsp.error.javac"), e);
      log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString());
    }

    errorReport.append(logger.getReport());

    // Stop capturing the System.err output for this thread
    String errorCapture = SystemLogHandler.unsetThread();
    if (errorCapture != null) {
      errorReport.append(Constants.NEWLINE);
      errorReport.append(errorCapture);
    }

    if (!ctxt.keepGenerated()) {
      File javaFile = new File(javaFileName);
      javaFile.delete();
    }

    if (be != null) {
      String errorReportString = errorReport.toString();
      log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString));
      JavacErrorDetail[] javacErrors =
          ErrorDispatcher.parseJavacErrors(errorReportString, javaFileName, pageNodes);
      if (javacErrors != null) {
        errDispatcher.javacError(javacErrors);
      } else {
        errDispatcher.javacError(errorReportString, be);
      }
    }

    if (log.isDebugEnabled()) {
      long t2 = System.currentTimeMillis();
      log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
    }

    logger = null;
    project = null;

    if (ctxt.isPrototypeMode()) {
      return;
    }

    // JSR45 Support
    if (!options.isSmapSuppressed()) {
      SmapUtil.installSmap(smap);
    }
  }