Пример #1
0
  public void setSettings(String settings) {
    _settingsProperties.clear();

    try {
      PropertiesUtil.load(_settingsProperties, settings);
      PropertiesUtil.trimKeys(_settingsProperties);
    } catch (IOException ioe) {
      _log.error(ioe);
    }
  }
Пример #2
0
  public LiferayResourceBundle(String string, String charsetName) throws IOException {

    _map = new HashMap<String, String>();

    Properties properties = PropertiesUtil.load(string, charsetName);

    LanguageResources.fixValues(_map, properties);
  }
Пример #3
0
  public LiferayResourceBundle(
      ResourceBundle parentResourceBundle, InputStream inputStream, String charsetName)
      throws IOException {

    setParent(parentResourceBundle);

    _map = new HashMap<String, String>();

    Properties properties = PropertiesUtil.load(inputStream, charsetName);

    LanguageResources.fixValues(_map, properties);
  }
  @Override
  public Properties getContactMappings(long ldapServerId, long companyId) throws Exception {

    String postfix = getPropertyPostfix(ldapServerId);

    Properties contactMappings =
        PropertiesUtil.load(
            PrefsPropsUtil.getString(
                companyId, PropsKeys.LDAP_CONTACT_MAPPINGS + postfix, StringPool.BLANK));

    LogUtil.debug(_log, contactMappings);

    return contactMappings;
  }
  @Override
  public Properties getUserExpandoMappings(long ldapServerId, long companyId) throws Exception {

    String postfix = getPropertyPostfix(ldapServerId);

    Properties userExpandoMappings =
        PropertiesUtil.load(
            PrefsPropsUtil.getString(
                companyId, PropsKeys.LDAP_USER_CUSTOM_MAPPINGS + postfix, StringPool.BLANK));

    LogUtil.debug(_log, userExpandoMappings);

    return userExpandoMappings;
  }
Пример #6
0
    @Override
    protected void doPortalInit() throws Exception {
      Properties properties = null;

      String propertiesString =
          HttpUtil.URLtoString(
              _servletContext.getResource("/WEB-INF/liferay-plugin-package.properties"));

      if (propertiesString != null) {
        properties = PropertiesUtil.load(propertiesString);
      } else {
        properties = new Properties();
      }

      _pacl.initPolicy(_servletContext.getServletContextName(), _classLoader, properties);
    }
  protected byte[] getPropertiesAsBytes(
      ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws Exception {

    StringBundler sb = new StringBundler(5);

    sb.append("##\n## To apply the configuration, deploy this file to a ");
    sb.append("Liferay installation with the file name ");
    sb.append(getFileName(resourceRequest));
    sb.append(".\n##\n\n");

    Properties properties = getProperties(resourceRequest, resourceResponse);

    sb.append(PropertiesUtil.toString(properties));

    String propertiesString = sb.toString();

    return propertiesString.getBytes();
  }
Пример #8
0
  protected void doInit() throws Exception {
    if (_companyId > 0) {
      Company company = CompanyLocalServiceUtil.getCompany(_companyId);

      _domain = company.getMx();
      _userName = PrefsPropsUtil.getString(_companyId, PropsKeys.GOOGLE_APPS_USERNAME);
      _password = PrefsPropsUtil.getString(_companyId, PropsKeys.GOOGLE_APPS_PASSWORD);
    }

    Http.Options options = new Http.Options();

    options.addPart("accountType", "HOSTED");

    String emailAddress = _userName;

    if (!emailAddress.contains(StringPool.AT)) {
      emailAddress = _userName.concat(StringPool.AT).concat(_domain);
    }

    options.addPart("Email", emailAddress);

    options.addPart("Passwd", _password);
    options.addPart("service", "apps");
    options.setLocation("https://www.google.com/accounts/ClientLogin");
    options.setPost(true);

    String content = HttpUtil.URLtoString(options);

    Properties properties = PropertiesUtil.load(content);

    _error = properties.getProperty("Error");

    if (_error != null) {
      _log.info("Unable to initialize authentication token: " + _error);
    }

    _authenticationToken = properties.getProperty("Auth");

    if (_authenticationToken != null) {
      _log.info("Authentication token " + _authenticationToken);
    }

    _initTime = System.currentTimeMillis();
  }
  public PluginPackageProperties(ServletContext servletContext) throws IOException {

    InputStream inputStream =
        servletContext.getResourceAsStream("/WEB-INF/liferay-plugin-package.properties");

    if (inputStream == null) {
      return;
    }

    String propertiesString = StringUtil.read(inputStream);

    String contextPath = servletContext.getRealPath(StringPool.SLASH);

    contextPath = StringUtil.replace(contextPath, CharPool.BACK_SLASH, CharPool.SLASH);

    propertiesString = propertiesString.replace("${context.path}", contextPath);

    PropertiesUtil.load(_properties, propertiesString);
  }
Пример #10
0
  private static void _reloadServletContext(
      HttpServletRequest request, UnicodeProperties unicodeProperties) throws Exception {

    // Data sources

    Properties jdbcProperties = new Properties();

    jdbcProperties.putAll(unicodeProperties);

    jdbcProperties = PropertiesUtil.getProperties(jdbcProperties, "jdbc.default.", true);

    DataSourceSwapper.swapCounterDataSource(jdbcProperties);
    DataSourceSwapper.swapLiferayDataSource(jdbcProperties);

    // Caches

    CacheRegistryUtil.clear();
    MultiVMPoolUtil.clear();
    WebCachePoolUtil.clear();
    CentralizedThreadLocal.clearShortLivedThreadLocals();

    // Persistence beans

    _reconfigurePersistenceBeans();

    // Quartz

    QuartzLocalServiceUtil.checkQuartzTables();

    // Startup

    StartupAction startupAction = new StartupAction();

    startupAction.run(null);

    // Servlet context

    HttpSession session = request.getSession();

    PortalInstances.reload(session.getServletContext());
  }
Пример #11
0
    /**
     * Returns a properties map representing the {@link OSGiBeanProperties} instance.
     *
     * @param osgiBeanProperties the instance of {@link OSGiBeanProperties} read for properties
     * @return a properties map representing the {@link OSGiBeanProperties} instance. The map will
     *     be empty if the {@link OSGiBeanProperties} instance has no properties.
     */
    public static Map<String, Object> toMap(OSGiBeanProperties osgiBeanProperties) {

      Map<String, Object> properties = new HashMap<>();

      for (String property : osgiBeanProperties.property()) {
        String[] parts = property.split(StringPool.EQUAL, 2);

        if (parts.length <= 1) {
          continue;
        }

        String key = parts[0];
        String className = String.class.getSimpleName();

        if (key.indexOf(StringPool.COLON) != -1) {
          String[] keyParts = StringUtil.split(key, StringPool.COLON);

          key = keyParts[0];
          className = keyParts[1];
        }

        String value = parts[1];

        _put(key, value, className, properties);
      }

      String portalPropertyPrefix = osgiBeanProperties.portalPropertyPrefix();

      if (Validator.isNotNull(portalPropertyPrefix)) {
        Properties portalProperties =
            PropsUtil.getProperties(
                portalPropertyPrefix, osgiBeanProperties.portalPropertiesRemovePrefix());

        properties.putAll(PropertiesUtil.toMap(portalProperties));
      }

      return properties;
    }
Пример #12
0
  private static Properties _loadProperties(String name) {
    Properties properties = new Properties();

    try {
      ClassLoader classLoader = LanguageResources.class.getClassLoader();

      Enumeration<URL> enu = classLoader.getResources(name);

      if (_log.isDebugEnabled() && !enu.hasMoreElements()) {
        _log.debug("No resources found for " + name);
      }

      while (enu.hasMoreElements()) {
        URL url = enu.nextElement();

        if (_log.isInfoEnabled()) {
          _log.info("Loading " + name + " from " + url);
        }

        try (InputStream inputStream = url.openStream()) {
          Properties inputStreamProperties = PropertiesUtil.load(inputStream, StringPool.UTF8);

          properties.putAll(inputStreamProperties);

          if (_log.isInfoEnabled()) {
            _log.info("Loading " + url + " with " + inputStreamProperties.size() + " values");
          }
        }
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e, e);
      }
    }

    return properties;
  }
  public Properties generate(
      ServletContext servletContext,
      List<URL> imageURLs,
      String spriteRootDirName,
      String spriteFileName,
      String spritePropertiesFileName,
      String rootPath,
      int maxHeight,
      int maxWidth,
      int maxSize)
      throws IOException {

    if (imageURLs.size() < 1) {
      return null;
    }

    Collections.sort(imageURLs, new PropertyComparator("path"));

    File spriteRootDir = null;

    if (Validator.isNull(spriteRootDirName)) {
      File tempDir =
          (File) servletContext.getAttribute(JavaConstants.JAVAX_SERVLET_CONTEXT_TEMPDIR);

      spriteRootDir = new File(tempDir, SpriteProcessor.PATH);
    } else {
      spriteRootDir = new File(spriteRootDirName);
    }

    spriteRootDir.mkdirs();

    File spritePropertiesFile = new File(spriteRootDir, spritePropertiesFileName);

    File spritePropertiesParentFile = spritePropertiesFile.getParentFile();

    spritePropertiesParentFile.mkdirs();

    boolean build = false;

    long lastModified = 0;

    if (spritePropertiesFile.exists()) {
      lastModified = spritePropertiesFile.lastModified();

      URLConnection urlConnection = null;

      for (URL imageURL : imageURLs) {
        urlConnection = imageURL.openConnection();

        if ((urlConnection != null) && (urlConnection.getLastModified() > lastModified)) {

          build = true;

          break;
        }
      }
    } else {
      build = true;
    }

    if (!build) {
      String spritePropertiesString = FileUtil.read(spritePropertiesFile);

      if (Validator.isNull(spritePropertiesString)) {
        return null;
      } else {
        return PropertiesUtil.load(spritePropertiesString);
      }
    }

    List<RenderedImage> renderedImages = new ArrayList<RenderedImage>();

    Properties spriteProperties = new SortedProperties();

    float x = 0;
    float y = 0;

    URLConnection urlConnection = null;

    for (URL imageURL : imageURLs) {
      urlConnection = imageURL.openConnection();

      if ((urlConnection != null) && (urlConnection.getContentLength() > maxSize)) {

        continue;
      }

      try {
        ImageBag imageBag = ImageToolUtil.read(urlConnection.getInputStream());

        RenderedImage renderedImage = imageBag.getRenderedImage();

        int height = renderedImage.getHeight();
        int width = renderedImage.getWidth();

        if ((height <= maxHeight) && (width <= maxWidth)) {
          renderedImage = convert(renderedImage);

          renderedImage = TranslateDescriptor.create(renderedImage, x, y, null, null);

          renderedImages.add(renderedImage);

          String key = imageURL.getPath();

          int pos = key.indexOf(rootPath);

          if (pos == 0) {
            key = key.substring(rootPath.length());
          }

          String contextPath = ContextPathUtil.getContextPath(servletContext);

          key = contextPath.concat(key);

          String value = (int) y + "," + height + "," + width;

          spriteProperties.setProperty(key, value);

          y += renderedImage.getHeight();
        }
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to process " + imageURL);
        }

        if (_log.isDebugEnabled()) {
          _log.debug(e, e);
        }
      }
    }

    if (renderedImages.size() <= 1) {
      renderedImages.clear();
      spriteProperties.clear();
    } else {

      // PNG

      RenderedImage renderedImage =
          MosaicDescriptor.create(
              renderedImages.toArray(new RenderedImage[renderedImages.size()]),
              MosaicDescriptor.MOSAIC_TYPE_OVERLAY,
              null,
              null,
              null,
              null,
              null);

      File spriteFile = new File(spriteRootDir, spriteFileName);

      spriteFile.mkdirs();

      ImageIO.write(renderedImage, "png", spriteFile);

      if (lastModified > 0) {
        spriteFile.setLastModified(lastModified);
      }

      ImageWorker imageWorker = new ImageWorker(renderedImage);

      imageWorker.forceIndexColorModelForGIF(true);

      // GIF

      renderedImage = imageWorker.getPlanarImage();

      spriteFile = new File(spriteRootDir, StringUtil.replace(spriteFileName, ".png", ".gif"));

      FileOutputStream fos = new FileOutputStream(spriteFile);

      try {
        ImageToolUtil.encodeGIF(renderedImage, fos);
      } finally {
        fos.close();
      }

      if (lastModified > 0) {
        spriteFile.setLastModified(lastModified);
      }
    }

    FileUtil.write(spritePropertiesFile, PropertiesUtil.toString(spriteProperties));

    if (lastModified > 0) {
      spritePropertiesFile.setLastModified(lastModified);
    }

    return spriteProperties;
  }
Пример #14
0
  public LangBuilder(String langDir, String langFile, boolean langPlugin, boolean langTranslate)
      throws Exception {

    _langDir = langDir;
    _langFile = langFile;
    _langTranslate = langTranslate;

    if (langPlugin) {
      _portalLanguageProperties = new Properties();

      Class<?> clazz = getClass();

      ClassLoader classLoader = clazz.getClassLoader();

      InputStream inputStream = classLoader.getResourceAsStream("content/Language.properties");

      _portalLanguageProperties.load(inputStream);
    }

    File renameKeysFile = new File(_langDir + "/rename.properties");

    if (renameKeysFile.exists()) {
      _renameKeys = PropertiesUtil.load(FileUtil.read(renameKeysFile));
    }

    String content = _orderProperties(new File(_langDir + "/" + _langFile + ".properties"));

    // Locales that are not invoked by _createProperties should still be
    // rewritten to use the rignt line separator

    _orderProperties(new File(_langDir + "/" + _langFile + "_en_GB.properties"));

    _createProperties(content, "ar"); // Arabic
    _createProperties(content, "eu"); // Basque
    _createProperties(content, "bg"); // Bulgarian
    _createProperties(content, "ca"); // Catalan
    _createProperties(content, "zh_CN"); // Chinese (China)
    _createProperties(content, "zh_TW"); // Chinese (Taiwan)
    _createProperties(content, "hr"); // Croatian
    _createProperties(content, "cs"); // Czech
    _createProperties(content, "da"); // Danish
    _createProperties(content, "nl"); // Dutch (Netherlands)
    _createProperties(content, "nl_BE", "nl"); // Dutch (Belgium)
    _createProperties(content, "et"); // Estonian
    _createProperties(content, "fi"); // Finnish
    _createProperties(content, "fr"); // French
    _createProperties(content, "gl"); // Galician
    _createProperties(content, "de"); // German
    _createProperties(content, "el"); // Greek
    _createProperties(content, "iw"); // Hebrew
    _createProperties(content, "hi_IN"); // Hindi (India)
    _createProperties(content, "hu"); // Hungarian
    _createProperties(content, "in"); // Indonesian
    _createProperties(content, "it"); // Italian
    _createProperties(content, "ja"); // Japanese
    _createProperties(content, "ko"); // Korean
    _createProperties(content, "lo"); // Lao
    _createProperties(content, "nb"); // Norwegian Bokmål
    _createProperties(content, "fa"); // Persian
    _createProperties(content, "pl"); // Polish
    _createProperties(content, "pt_BR"); // Portuguese (Brazil)
    _createProperties(content, "pt_PT", "pt_BR"); // Portuguese (Portugal)
    _createProperties(content, "ro"); // Romanian
    _createProperties(content, "ru"); // Russian
    _createProperties(content, "sr_RS"); // Serbian (Cyrillic)
    _createProperties(content, "sr_RS_latin"); // Serbian (Latin)
    _createProperties(content, "sk"); // Slovak
    _createProperties(content, "sl"); // Slovene
    _createProperties(content, "es"); // Spanish
    _createProperties(content, "sv"); // Swedish
    _createProperties(content, "tr"); // Turkish
    _createProperties(content, "uk"); // Ukrainian
    _createProperties(content, "vi"); // Vietnamese
  }
Пример #15
0
 public String getSettings() {
   return PropertiesUtil.toString(_settingsProperties);
 }
Пример #16
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;
  }
Пример #17
0
  private void _createProperties(String content, String languageId, String parentLanguageId)
      throws IOException {

    File propertiesFile = new File(_langDir + "/" + _langFile + "_" + languageId + ".properties");

    Properties properties = new Properties();

    if (propertiesFile.exists()) {
      properties = PropertiesUtil.load(new FileInputStream(propertiesFile), StringPool.UTF8);
    }

    Properties parentProperties = null;

    if (parentLanguageId != null) {
      File parentPropertiesFile =
          new File(_langDir + "/" + _langFile + "_" + parentLanguageId + ".properties");

      if (parentPropertiesFile.exists()) {
        parentProperties = new Properties();

        parentProperties =
            PropertiesUtil.load(new FileInputStream(parentPropertiesFile), StringPool.UTF8);
      }
    }

    String translationId = "en_" + languageId;

    if (translationId.equals("en_pt_BR")) {
      translationId = "en_pt";
    } else if (translationId.equals("en_pt_PT")) {
      translationId = "en_pt";
    } else if (translationId.equals("en_zh_CN")) {
      translationId = "en_zh";
    } else if (translationId.equals("en_zh_TW")) {
      translationId = "en_zt";
    } else if (translationId.equals("en_hi_IN")) {
      translationId = "en_hi";
    }

    UnsyncBufferedReader unsyncBufferedReader =
        new UnsyncBufferedReader(new UnsyncStringReader(content));
    UnsyncBufferedWriter unsyncBufferedWriter =
        new UnsyncBufferedWriter(
            new OutputStreamWriter(new FileOutputStream(propertiesFile), StringPool.UTF8));

    int state = 0;

    String line = null;

    while ((line = unsyncBufferedReader.readLine()) != null) {
      line = line.trim();

      int pos = line.indexOf("=");

      if (pos != -1) {
        String key = line.substring(0, pos);
        String value = line.substring(pos + 1, line.length());

        if (((state == 1) && !key.startsWith("lang."))
            || ((state == 2) && !key.startsWith("javax.portlet."))
            || ((state == 3) && !key.startsWith("category."))
            || ((state == 4) && !key.startsWith("model.resource."))
            || ((state == 5) && !key.startsWith("action."))
            || ((state == 7) && !key.startsWith("currency."))
            || ((state != 7) && key.startsWith("currency."))) {

          throw new RuntimeException(
              "File " + languageId + " with state " + state + " has key " + key);
        }

        String translatedText = properties.getProperty(key);

        if ((translatedText == null) && (parentProperties != null)) {
          translatedText = parentProperties.getProperty(key);
        }

        if ((translatedText == null) && (_renameKeys != null)) {
          String renameKey = _renameKeys.getProperty(key);

          if (renameKey != null) {
            translatedText = properties.getProperty(key);

            if ((translatedText == null) && (parentProperties != null)) {

              translatedText = parentProperties.getProperty(key);
            }
          }
        }

        if (translatedText != null) {
          if (translatedText.contains("Babel Fish") || translatedText.contains("Yahoo! - 999")) {

            translatedText = "";
          } else if (translatedText.endsWith(AUTOMATIC_COPY)) {
            translatedText = value + AUTOMATIC_COPY;
          }
        }

        if ((translatedText == null) || translatedText.equals("")) {
          if (line.contains("{") || line.contains("<")) {
            translatedText = value + AUTOMATIC_COPY;
          } else if (line.contains("[")) {
            pos = line.indexOf("[");

            String baseKey = line.substring(0, pos);

            translatedText = properties.getProperty(baseKey) + AUTOMATIC_COPY;
          } else if (key.equals("lang.dir")) {
            translatedText = "ltr";
          } else if (key.equals("lang.line.begin")) {
            translatedText = "left";
          } else if (key.equals("lang.line.end")) {
            translatedText = "right";
          } else if (translationId.equals("en_el")
              && (key.equals("enabled") || key.equals("on") || key.equals("on-date"))) {

            translatedText = "";
          } else if (translationId.equals("en_es") && key.equals("am")) {

            translatedText = "";
          } else if (translationId.equals("en_it") && key.equals("am")) {

            translatedText = "";
          } else if (translationId.equals("en_ja")
              && (key.equals("any")
                  || key.equals("anytime")
                  || key.equals("down")
                  || key.equals("on")
                  || key.equals("on-date")
                  || key.equals("the"))) {

            translatedText = "";
          } else if (translationId.equals("en_ko") && key.equals("the")) {

            translatedText = "";
          } else {
            translatedText = _translate(translationId, key, value, 0);

            if (Validator.isNull(translatedText)) {
              translatedText = value + AUTOMATIC_COPY;
            } else {
              translatedText = translatedText + AUTOMATIC_TRANSLATION;
            }
          }
        }

        if (Validator.isNotNull(translatedText)) {
          if (translatedText.contains("Babel Fish") || translatedText.contains("Yahoo! - 999")) {

            throw new IOException(
                "IP was blocked because of over usage. Please " + "use another IP.");
          }

          translatedText = _fixTranslation(translatedText);

          unsyncBufferedWriter.write(key + "=" + translatedText);

          unsyncBufferedWriter.newLine();
          unsyncBufferedWriter.flush();
        }
      } else {
        if (line.startsWith("## Language settings")) {
          if (state == 1) {
            throw new RuntimeException(languageId);
          }

          state = 1;
        } else if (line.startsWith("## Portlet descriptions and titles")) {

          if (state == 2) {
            throw new RuntimeException(languageId);
          }

          state = 2;
        } else if (line.startsWith("## Category titles")) {
          if (state == 3) {
            throw new RuntimeException(languageId);
          }

          state = 3;
        } else if (line.startsWith("## Model resources")) {
          if (state == 4) {
            throw new RuntimeException(languageId);
          }

          state = 4;
        } else if (line.startsWith("## Action names")) {
          if (state == 5) {
            throw new RuntimeException(languageId);
          }

          state = 5;
        } else if (line.startsWith("## Messages")) {
          if (state == 6) {
            throw new RuntimeException(languageId);
          }

          state = 6;
        } else if (line.startsWith("## Currency")) {
          if (state == 7) {
            throw new RuntimeException(languageId);
          }

          state = 7;
        }

        unsyncBufferedWriter.write(line);

        unsyncBufferedWriter.newLine();
        unsyncBufferedWriter.flush();
      }
    }

    unsyncBufferedReader.close();
    unsyncBufferedWriter.close();
  }
Пример #18
0
  protected String doTransform(
      ThemeDisplay themeDisplay,
      Map<String, Object> contextObjects,
      Map<String, String> tokens,
      String viewMode,
      String languageId,
      Document document,
      PortletRequestModel portletRequestModel,
      String script,
      String langType,
      boolean propagateException)
      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(document);
    }

    List<TransformerListener> transformerListeners =
        JournalTransformerListenerRegistryUtil.getTransformerListeners();

    for (TransformerListener transformerListener : transformerListeners) {

      // Modify XML

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

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

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

      // Modify script

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

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

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

    // Transform

    String output = null;

    if (Validator.isNull(langType)) {
      output = LocalizationUtil.getLocalization(document.asXML(), languageId);
    } else {
      long companyId = 0;
      long companyGroupId = 0;
      long articleGroupId = 0;
      long classNameId = 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"));
        classNameId = GetterUtil.getLong(tokens.get(TemplateConstants.CLASS_NAME_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, document, script, langType);

      if (contextObjects != null) {
        template.putAll(contextObjects);
      }

      UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter();

      try {
        if (document != null) {
          Element rootElement = document.getRootElement();

          List<TemplateNode> templateNodes =
              getTemplateNodes(
                  themeDisplay, rootElement, Long.valueOf(tokens.get("ddm_structure_id")));

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

          if (portletRequestModel != null) {
            template.put("request", portletRequestModel.toMap());

            if (langType.equals(TemplateConstants.LANG_TYPE_XSL)) {
              Document requestDocument = SAXReaderUtil.read(portletRequestModel.toXML());

              Element requestElement = requestDocument.getRootElement();

              template.put("xmlRequest", requestElement.asXML());
            }
          } else {
            Element requestElement = rootElement.element("request");

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

            if (langType.equals(TemplateConstants.LANG_TYPE_XSL)) {
              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, classNameId);

        Locale locale = LocaleUtil.fromLanguageId(languageId);

        template.put("locale", locale);

        template.put("permissionChecker", PermissionThreadLocal.getPermissionChecker());
        template.put("randomNamespace", StringUtil.randomId() + StringPool.UNDERLINE);
        template.put("scopeGroupId", scopeGroupId);
        template.put("siteGroupId", siteGroupId);
        template.put("templatesPath", templatesPath);
        template.put("viewMode", viewMode);

        if (themeDisplay != null) {
          TemplateManager templateManager = TemplateManagerUtil.getTemplateManager(langType);

          HttpServletRequest request = themeDisplay.getRequest();

          templateManager.addTaglibSupport(template, request, themeDisplay.getResponse());
          templateManager.addTaglibTheme(
              template,
              "taglibLiferay",
              request,
              new PipingServletResponse(themeDisplay.getResponse(), unsyncStringWriter));
        }

        // Deprecated variables

        template.put("groupId", articleGroupId);
        template.put("journalTemplatesPath", templatesPath);

        mergeTemplate(template, unsyncStringWriter, propagateException);
      } 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;
  }