Exemplo n.º 1
0
  public String transform(
      ThemeDisplay themeDisplay, Map<String, Object> contextObjects, String script, String langType)
      throws Exception {

    if (Validator.isNull(langType)) {
      return null;
    }

    long companyId = 0;
    long companyGroupId = 0;
    long scopeGroupId = 0;
    long siteGroupId = 0;

    if (themeDisplay != null) {
      companyId = themeDisplay.getCompanyId();
      companyGroupId = themeDisplay.getCompanyGroupId();
      scopeGroupId = themeDisplay.getScopeGroupId();
      siteGroupId = themeDisplay.getSiteGroupId();
    }

    String templateId = String.valueOf(contextObjects.get("template_id"));

    templateId = getTemplateId(templateId, companyId, companyGroupId, scopeGroupId);

    Template template = getTemplate(templateId, script, langType);

    UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

    try {
      if (contextObjects != null) {
        for (String key : contextObjects.keySet()) {
          template.put(key, contextObjects.get(key));
        }
      }

      template.put("company", getCompany(themeDisplay, companyId));
      template.put("companyId", companyId);
      template.put("device", getDevice(themeDisplay));

      String templatesPath = getTemplatesPath(companyId, scopeGroupId);

      template.put("journalTemplatesPath", templatesPath);
      template.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
      template.put(
          "randomNamespace", PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE);
      template.put("scopeGroupId", scopeGroupId);
      template.put("siteGroupId", siteGroupId);
      template.put("templatesPath", templatesPath);

      // Deprecated variables

      template.put("groupId", scopeGroupId);

      mergeTemplate(template, unsyncStringWriter);
    } catch (Exception e) {
      throw new TransformException("Unhandled exception", e);
    }

    return unsyncStringWriter.toString();
  }
Exemplo n.º 2
0
  @Override
  public int doStartTag() {
    HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();

    if (Validator.isNull(_id)) {
      _id = PwdGenerator.getPassword(PwdGenerator.KEY3, 4);
    }

    request.setAttribute("liferay-ui:panel-container:id", _id);
    request.setAttribute("liferay-ui:panel-container:accordion", String.valueOf(_accordion));
    request.setAttribute("liferay-ui:panel-container:persistState", String.valueOf(_persistState));
    request.setAttribute("liferay-ui:panel-container:extended", _extended);
    request.setAttribute("liferay-ui:panel-container:cssClass", _cssClass);
    request.setAttribute("liferay-ui:panel-container:panelCount" + _id, new IntegerWrapper());

    return EVAL_BODY_BUFFERED;
  }
  public static String getFullInstanceSeparator() {
    String instanceId =
        PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2 + PwdGenerator.KEY3, 12);

    return PortletConstants.INSTANCE_SEPARATOR + instanceId;
  }
  protected void doAddBookItems(long userId, long groupId, long categoryId, String[] isbns)
      throws IOException, PortalException, SystemException {

    if (!AmazonRankingsUtil.isEnabled()) {
      throw new AmazonException("Amazon integration is not enabled");
    }

    String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR);

    for (int i = 0; (i < isbns.length) && (i < 50); i++) {
      String isbn = isbns[i];

      AmazonRankings amazonRankings = AmazonRankingsUtil.getAmazonRankings(isbn);

      if (amazonRankings == null) {
        continue;
      }

      String name = amazonRankings.getProductName();
      String description = StringPool.BLANK;
      String properties = getBookProperties(amazonRankings);

      int minQuantity = 0;
      int maxQuantity = 0;
      double price = amazonRankings.getListPrice();
      double discount = 1 - amazonRankings.getOurPrice() / price;
      boolean taxable = true;
      double shipping = 0.0;
      boolean useShippingFormula = true;

      ShoppingItemPrice itemPrice = shoppingItemPricePersistence.create(0);

      itemPrice.setMinQuantity(minQuantity);
      itemPrice.setMaxQuantity(maxQuantity);
      itemPrice.setPrice(price);
      itemPrice.setDiscount(discount);
      itemPrice.setTaxable(taxable);
      itemPrice.setShipping(shipping);
      itemPrice.setUseShippingFormula(useShippingFormula);
      itemPrice.setStatus(ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT);

      boolean requiresShipping = true;
      int stockQuantity = 0;
      boolean featured = false;
      Boolean sale = null;

      // Small image

      boolean smallImage = true;
      String smallImageURL = StringPool.BLANK;
      File smallImageFile =
          new File(
              tmpDir
                  + File.separatorChar
                  + PwdGenerator.getPassword(8, PwdGenerator.KEY2)
                  + ".jpg");

      byte[] smallImageBytes = HttpUtil.URLtoByteArray(amazonRankings.getSmallImageURL());

      if (smallImageBytes.length < 1024) {
        smallImage = false;
      } else {
        OutputStream os = new FileOutputStream(smallImageFile);

        os.write(smallImageBytes);

        os.close();
      }

      // Medium image

      boolean mediumImage = true;
      String mediumImageURL = StringPool.BLANK;
      File mediumImageFile =
          new File(
              tmpDir
                  + File.separatorChar
                  + PwdGenerator.getPassword(8, PwdGenerator.KEY2)
                  + ".jpg");

      byte[] mediumImageBytes = HttpUtil.URLtoByteArray(amazonRankings.getMediumImageURL());

      if (mediumImageBytes.length < 1024) {
        mediumImage = false;
      } else {
        OutputStream os = new FileOutputStream(mediumImageFile);

        os.write(mediumImageBytes);

        os.close();
      }

      // Large image

      boolean largeImage = true;
      String largeImageURL = StringPool.BLANK;
      File largeImageFile =
          new File(
              tmpDir
                  + File.separatorChar
                  + PwdGenerator.getPassword(8, PwdGenerator.KEY2)
                  + ".jpg");

      byte[] largeImageBytes = HttpUtil.URLtoByteArray(amazonRankings.getLargeImageURL());

      if (largeImageBytes.length < 1024) {
        largeImage = false;
      } else {
        OutputStream os = new FileOutputStream(largeImageFile);

        os.write(largeImageBytes);

        os.close();
      }

      List<ShoppingItemField> itemFields = new ArrayList<ShoppingItemField>();

      List<ShoppingItemPrice> itemPrices = new ArrayList<ShoppingItemPrice>();

      itemPrices.add(itemPrice);

      ServiceContext serviceContext = new ServiceContext();

      serviceContext.setAddGroupPermissions(true);
      serviceContext.setAddGuestPermissions(true);

      addItem(
          userId,
          groupId,
          categoryId,
          isbn,
          name,
          description,
          properties,
          StringPool.BLANK,
          requiresShipping,
          stockQuantity,
          featured,
          sale,
          smallImage,
          smallImageURL,
          smallImageFile,
          mediumImage,
          mediumImageURL,
          mediumImageFile,
          largeImage,
          largeImageURL,
          largeImageFile,
          itemFields,
          itemPrices,
          serviceContext);

      smallImageFile.delete();
      mediumImageFile.delete();
      largeImageFile.delete();
    }
  }
Exemplo n.º 5
0
  public String transform(
      ThemeDisplay themeDisplay,
      Map<String, String> tokens,
      String viewMode,
      String languageId,
      String xml,
      String script,
      String langType)
      throws Exception {

    // Setup listeners

    if (_log.isDebugEnabled()) {
      _log.debug("Language " + languageId);
    }

    if (Validator.isNull(viewMode)) {
      viewMode = Constants.VIEW;
    }

    if (_logTokens.isDebugEnabled()) {
      String tokensString = PropertiesUtil.list(tokens);

      _logTokens.debug(tokensString);
    }

    if (_logTransformBefore.isDebugEnabled()) {
      _logTransformBefore.debug(xml);
    }

    List<TransformerListener> transformerListeners = new ArrayList<TransformerListener>();

    for (String transformerListenersClassName : _transformerListenerClassNames) {

      TransformerListener transformerListener = null;

      try {
        if (_log.isDebugEnabled()) {
          _log.debug("Instantiate listener " + transformerListenersClassName);
        }

        ClassLoader classLoader = PortalClassLoaderUtil.getClassLoader();

        transformerListener =
            (TransformerListener)
                InstanceFactory.newInstance(classLoader, transformerListenersClassName);

        transformerListeners.add(transformerListener);
      } catch (Exception e) {
        _log.error(e, e);
      }

      // Modify XML

      if (_logXmlBeforeListener.isDebugEnabled()) {
        _logXmlBeforeListener.debug(xml);
      }

      if (transformerListener != null) {
        xml = transformerListener.onXml(xml, languageId, tokens);

        if (_logXmlAfterListener.isDebugEnabled()) {
          _logXmlAfterListener.debug(xml);
        }
      }

      // Modify script

      if (_logScriptBeforeListener.isDebugEnabled()) {
        _logScriptBeforeListener.debug(script);
      }

      if (transformerListener != null) {
        script = transformerListener.onScript(script, xml, languageId, tokens);

        if (_logScriptAfterListener.isDebugEnabled()) {
          _logScriptAfterListener.debug(script);
        }
      }
    }

    // Transform

    String output = null;

    if (Validator.isNull(langType)) {
      output = LocalizationUtil.getLocalization(xml, languageId);
    } else {
      long companyId = 0;
      long companyGroupId = 0;
      long articleGroupId = 0;

      if (tokens != null) {
        companyId = GetterUtil.getLong(tokens.get("company_id"));
        companyGroupId = GetterUtil.getLong(tokens.get("company_group_id"));
        articleGroupId = GetterUtil.getLong(tokens.get("article_group_id"));
      }

      long scopeGroupId = 0;
      long siteGroupId = 0;

      if (themeDisplay != null) {
        companyId = themeDisplay.getCompanyId();
        companyGroupId = themeDisplay.getCompanyGroupId();
        scopeGroupId = themeDisplay.getScopeGroupId();
        siteGroupId = themeDisplay.getSiteGroupId();
      }

      String templateId = tokens.get("template_id");

      templateId = getTemplateId(templateId, companyId, companyGroupId, articleGroupId);

      Template template = getTemplate(templateId, tokens, languageId, xml, script, langType);

      UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

      try {
        if (Validator.isNotNull(xml)) {
          Document document = SAXReaderUtil.read(xml);

          Element rootElement = document.getRootElement();

          List<TemplateNode> templateNodes = getTemplateNodes(themeDisplay, rootElement);

          if (templateNodes != null) {
            for (TemplateNode templateNode : templateNodes) {
              template.put(templateNode.getName(), templateNode);
            }
          }

          Element requestElement = rootElement.element("request");

          template.put("request", insertRequestVariables(requestElement));

          template.put("xmlRequest", requestElement.asXML());
        }

        template.put("articleGroupId", articleGroupId);
        template.put("company", getCompany(themeDisplay, companyId));
        template.put("companyId", companyId);
        template.put("device", getDevice(themeDisplay));

        String templatesPath = getTemplatesPath(companyId, articleGroupId);

        template.put("journalTemplatesPath", templatesPath);

        Locale locale = LocaleUtil.fromLanguageId(languageId);

        template.put("locale", locale);

        template.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
        template.put(
            "randomNamespace",
            PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE);
        template.put("scopeGroupId", scopeGroupId);
        template.put("siteGroupId", siteGroupId);
        template.put("templatesPath", templatesPath);
        template.put("viewMode", viewMode);

        // Deprecated variables

        template.put("groupId", articleGroupId);

        mergeTemplate(template, unsyncStringWriter);
      } catch (Exception e) {
        if (e instanceof DocumentException) {
          throw new TransformException("Unable to read XML document", e);
        } else if (e instanceof IOException) {
          throw new TransformException("Error reading template", e);
        } else if (e instanceof TransformException) {
          throw (TransformException) e;
        } else {
          throw new TransformException("Unhandled exception", e);
        }
      }

      output = unsyncStringWriter.toString();
    }

    // Postprocess output

    for (TransformerListener transformerListener : transformerListeners) {

      // Modify output

      if (_logOutputBeforeListener.isDebugEnabled()) {
        _logOutputBeforeListener.debug(output);
      }

      output = transformerListener.onOutput(output, languageId, tokens);

      if (_logOutputAfterListener.isDebugEnabled()) {
        _logOutputAfterListener.debug(output);
      }
    }

    if (_logTransfromAfter.isDebugEnabled()) {
      _logTransfromAfter.debug(output);
    }

    return output;
  }
Exemplo n.º 6
0
  protected String doTransform(
      ThemeDisplay themeDisplay,
      Map<String, String> tokens,
      String viewMode,
      String languageId,
      String xml,
      String script)
      throws Exception {

    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream();

    long companyId = GetterUtil.getLong(tokens.get("company_id"));
    Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
    long groupId = GetterUtil.getLong(tokens.get("group_id"));
    String journalTemplatesPath =
        VelocityResourceListener.JOURNAL_SEPARATOR
            + StringPool.SLASH
            + companyId
            + StringPool.SLASH
            + groupId;
    String randomNamespace = PwdGenerator.getPassword(PwdGenerator.KEY3, 4) + StringPool.UNDERLINE;
    Locale locale = LocaleUtil.fromLanguageId(languageId);

    XSLErrorListener xslErrorListener = new XSLErrorListener(locale);

    StreamSource xmlSource = new StreamSource(new UnsyncStringReader(xml));

    TransformerFactory transformerFactory = TransformerFactory.newInstance();

    transformerFactory.setURIResolver(new URIResolver(tokens, languageId));
    transformerFactory.setErrorListener(xslErrorListener);

    try {
      StreamSource scriptSource = new StreamSource(new UnsyncStringReader(script));

      Transformer transformer = transformerFactory.newTransformer(scriptSource);

      transformer.setParameter("company", company);
      transformer.setParameter("companyId", new Long(companyId));
      transformer.setParameter("groupId", String.valueOf(groupId));
      transformer.setParameter("journalTemplatesPath", journalTemplatesPath);
      transformer.setParameter("viewMode", viewMode);
      transformer.setParameter("locale", locale);
      transformer.setParameter("permissionChecker", PermissionThreadLocal.getPermissionChecker());
      transformer.setParameter("randomNamespace", randomNamespace);

      transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));
    } catch (Exception e1) {
      String errorTemplate = ContentUtil.get(PropsValues.JOURNAL_ERROR_TEMPLATE_XSL);

      StreamSource scriptSource = new StreamSource(new UnsyncStringReader(errorTemplate));

      Transformer transformer = transformerFactory.newTransformer(scriptSource);

      transformer.setParameter("company", company);
      transformer.setParameter("companyId", new Long(companyId));
      transformer.setParameter("groupId", String.valueOf(groupId));
      transformer.setParameter("journalTemplatesPath", journalTemplatesPath);
      transformer.setParameter("locale", locale);
      transformer.setParameter("randomNamespace", randomNamespace);

      transformer.setParameter("exception", xslErrorListener.getMessageAndLocation());
      transformer.setParameter("script", script);

      if (xslErrorListener.getLocation() != null) {
        transformer.setParameter("column", new Integer(xslErrorListener.getColumnNumber()));
        transformer.setParameter("line", new Integer(xslErrorListener.getLineNumber()));
      }

      transformer.transform(xmlSource, new StreamResult(unsyncByteArrayOutputStream));
    }

    return unsyncByteArrayOutputStream.toString(StringPool.UTF8);
  }
Exemplo n.º 7
0
  @Override
  protected void setAttributes(HttpServletRequest request) {
    super.setAttributes(request);

    Object bean = getBean();

    if (bean == null) {
      bean = pageContext.getAttribute("aui:model-context:bean");
    }

    String name = getName();

    int pos = name.indexOf(StringPool.DOUBLE_DASH);

    if (pos != -1) {
      name = name.substring(pos + 2, name.length() - 2);
    }

    String field = getField();

    if (Validator.isNull(field)) {
      field = getName();
    }

    String formName = getFormName();

    if (formName == null) {
      FormTag formTag = (FormTag) findAncestorWithClass(this, FormTag.class);

      if (formTag != null) {
        formName = formTag.getName();
      }
    }

    String id = getId();
    String type = getType();

    if (Validator.isNull(id)) {
      if (!Validator.equals(type, "assetTags") && !Validator.equals(type, "radio")) {

        id = name;
      } else {
        id = PwdGenerator.getPassword(PwdGenerator.KEY3, 4);
      }
    }

    String label = getLabel();

    if (label == null) {
      label = TextFormatter.format(name, TextFormatter.K);
    }

    Class<?> model = getModel();

    if (model == null) {
      model = (Class<?>) pageContext.getAttribute("aui:model-context:model");
    }

    _forLabel = id;

    String baseType = null;

    if ((model != null) && Validator.isNull(type)) {
      baseType = ModelHintsUtil.getType(model.getName(), field);

      String fieldParam = getFieldParam();

      if (Validator.isNotNull(fieldParam)) {
        _forLabel = fieldParam;
      }

      if (ModelHintsUtil.isLocalized(model.getName(), field)) {
        Locale defaultLocale = LocaleUtil.getDefault();
        String defaultLanguageId = LocaleUtil.toLanguageId(defaultLocale);

        _forLabel += StringPool.UNDERLINE + defaultLanguageId;
      }
    } else if (Validator.isNotNull(type)) {
      if (Validator.equals(type, "checkbox") || Validator.equals(type, "radio")) {

        baseType = type;
      }
    }

    if (Validator.isNull(baseType)) {
      baseType = "text";
    }

    setNamespacedAttribute(request, "baseType", baseType);
    setNamespacedAttribute(request, "bean", bean);
    setNamespacedAttribute(request, "field", field);
    setNamespacedAttribute(request, "forLabel", _forLabel);
    setNamespacedAttribute(request, "formName", formName);
    setNamespacedAttribute(request, "id", id);
    setNamespacedAttribute(request, "label", label);
    setNamespacedAttribute(request, "model", model);

    request.setAttribute(getAttributeNamespace() + "value", getValue());
  }
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    UploadServletRequest uploadRequest = null;

    try {
      String cmd = ParamUtil.getString(request, Constants.CMD);

      ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

      long groupId = ParamUtil.getLong(request, "groupId");
      String articleId = ParamUtil.getString(request, "articleId");
      double version =
          ParamUtil.getDouble(request, "version", JournalArticleConstants.DEFAULT_VERSION);

      String languageId = LanguageUtil.getLanguageId(request);

      String output = null;

      if (cmd.equals(Constants.PREVIEW)) {
        uploadRequest = PortalUtil.getUploadServletRequest(request);

        String title = ParamUtil.getString(uploadRequest, "title");
        String description = ParamUtil.getString(uploadRequest, "description");
        String type = ParamUtil.getString(uploadRequest, "type");
        String structureId = ParamUtil.getString(uploadRequest, "structureId");
        String templateId = ParamUtil.getString(uploadRequest, "templateId");

        Date now = new Date();

        Date createDate = now;
        Date modifiedDate = now;
        Date displayDate = now;

        User user = PortalUtil.getUser(uploadRequest);

        String xml = ParamUtil.getString(uploadRequest, "xml");

        Document doc = SAXReaderUtil.read(xml);

        Element root = doc.getRootElement();

        String previewArticleId = "PREVIEW_" + PwdGenerator.getPassword(PwdGenerator.KEY3, 10);

        format(groupId, articleId, version, previewArticleId, root, uploadRequest);

        Map<String, String> tokens = JournalUtil.getTokens(groupId, themeDisplay);

        tokens.put("article_resource_pk", "-1");

        JournalArticle article = new JournalArticleImpl();

        article.setGroupId(groupId);
        article.setCompanyId(user.getCompanyId());
        article.setUserId(user.getUserId());
        article.setUserName(user.getFullName());
        article.setCreateDate(createDate);
        article.setModifiedDate(modifiedDate);
        article.setArticleId(articleId);
        article.setVersion(version);
        article.setTitle(title);
        article.setDescription(description);
        article.setContent(xml);
        article.setType(type);
        article.setStructureId(structureId);
        article.setTemplateId(templateId);
        article.setDisplayDate(displayDate);

        output =
            JournalArticleLocalServiceUtil.getArticleContent(
                article, templateId, null, languageId, themeDisplay);
      } else {
        output =
            JournalArticleServiceUtil.getArticleContent(
                groupId, articleId, version, languageId, themeDisplay);
      }

      request.setAttribute(WebKeys.JOURNAL_ARTICLE_CONTENT, output);

      if (output.startsWith("<?xml ")) {
        return mapping.findForward("portlet.journal.raw_article_content");
      } else {
        return mapping.findForward("portlet.journal.view_article_content");
      }
    } catch (Exception e) {
      PortalUtil.sendError(e, request, response);

      return null;
    } finally {
      if (uploadRequest != null) {
        uploadRequest.cleanUp();
      }
    }
  }
Exemplo n.º 9
0
 @Override
 public String generate(PasswordPolicy passwordPolicy) {
   return PwdGenerator.getSecurePassword(_charset, _length);
 }