Esempio n. 1
0
  /**
   * Overridden to get use apply the XLST transformation on the content.
   *
   * @throws TransformerException
   */
  public void appendToResponse(WOResponse response, WOContext context) {
    start = System.currentTimeMillis();
    current = start;
    if (isEnabled()) {
      WOResponse newResponse = new WOResponse();
      newResponse.setContentEncoding(response.contentEncoding());

      super.appendToResponse(newResponse, context);

      if (log.isDebugEnabled()) {
        String contentString = newResponse.contentString();
        log.debug("Converting content string:\n" + contentString);
      }

      try {
        NSData data = transform(transformer(), newResponse.content());
        if (hasBinding("data") && canSetValueForBinding("data")) {
          setValueForBinding(data, "data");
        }
        if (hasBinding("stream") && canSetValueForBinding("stream")) {
          setValueForBinding(data.stream(), "stream");
        }
        response.appendContentData(data);
      } catch (TransformerException e) {
        throw NSForwardException._runtimeExceptionForThrowable(e);
      }
    } else {
      super.appendToResponse(response, context);
    }
    log.debug("Total: " + (System.currentTimeMillis() - start));
    start = System.currentTimeMillis();
  }
Esempio n. 2
0
    public synchronized Transformer getTransformer(String framework, String filename) {
      if (filename == null || filename.length() == 0) {
        throw new IllegalArgumentException("filename cannot be null or empty");
      }
      String key = framework + "-" + filename;

      Templates t = (Templates) pool.getTemplates().get(key);
      String s = null;

      if (t == null) {
        try {
          WOApplication app = WOApplication.application();
          WOResourceManager rm = app.resourceManager();

          TransformerFactory fac = TransformerFactory.newInstance();

          log.debug("creating template for file " + filename + " in framework " + framework);
          InputStream is = rm.inputStreamForResourceNamed(filename, framework, null);
          if (is == null) {
            log.debug("trying with framework = null");
            is = rm.inputStreamForResourceNamed(filename, null, null);
            if (is == null) {
              throw new IllegalArgumentException("inputStream is null");
            }
          }
          if (is.available() == 0) {
            throw new IllegalArgumentException(
                "InputStream has 0 bytes available, cannot read xsl file!");
          }
          s = ERXFileUtilities.stringFromInputStream(is);
          s = templateParser.parseTemplateWithObject(s, "@@", app);
          t = fac.newTemplates(new StreamSource(new ByteArrayInputStream(s.getBytes())));

          if (app.isCachingEnabled()) {
            templates.put(key, t);
          }
        } catch (IOException e1) {
          throw NSForwardException._runtimeExceptionForThrowable(e1);
        } catch (TransformerConfigurationException tce) {
          log.error("could not create template " + tce.getLocationAsString(), tce);
          log.error("  cause", tce.getCause());
          if (tce.getCause() != null && tce.getCause() instanceof org.xml.sax.SAXParseException) {
            org.xml.sax.SAXParseException e = (org.xml.sax.SAXParseException) tce.getCause();
            log.error(
                "SAXParseException: line " + e.getLineNumber() + ", column " + e.getColumnNumber());
          }
          log.error("this is the incorrect xsl:>>>" + s + "<<<");
          return null;
        }
      }

      try {
        return t.newTransformer();
      } catch (TransformerConfigurationException tce) {
        log.error("could not create template " + tce.getLocationAsString(), tce);
        log.error("  cause", tce.getCause());
        return null;
      }
    }
 /**
  * Returns the corresponding controller instance.
  *
  * @param <T> the type of controller to return
  * @param controllerClass the controller class to lookup
  * @param request the current request
  * @param context the current context
  * @return the created controller
  */
 public <T extends ERXRouteController> T controller(
     Class<T> controllerClass, WORequest request, WOContext context) {
   try {
     T controller = controllerClass.getConstructor(WORequest.class).newInstance(request);
     controller._setRequestHandler(this);
     controller._setContext(context);
     return controller;
   } catch (Exception e) {
     throw NSForwardException._runtimeExceptionForThrowable(e);
   }
 }
Esempio n. 4
0
  private void doCreateDummyData() {
    try {
      log.info("load");

      String wordFile = ERXFileUtilities.stringFromFile(new File("/usr/share/dict/words"));
      words = NSArray.componentsSeparatedByString(wordFile, "\n");
      log.info("loaded words: {}", words.count());

      int MAX = 100;
      int MAX_ASSETS = MAX * 10;

      for (int i = 0; i < MAX; i++) {
        Tag tag = Tag.clazz.createAndInsertObject(ec);
        tag.setName(randomWord());
        tags.addObject(tag);
      }
      log.info("created tags: {}", tags.count());

      for (int i = 0; i < MAX; i++) {
        AssetGroup group = AssetGroup.clazz.createAndInsertObject(ec);
        group.setName(randomWord());
        groups.addObject(group);
      }
      log.info("created groups: {}", groups.count());

      for (int i = 0; i < MAX_ASSETS; i++) {
        Asset asset = Asset.clazz.createAndInsertObject(ec);
        asset.setAssetGroup(randomAssetGroup());
        asset.setCreationDate(randomTime());
        asset.setUserCount((long) randomInt(10000));
        asset.setPrice(randomPrice());

        for (int j = 0; j < 10; j++) {
          asset.addToTags(randomTag());
        }

        asset.setContent(randomText(1000));

        asset.setGenericInfo(randomText(1000));

        assets.addObject(asset);
      }
      log.info("created assets: {}", assets.count());

      ec.saveChanges();
      log.info("fin: {}", words.count());
    } catch (IOException e) {
      throw NSForwardException._runtimeExceptionForThrowable(e);
    }
  }
 @Override
 public Object fireNow(D2WContext c) {
   WOComponent component = ERXWOContext.currentContext().component();
   D2WPage currentPage = ERD2WUtilities.enclosingComponentOfClass(component, D2WPage.class);
   if (ERD2WUtilities.enclosingPageOfClass(currentPage, D2WPage.class) == null) {
     try {
       Class<?> clazz = Class.forName((String) value());
       return clazz.newInstance();
     } catch (Exception e) {
       throw NSForwardException._runtimeExceptionForThrowable(e);
     }
   }
   return null;
 }
Esempio n. 6
0
  private Transformer transformer() {
    Transformer transformer;
    try {
      synchronized (cache) {
        String stylesheet = (String) valueForBinding("stylesheet");
        String framework = (String) valueForBinding("framework");
        NSArray languages = session().languages();
        String key = stylesheet + "-" + framework;
        transformer = (Transformer) cache.get(key);
        if (transformer == null || booleanValueForBinding("nocache")) {
          byte bytes[] =
              application()
                  .resourceManager()
                  .bytesForResourceNamed(stylesheet, framework, languages);
          DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
          documentBuilderFactory.setValidating(false);
          documentBuilderFactory.setNamespaceAware(true);
          DocumentBuilder documentBuilder;
          documentBuilder = documentBuilderFactory.newDocumentBuilder();
          ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
          Document document = documentBuilder.parse(bis);
          Source xslt = new DOMSource(document);
          xslt.setSystemId(key);
          String transformerFactoryName = (String) valueForBinding("transformerFactory");
          String oldTransformerFactoryName =
              System.getProperty("javax.xml.transform.TransformerFactory");
          if (transformerFactoryName != null) {
            System.setProperty("javax.xml.transform.TransformerFactory", transformerFactoryName);
          } else {
            System.setProperty(
                "javax.xml.transform.TransformerFactory",
                "org.apache.xalan.processor.TransformerFactoryImpl");
          }
          TransformerFactory transformerFactory = TransformerFactory.newInstance();
          if (oldTransformerFactoryName != null) {
            System.setProperty("javax.xml.transform.TransformerFactory", oldTransformerFactoryName);
          }
          transformer = transformerFactory.newTransformer(xslt);
          // transformer.setOutputProperty("indent", "no");
          // transformer.setOutputProperty("method", "xml");

          cache.put(key, transformer);
        }
      }
      return transformer;
    } catch (Exception ex) {
      throw NSForwardException._runtimeExceptionForThrowable(ex);
    }
  }
Esempio n. 7
0
  public NSArray theList() {
    NSMutableArray aSortedArray;
    NSArray anUnsortedArray;
    if (_privateList() == null) {
      EODataSource aDataSource = _localDataSource();
      anUnsortedArray = aDataSource.fetchObjects();
      // 81398 sort contents
      aSortedArray = new NSMutableArray(anUnsortedArray);
      try {
        _WOJExtensionsUtil._sortEOsUsingSingleKey(aSortedArray, _localDestinationDisplayKey());
      } catch (NSComparator.ComparisonException e) {
        throw NSForwardException._runtimeExceptionForThrowable(e);
      }

      if (!_localIsMandatory()) {
        aSortedArray.insertObjectAtIndex(_noneString, 0);
      }
      set_privateList(aSortedArray);
    }
    return _privateList();
  }
 protected static NSDictionary _dictionaryFromFile(File file) {
   NSDictionary model = null;
   try {
     model = Services.dictionaryFromFile(file);
     NSArray rules = (NSArray) model.objectForKey("rules");
     Enumeration e = rules.objectEnumerator();
     while (e.hasMoreElements()) {
       NSMutableDictionary dict = (NSMutableDictionary) e.nextElement();
       if ("com.webobjects.directtoweb.Rule".equals(dict.objectForKey("class"))) {
         dict.setObjectForKey("ERD2WExtendedRule", "class");
       }
     }
   } catch (Throwable throwable) {
     NSLog.err.appendln(
         "****** DirectToWeb: Problem reading file " + file + " reason:" + throwable);
     if (NSLog.debugLoggingAllowedForLevelAndGroups(1, 40L)) {
       NSLog.err.appendln("STACKTRACE:");
       NSLog.err.appendln(throwable);
     }
     throw NSForwardException._runtimeExceptionForThrowable(throwable);
   }
   return model;
 }
 /**
  * Overridden to always return the single static clazz instance if possible.
  *
  * @param entity to generate the clazz for
  * @return clazz object for the given entity
  */
 @SuppressWarnings("rawtypes")
 @Override
 public EOEnterpriseObjectClazz classFromEntity(EOEntity entity) {
   EOEnterpriseObjectClazz clazz = null;
   if (entity == null) {
     clazz = newInstanceOfDefaultClazz();
   } else {
     try {
       String className = entity.className();
       if (classNameIsGenericRecord(className)) {
         clazz = newInstanceOfGenericRecordClazz();
       } else {
         try {
           Class klass = Class.forName(className);
           Field field = klass.getDeclaredField("clazz");
           Object obj = field.get(null);
           return (EOEnterpriseObjectClazz) obj;
         } catch (ClassNotFoundException e) {
           // Can't find entity class?
           throw NSForwardException._runtimeExceptionForThrowable(e);
         } catch (NoSuchFieldException e) {
           // Field doesn't exist. Then try to instantiate clazzName
         } catch (IllegalAccessException e) {
           // Field is not public. Try to instantiate clazzName
         }
         String clazzName = clazzNameForEntity(entity);
         clazz = (EOEnterpriseObjectClazz) Class.forName(clazzName).newInstance();
       }
     } catch (InstantiationException ex) {
     } catch (ClassNotFoundException ex) {
     } catch (IllegalAccessException ex) {
     }
   }
   if (clazz == null) return classFromEntity(entity.parentEntity());
   return clazz;
 }
 /**
  * Encodes a dictionary into a string that can be used in a request uri.
  *
  * @param dict dictionary with form values
  * @param separator optional value separator
  */
 public static String queryStringForDictionary(
     NSDictionary<?, ?> dict, String separator, String encoding) {
   if (separator == null) {
     separator = "&";
   }
   StringBuilder sb = new StringBuilder(100);
   if (dict != null) {
     for (Enumeration<?> e = dict.allKeys().objectEnumerator(); e.hasMoreElements(); ) {
       Object key = e.nextElement();
       try {
         sb.append(URLEncoder.encode(key.toString(), encoding));
         sb.append('=');
         sb.append(URLEncoder.encode(dict.objectForKey(key).toString(), encoding));
         if (e.hasMoreElements()) {
           sb.append(separator);
         }
       } catch (UnsupportedEncodingException ex) {
         // yeah right...like this will ever happen
         throw NSForwardException._runtimeExceptionForThrowable(ex);
       }
     }
   }
   return sb.toString();
 }