@Before
  public void setUp() throws Exception {
    VelocityEngineConfiguration _velocityEngineConfiguration =
        Configurable.createConfigurable(VelocityEngineConfiguration.class, Collections.emptyMap());

    _templateContextHelper = new MockTemplateContextHelper();

    _velocityEngine = new VelocityEngine();

    boolean cacheEnabled = false;

    ExtendedProperties extendedProperties = new FastExtendedProperties();

    extendedProperties.setProperty(
        VelocityEngine.DIRECTIVE_IF_TOSTRING_NULLCHECK,
        String.valueOf(_velocityEngineConfiguration.directiveIfToStringNullCheck()));
    extendedProperties.setProperty(
        VelocityEngine.EVENTHANDLER_METHODEXCEPTION,
        LiferayMethodExceptionEventHandler.class.getName());
    extendedProperties.setProperty(
        RuntimeConstants.INTROSPECTOR_RESTRICT_CLASSES,
        StringUtil.merge(_velocityEngineConfiguration.restrictedClasses()));
    extendedProperties.setProperty(
        RuntimeConstants.INTROSPECTOR_RESTRICT_PACKAGES,
        StringUtil.merge(_velocityEngineConfiguration.restrictedPackages()));
    extendedProperties.setProperty(VelocityEngine.RESOURCE_LOADER, "liferay");
    extendedProperties.setProperty(
        "liferay." + VelocityEngine.RESOURCE_LOADER + ".cache", String.valueOf(cacheEnabled));
    extendedProperties.setProperty(
        "liferay." + VelocityEngine.RESOURCE_LOADER + ".resourceModificationCheckInterval",
        _velocityEngineConfiguration.resourceModificationCheckInterval() + "");
    extendedProperties.setProperty(
        "liferay." + VelocityEngine.RESOURCE_LOADER + ".class",
        LiferayResourceLoader.class.getName());
    extendedProperties.setProperty(
        VelocityEngine.RESOURCE_MANAGER_CLASS, LiferayResourceManager.class.getName());
    extendedProperties.setProperty(
        "liferay." + VelocityEngine.RESOURCE_MANAGER_CLASS + ".resourceModificationCheckInterval",
        _velocityEngineConfiguration.resourceModificationCheckInterval() + "");
    extendedProperties.setProperty(
        VelocityTemplateResourceLoader.class.getName(), _templateResourceLoader);
    extendedProperties.setProperty(
        VelocityEngine.RUNTIME_LOG_LOGSYSTEM_CLASS, _velocityEngineConfiguration.logger());
    extendedProperties.setProperty(
        VelocityEngine.RUNTIME_LOG_LOGSYSTEM + ".log4j.category",
        _velocityEngineConfiguration.loggerCategory());
    extendedProperties.setProperty(
        RuntimeConstants.UBERSPECT_CLASSNAME, SecureUberspector.class.getName());
    extendedProperties.setProperty(
        VelocityEngine.VM_LIBRARY,
        StringUtil.merge(_velocityEngineConfiguration.velocimacroLibrary()));
    extendedProperties.setProperty(
        VelocityEngine.VM_LIBRARY_AUTORELOAD, String.valueOf(!cacheEnabled));
    extendedProperties.setProperty(
        VelocityEngine.VM_PERM_ALLOW_INLINE_REPLACE_GLOBAL, String.valueOf(!cacheEnabled));

    _velocityEngine.setExtendedProperties(extendedProperties);

    _velocityEngine.init();
  }
  public static String getStringFromAttribute(int type, Serializable attribute) {

    if (attribute == null) {
      return StringPool.BLANK;
    }

    if ((type == ExpandoColumnConstants.BOOLEAN)
        || (type == ExpandoColumnConstants.DOUBLE)
        || (type == ExpandoColumnConstants.FLOAT)
        || (type == ExpandoColumnConstants.INTEGER)
        || (type == ExpandoColumnConstants.LONG)
        || (type == ExpandoColumnConstants.SHORT)) {

      return String.valueOf(attribute);
    } else if ((type == ExpandoColumnConstants.BOOLEAN_ARRAY)
        || (type == ExpandoColumnConstants.DOUBLE_ARRAY)
        || (type == ExpandoColumnConstants.FLOAT_ARRAY)
        || (type == ExpandoColumnConstants.INTEGER_ARRAY)
        || (type == ExpandoColumnConstants.LONG_ARRAY)
        || (type == ExpandoColumnConstants.SHORT_ARRAY)
        || (type == ExpandoColumnConstants.STRING_ARRAY)) {

      return StringUtil.merge(ArrayUtil.toStringArray((Object[]) attribute));
    } else if (type == ExpandoColumnConstants.DATE) {
      DateFormat dateFormat = _getDateFormat();

      return dateFormat.format((Date) attribute);
    } else if (type == ExpandoColumnConstants.DATE_ARRAY) {
      return StringUtil.merge(ArrayUtil.toStringArray((Date[]) attribute, _getDateFormat()));
    } else {
      return attribute.toString();
    }
  }
Ejemplo n.º 3
0
  protected void mergePortlets(Layout layout, String newTypeSettings, String portletsMergeMode) {

    try {
      UnicodeProperties previousTypeSettingsProperties = layout.getTypeSettingsProperties();

      LayoutTypePortlet previousLayoutType = (LayoutTypePortlet) layout.getLayoutType();

      LayoutTemplate previousLayoutTemplate = previousLayoutType.getLayoutTemplate();

      List<String> previousColumns = previousLayoutTemplate.getColumns();

      UnicodeProperties newTypeSettingsProperties = new UnicodeProperties(true);

      newTypeSettingsProperties.load(newTypeSettings);

      String layoutTemplateId =
          newTypeSettingsProperties.getProperty(LayoutTypePortletConstants.LAYOUT_TEMPLATE_ID);

      previousTypeSettingsProperties.setProperty(
          LayoutTypePortletConstants.LAYOUT_TEMPLATE_ID, layoutTemplateId);

      LayoutTemplate newLayoutTemplate =
          LayoutTemplateLocalServiceUtil.getLayoutTemplate(layoutTemplateId, false, null);

      String[] newPortletIds = new String[0];

      for (String columnId : newLayoutTemplate.getColumns()) {
        String columnValue = newTypeSettingsProperties.getProperty(columnId);

        String[] portletIds = StringUtil.split(columnValue);

        if (!previousColumns.contains(columnId)) {
          newPortletIds = ArrayUtil.append(newPortletIds, portletIds);
        } else {
          String[] previousPortletIds =
              StringUtil.split(previousTypeSettingsProperties.getProperty(columnId));

          portletIds = appendPortletIds(previousPortletIds, portletIds, portletsMergeMode);

          previousTypeSettingsProperties.setProperty(columnId, StringUtil.merge(portletIds));
        }
      }

      // Add portlets in non-existent column to the first column

      String columnId = previousColumns.get(0);

      String[] portletIds = StringUtil.split(previousTypeSettingsProperties.getProperty(columnId));

      appendPortletIds(portletIds, newPortletIds, portletsMergeMode);

      previousTypeSettingsProperties.setProperty(columnId, StringUtil.merge(portletIds));

      layout.setTypeSettings(previousTypeSettingsProperties.toString());
    } catch (IOException ioe) {
      layout.setTypeSettings(newTypeSettings);
    }
  }
Ejemplo n.º 4
0
  public static Map<String, String> getServerInfo() {
    Map<String, String> serverInfo = new HashMap<String, String>();

    serverInfo.put("hostName", getHostName());
    serverInfo.put("ipAddresses", StringUtil.merge(getIpAddresses()));
    serverInfo.put("macAddresses", StringUtil.merge(getMacAddresses()));

    return serverInfo;
  }
Ejemplo n.º 5
0
  protected void indexField(Document document, Element element, String elType, String elIndexType) {

    if (Validator.isNull(elIndexType)) {
      return;
    }

    com.liferay.portal.kernel.xml.Document structureDocument = element.getDocument();

    Element rootElement = structureDocument.getRootElement();

    String defaultLocale = GetterUtil.getString(rootElement.attributeValue("default-locale"));

    String name = encodeFieldName(element.attributeValue("name"));

    List<Element> dynamicContentElements = element.elements("dynamic-content");

    for (Element dynamicContentElement : dynamicContentElements) {
      String contentLocale =
          GetterUtil.getString(dynamicContentElement.attributeValue("language-id"));

      String[] value = new String[] {dynamicContentElement.getText()};

      if (elType.equals("multi-list")) {
        List<Element> optionElements = dynamicContentElement.elements("option");

        value = new String[optionElements.size()];

        for (int i = 0; i < optionElements.size(); i++) {
          value[i] = optionElements.get(i).getText();
        }
      }

      if (elIndexType.equals("keyword")) {
        if (Validator.isNull(contentLocale)) {
          document.addKeyword(name, value);
        } else {
          if (defaultLocale.equals(contentLocale)) {
            document.addKeyword(name, value);
          }

          document.addKeyword(name.concat(StringPool.UNDERLINE).concat(contentLocale), value);
        }
      } else if (elIndexType.equals("text")) {
        if (Validator.isNull(contentLocale)) {
          document.addText(name, StringUtil.merge(value, StringPool.SPACE));
        } else {
          if (defaultLocale.equals(contentLocale)) {
            document.addText(name, StringUtil.merge(value, StringPool.SPACE));
          }

          document.addText(
              name.concat(StringPool.UNDERLINE).concat(contentLocale),
              StringUtil.merge(value, StringPool.SPACE));
        }
      }
    }
  }
Ejemplo n.º 6
0
  @Override
  public int countByG_U_C_A(
      long groupId,
      long userId,
      long[] categoryIds,
      boolean anonymous,
      QueryDefinition queryDefinition)
      throws SystemException {

    Session session = null;

    try {
      session = openSession();

      String sql = CustomSQLUtil.get(COUNT_BY_G_U_C);

      if (ArrayUtil.isEmpty(categoryIds)) {
        sql = StringUtil.replace(sql, "(MBThread.categoryId = ?) AND", StringPool.BLANK);
      } else {
        sql =
            StringUtil.replace(
                sql,
                "MBThread.categoryId = ?",
                "MBThread.categoryId = "
                    + StringUtil.merge(categoryIds, " OR MBThread.categoryId = "));
      }

      sql = updateSQL(sql, queryDefinition);

      SQLQuery q = session.createSQLQuery(sql);

      q.addScalar(COUNT_COLUMN_NAME, Type.LONG);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(groupId);
      qPos.add(userId);
      qPos.add(anonymous);

      if (queryDefinition.getStatus() != WorkflowConstants.STATUS_ANY) {
        qPos.add(queryDefinition.getStatus());
      }

      Iterator<Long> itr = q.iterate();

      if (itr.hasNext()) {
        Long count = itr.next();

        if (count != null) {
          return count.intValue();
        }
      }

      return 0;
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
  @Ignore
  @Test
  public void testDeleteTimestampFromDLReferenceURLs() throws Exception {
    String content = replaceParameters(getContent("dl_references.txt"), _fileEntry);

    List<String> urls = getURLs(content);

    String urlContent = StringUtil.merge(urls, StringPool.NEW_LINE);

    content =
        ExportImportHelperUtil.replaceExportContentReferences(
            _portletDataContextExport, _referrerStagedModel, urlContent, true);

    String[] exportedURLs = content.split(StringPool.NEW_LINE);

    Assert.assertEquals(urls.size(), exportedURLs.length);

    for (int i = 0; i < urls.size(); i++) {
      String exportedUrl = exportedURLs[i];
      String url = urls.get(i);

      Assert.assertFalse(exportedUrl.matches("[?&]t="));

      if (url.contains("/documents/") && url.contains("?")) {
        Assert.assertTrue(exportedUrl.contains("width=100&height=100"));
      }

      if (url.contains("/documents/") && url.contains("mustkeep")) {
        Assert.assertTrue(exportedUrl.contains("mustkeep"));
      }
    }
  }
  public void updateKBArticlesPriorities(Map<Long, Double> resourcePrimKeyToPriorityMap)
      throws PortalException, SystemException {

    for (double priority : resourcePrimKeyToPriorityMap.values()) {
      validate(priority);
    }

    long[] resourcePrimKeys =
        StringUtil.split(StringUtil.merge(resourcePrimKeyToPriorityMap.keySet()), 0L);

    List<KBArticle> kbArticles1 =
        getKBArticles(resourcePrimKeys, WorkflowConstants.STATUS_ANY, null);

    for (KBArticle kbArticle1 : kbArticles1) {
      double priority = resourcePrimKeyToPriorityMap.get(kbArticle1.getResourcePrimKey());

      List<KBArticle> kbArticles2 =
          getKBArticleVersions(
              kbArticle1.getResourcePrimKey(),
              WorkflowConstants.STATUS_ANY,
              QueryUtil.ALL_POS,
              QueryUtil.ALL_POS,
              null);

      for (KBArticle kbArticle2 : kbArticles2) {
        kbArticle2.setPriority(priority);

        kbArticlePersistence.update(kbArticle2, false);
      }
    }
  }
Ejemplo n.º 9
0
  public List<Group> getMySites(String[] classNames, boolean includeControlPanel, int max)
      throws PortalException, SystemException {

    ThreadLocalCache<List<Group>> threadLocalCache =
        ThreadLocalCacheManager.getThreadLocalCache(Lifecycle.REQUEST, UserImpl.class.getName());

    String key = StringUtil.toHexString(max);

    if ((classNames != null) && (classNames.length > 0)) {
      key = StringUtil.merge(classNames).concat(StringPool.POUND).concat(key);
    }

    key = key.concat(StringPool.POUND).concat(String.valueOf(includeControlPanel));

    List<Group> myPlaces = threadLocalCache.get(key);

    if (myPlaces != null) {
      return myPlaces;
    }

    myPlaces = GroupServiceUtil.getUserPlaces(getUserId(), classNames, includeControlPanel, max);

    threadLocalCache.put(key, myPlaces);

    return myPlaces;
  }
  public PortletURL getPortletURL() throws PortalException {
    PortletURL portletURL = _liferayPortletResponse.createRenderURL();

    User selUser = PortalUtil.getSelectedUser(_request);

    if (selUser != null) {
      portletURL.setParameter("p_u_i_d", String.valueOf(selUser.getUserId()));
    }

    long[] selectedGroupIds =
        StringUtil.split(ParamUtil.getString(_request, "selectedGroupIds"), 0L);
    boolean includeCompany = ParamUtil.getBoolean(_request, "includeCompany");
    boolean includeCurrentGroup = ParamUtil.getBoolean(_request, "includeCurrentGroup", true);
    boolean includeUserPersonalSite = ParamUtil.getBoolean(_request, "includeUserPersonalSite");
    String eventName =
        ParamUtil.getString(
            _request, "eventName", _liferayPortletResponse.getNamespace() + "selectSite");
    String target = ParamUtil.getString(_request, "target");

    portletURL.setParameter("groupId", String.valueOf(getGroupId()));
    portletURL.setParameter("selectedGroupIds", StringUtil.merge(selectedGroupIds));
    portletURL.setParameter("type", getType());
    portletURL.setParameter("types", getTypes());
    portletURL.setParameter("displayStyle", getDisplayStyle());
    portletURL.setParameter("filter", getFilter());
    portletURL.setParameter("includeCompany", String.valueOf(includeCompany));
    portletURL.setParameter("includeCurrentGroup", String.valueOf(includeCurrentGroup));
    portletURL.setParameter("includeUserPersonalSite", String.valueOf(includeUserPersonalSite));
    portletURL.setParameter("manualMembership", String.valueOf(isManualMembership()));
    portletURL.setParameter("eventName", eventName);
    portletURL.setParameter("target", target);

    return portletURL;
  }
Ejemplo n.º 11
0
  protected void exportAssetTags(PortletDataContext portletDataContext) throws Exception {

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("tags");

    Map<String, String[]> assetTagNamesMap = portletDataContext.getAssetTagNamesMap();

    for (Map.Entry<String, String[]> entry : assetTagNamesMap.entrySet()) {
      String[] assetTagNameParts = StringUtil.split(entry.getKey(), CharPool.POUND);

      String className = assetTagNameParts[0];
      String classPK = assetTagNameParts[1];

      Element assetElement = rootElement.addElement("asset");

      assetElement.addAttribute("class-name", className);
      assetElement.addAttribute("class-pk", classPK);
      assetElement.addAttribute("tags", StringUtil.merge(entry.getValue()));
    }

    List<AssetTag> assetTags =
        AssetTagServiceUtil.getGroupTags(portletDataContext.getScopeGroupId());

    for (AssetTag assetTag : assetTags) {
      exportAssetTag(portletDataContext, assetTag, rootElement);
    }

    portletDataContext.addZipEntry(
        portletDataContext.getRootPath() + "/tags.xml", document.formattedString());
  }
    public FunctionNotDefined(Set<String> undefinedFunctionNames) {
      super(
          String.format(
              "The functions \"%s\" were not defined", StringUtil.merge(undefinedFunctionNames)));

      _undefinedFunctionNames = undefinedFunctionNames;
    }
  protected void lockProtectedGetActivityLimit(
      final long groupId,
      final User user,
      final SocialActivity activity,
      final SocialActivityCounterDefinition activityCounterDefinition)
      throws PortalException {

    final long classPK = getLimitClassPK(activity, activityCounterDefinition);

    String lockKey =
        StringUtil.merge(
            new Object[] {
              groupId,
              user.getUserId(),
              activity.getClassNameId(),
              classPK,
              activity.getType(),
              activityCounterDefinition.getName()
            },
            StringPool.POUND);

    LockProtectedAction<SocialActivityLimit> lockProtectedAction =
        new LockProtectedAction<SocialActivityLimit>(
            SocialActivityLimit.class,
            lockKey,
            PropsValues.SOCIAL_ACTIVITY_LOCK_TIMEOUT,
            PropsValues.SOCIAL_ACTIVITY_LOCK_RETRY_DELAY) {

          @Override
          protected SocialActivityLimit performProtectedAction() throws PortalException {

            SocialActivityLimit activityLimit =
                socialActivityLimitPersistence.fetchByG_U_C_C_A_A(
                    groupId,
                    user.getUserId(),
                    activity.getClassNameId(),
                    classPK,
                    activity.getType(),
                    activityCounterDefinition.getName());

            if (activityLimit == null) {
              activityLimit =
                  socialActivityLimitLocalService.addActivityLimit(
                      user.getUserId(),
                      activity.getGroupId(),
                      activity.getClassNameId(),
                      classPK,
                      activity.getType(),
                      activityCounterDefinition.getName(),
                      activityCounterDefinition.getLimitPeriod());
            }

            return activityLimit;
          }
        };

    lockProtectedAction.performAction();

    socialActivityLimitPersistence.cacheResult(lockProtectedAction.getReturnValue());
  }
Ejemplo n.º 14
0
  protected void exportAssetLinks(PortletDataContext portletDataContext) throws Exception {

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("links");

    Map<String, String[]> assetLinkUuidsMap = portletDataContext.getAssetLinkUuidsMap();

    for (Map.Entry<String, String[]> entry : assetLinkUuidsMap.entrySet()) {
      String[] assetLinkNameParts = StringUtil.split(entry.getKey(), CharPool.POUND);
      String[] targetAssetEntryUuids = entry.getValue();

      String sourceAssetEntryUuid = assetLinkNameParts[0];
      String assetLinkType = assetLinkNameParts[1];

      Element assetElement = rootElement.addElement("asset-link");

      assetElement.addAttribute("source-uuid", sourceAssetEntryUuid);
      assetElement.addAttribute("target-uuids", StringUtil.merge(targetAssetEntryUuids));
      assetElement.addAttribute("type", assetLinkType);
    }

    portletDataContext.addZipEntry(
        portletDataContext.getRootPath() + "/links.xml", document.formattedString());
  }
  @Override
  public void removeNestedColumns(String portletNamespace) {
    UnicodeProperties typeSettingsProperties = getTypeSettingsProperties();

    UnicodeProperties newTypeSettingsProperties = new UnicodeProperties();

    for (Map.Entry<String, String> entry : typeSettingsProperties.entrySet()) {

      String key = entry.getKey();

      if (!key.startsWith(portletNamespace)) {
        newTypeSettingsProperties.setProperty(key, entry.getValue());
      }
    }

    Layout layout = getLayout();

    layout.setTypeSettingsProperties(newTypeSettingsProperties);

    String nestedColumnIds =
        GetterUtil.getString(getTypeSettingsProperty(LayoutTypePortletConstants.NESTED_COLUMN_IDS));

    String[] nestedColumnIdsArray =
        ArrayUtil.removeByPrefix(StringUtil.split(nestedColumnIds), portletNamespace);

    setTypeSettingsProperty(
        LayoutTypePortletConstants.NESTED_COLUMN_IDS, StringUtil.merge(nestedColumnIdsArray));
  }
Ejemplo n.º 16
0
 protected void validate(String name) throws PortalException {
   if (!AssetUtil.isValidWord(name)) {
     throw new AssetTagException(
         StringUtil.merge(AssetUtil.INVALID_CHARACTERS, StringPool.SPACE),
         AssetTagException.INVALID_CHARACTER);
   }
 }
Ejemplo n.º 17
0
  private String _trimMultilineText(String text) {
    String[] textArray = StringUtil.splitLines(text);

    for (int i = 0; i < textArray.length; i++) {
      textArray[i] = textArray[i].trim();
    }

    return StringUtil.merge(textArray, " ");
  }
Ejemplo n.º 18
0
  protected List<MBThread> doFindByS_G_U_C(
      long groupId,
      long userId,
      long[] categoryIds,
      QueryDefinition queryDefinition,
      boolean inlineSQLHelper)
      throws SystemException {

    Session session = null;

    try {
      session = openSession();

      String sql = CustomSQLUtil.get(FIND_BY_S_G_U_C);

      if (ArrayUtil.isEmpty(categoryIds)) {
        sql = StringUtil.replace(sql, "(MBThread.categoryId = ?) AND", StringPool.BLANK);
      } else {
        sql =
            StringUtil.replace(
                sql,
                "MBThread.categoryId = ?",
                "MBThread.categoryId = "
                    + StringUtil.merge(categoryIds, " OR MBThread.categoryId = "));
      }

      sql = updateSQL(sql, queryDefinition);

      if (inlineSQLHelper) {
        sql =
            InlineSQLHelperUtil.replacePermissionCheck(
                sql, MBMessage.class.getName(), "MBThread.rootMessageId", groupId);
      }

      SQLQuery q = session.createSQLQuery(sql);

      q.addEntity("MBThread", MBThreadImpl.class);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(PortalUtil.getClassNameId(MBThread.class.getName()));
      qPos.add(groupId);
      qPos.add(userId);

      if (queryDefinition.getStatus() != WorkflowConstants.STATUS_ANY) {
        qPos.add(queryDefinition.getStatus());
      }

      return (List<MBThread>)
          QueryUtil.list(q, getDialect(), queryDefinition.getStart(), queryDefinition.getEnd());
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
  protected String getBookProperties(AmazonRankings amazonRankings) {
    String isbn = amazonRankings.getISBN();

    String authors = StringUtil.merge(amazonRankings.getAuthors(), ", ");

    String publisher =
        amazonRankings.getManufacturer() + "; (" + amazonRankings.getReleaseDateAsString() + ")";

    String properties = "ISBN=" + isbn + "\nAuthor=" + authors + "\nPublisher=" + publisher;

    return properties;
  }
Ejemplo n.º 20
0
  private static JSONObject _createRequest(
      String orderUuid, String productEntryName, int maxServers) throws Exception {

    JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

    jsonObject.put("version", 2);
    jsonObject.put("orderUuid", orderUuid);
    jsonObject.put("liferayVersion", ReleaseInfo.getBuildNumber());

    if (Validator.isNull(productEntryName)) {
      jsonObject.put("cmd", "QUERY");
    } else {
      jsonObject.put("cmd", "REGISTER");

      if (productEntryName.startsWith("basic")) {
        jsonObject.put("productEntryName", "basic");

        if (productEntryName.equals("basic-cluster")) {
          jsonObject.put("cluster", true);
          jsonObject.put("maxServers", maxServers);
        } else if (productEntryName.startsWith("basic-")) {
          String[] productNameArray = StringUtil.split(productEntryName, StringPool.DASH);

          if (productNameArray.length >= 3) {
            jsonObject.put("offeringEntryId", productNameArray[1]);
            jsonObject.put("clusterId", productNameArray[2]);
          }
        }
      } else {
        jsonObject.put("productEntryName", productEntryName);
      }

      jsonObject.put("hostName", getHostName());
      jsonObject.put("ipAddresses", StringUtil.merge(getIpAddresses()));
      jsonObject.put("macAddresses", StringUtil.merge(getMacAddresses()));
      jsonObject.put("serverId", Arrays.toString(getServerIdBytes()));
    }

    return jsonObject;
  }
Ejemplo n.º 21
0
  @Override
  public List<MBThread> findByG_U_C_A(
      long groupId,
      long userId,
      long[] categoryIds,
      boolean anonymous,
      QueryDefinition queryDefinition)
      throws SystemException {

    Session session = null;

    try {
      session = openSession();

      String sql = CustomSQLUtil.get(FIND_BY_G_U_C_A);

      if (ArrayUtil.isEmpty(categoryIds)) {
        sql = StringUtil.replace(sql, "(MBThread.categoryId = ?) AND", StringPool.BLANK);
      } else {
        sql =
            StringUtil.replace(
                sql,
                "MBThread.categoryId = ?",
                "MBThread.categoryId = "
                    + StringUtil.merge(categoryIds, " OR MBThread.categoryId = "));
      }

      sql = updateSQL(sql, queryDefinition);

      SQLQuery q = session.createSQLQuery(sql);

      q.addEntity("MBThread", MBThreadImpl.class);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(groupId);
      qPos.add(userId);
      qPos.add(anonymous);

      if (queryDefinition.getStatus() != WorkflowConstants.STATUS_ANY) {
        qPos.add(queryDefinition.getStatus());
      }

      return (List<MBThread>)
          QueryUtil.list(q, getDialect(), queryDefinition.getStart(), queryDefinition.getEnd());
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
  protected void setupWarProject(String dirName, String fileName) throws Exception {

    File propertiesFile = new File(dirName + "/" + fileName);

    Properties properties = new Properties();

    properties.load(new FileInputStream(propertiesFile));

    Set<String> jars = new TreeSet<String>();

    jars.addAll(getCommonJars());

    List<String> dependencyJars = getPortalDependencyJars(properties);

    jars.addAll(dependencyJars);

    File projectDir = new File(propertiesFile.getParent() + "/../..");

    jars.addAll(getImportSharedJars(projectDir));

    File libDir = new File(propertiesFile.getParent() + "/lib");

    jars.addAll(getRequiredDeploymentContextsJars(libDir, properties));

    writeEclipseFiles(libDir, projectDir, dependencyJars);

    String libDirPath =
        StringUtil.replace(libDir.getPath(), StringPool.BACK_SLASH, StringPool.SLASH);

    List<String> ignores = ListUtil.fromFile(libDir.getCanonicalPath() + "/../.gitignore");

    if (libDirPath.contains("/ext/") || ignores.contains("/lib")) {
      return;
    }

    File gitignoreFile = new File(libDir.getCanonicalPath() + "/.gitignore");

    System.out.println("Updating " + gitignoreFile);

    String[] gitIgnores = jars.toArray(new String[jars.size()]);

    for (int i = 0; i < gitIgnores.length; i++) {
      String gitIgnore = gitIgnores[i];

      if (Validator.isNotNull(gitIgnore) && !gitIgnore.startsWith("/")) {
        gitIgnores[i] = "/" + gitIgnore;
      }
    }

    _fileUtil.write(gitignoreFile, StringUtil.merge(gitIgnores, "\n"));
  }
  @Override
  public BackgroundTask addBackgroundTask(
      long userId,
      long groupId,
      String name,
      String[] servletContextNames,
      Class<?> taskExecutorClass,
      Map<String, Serializable> taskContextMap,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.findByPrimaryKey(userId);
    Date now = new Date();

    final long backgroundTaskId = counterLocalService.increment();

    BackgroundTask backgroundTask = backgroundTaskPersistence.create(backgroundTaskId);

    backgroundTask.setCompanyId(user.getCompanyId());
    backgroundTask.setCreateDate(serviceContext.getCreateDate(now));
    backgroundTask.setGroupId(groupId);
    backgroundTask.setModifiedDate(serviceContext.getModifiedDate(now));
    backgroundTask.setUserId(userId);
    backgroundTask.setUserName(user.getFullName());
    backgroundTask.setName(name);
    backgroundTask.setServletContextNames(StringUtil.merge(servletContextNames));
    backgroundTask.setTaskExecutorClassName(taskExecutorClass.getName());

    if (taskContextMap != null) {
      String taskContext = JSONFactoryUtil.serialize(taskContextMap);

      backgroundTask.setTaskContext(taskContext);
    }

    backgroundTask.setStatus(BackgroundTaskConstants.STATUS_NEW);

    backgroundTaskPersistence.update(backgroundTask);

    TransactionCommitCallbackRegistryUtil.registerCallback(
        new Callable<Void>() {

          @Override
          public Void call() throws Exception {
            backgroundTaskLocalService.triggerBackgroundTask(backgroundTaskId);

            return null;
          }
        });

    return backgroundTask;
  }
  protected Properties getProperties(
      ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws Exception {

    Properties properties = new Properties();

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

    Map<String, ConfigurationModel> configurationModels =
        _configurationModelRetriever.getConfigurationModels(themeDisplay.getLanguageId());

    String factoryPid = ParamUtil.getString(resourceRequest, "factoryPid");
    String pid = ParamUtil.getString(resourceRequest, "pid");

    ConfigurationModel configurationModel = configurationModels.get(pid);

    if ((configurationModel == null) && Validator.isNotNull(factoryPid)) {
      configurationModel = configurationModels.get(factoryPid);
    }

    if (configurationModel == null) {
      return properties;
    }

    Configuration configuration = _configurationModelRetriever.getConfiguration(pid);

    if (configuration == null) {
      return properties;
    }

    ExtendedAttributeDefinition[] attributeDefinitions =
        configurationModel.getAttributeDefinitions(ConfigurationModel.ALL);

    for (AttributeDefinition attributeDefinition : attributeDefinitions) {
      String[] values = AttributeDefinitionUtil.getProperty(attributeDefinition, configuration);

      String value = null;

      // See http://goo.gl/JhYK7g

      if (values.length == 1) {
        value = values[0];
      } else if (values.length > 1) {
        value = StringUtil.merge(values, "\n");
      }

      properties.setProperty(attributeDefinition.getID(), value);
    }

    return properties;
  }
  @Test
  public void testGetSelectedLayoutsJSONSelectNoLayouts() throws Exception {
    Layout layout = LayoutTestUtil.addLayout(_stagingGroup);

    LayoutTestUtil.addLayout(_stagingGroup, layout.getPlid());

    String selectedLayoutsJSON =
        ExportImportHelperUtil.getSelectedLayoutsJSON(
            _stagingGroup.getGroupId(), false, StringUtil.merge(new long[0]));

    JSONArray selectedLayoutsJSONArray = JSONFactoryUtil.createJSONArray(selectedLayoutsJSON);

    Assert.assertEquals(0, selectedLayoutsJSONArray.length());
  }
  public void moveEntries(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    long newFolderId = ParamUtil.getLong(actionRequest, "newFolderId");

    long[] folderIds = StringUtil.split(ParamUtil.getString(actionRequest, "folderIds"), 0L);

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(JournalArticle.class.getName(), actionRequest);

    for (long folderId : folderIds) {
      _journalFolderService.moveFolder(folderId, newFolderId, serviceContext);
    }

    List<String> invalidArticleIds = new ArrayList<>();

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

    String[] articleIds = StringUtil.split(ParamUtil.getString(actionRequest, "articleIds"));

    for (String articleId : articleIds) {
      try {
        _journalArticleService.moveArticle(
            themeDisplay.getScopeGroupId(),
            HtmlUtil.unescape(articleId),
            newFolderId,
            serviceContext);
      } catch (InvalidDDMStructureException idse) {
        if (_log.isWarnEnabled()) {
          _log.warn(idse.getMessage());
        }

        invalidArticleIds.add(articleId);
      }
    }

    if (!invalidArticleIds.isEmpty()) {
      StringBundler sb = new StringBundler(4);

      sb.append("Folder ");
      sb.append(newFolderId);
      sb.append(" does not allow the structures for articles: ");
      sb.append(StringUtil.merge(invalidArticleIds));

      throw new InvalidDDMStructureException(sb.toString());
    }

    sendEditEntryRedirect(actionRequest, actionResponse);
  }
Ejemplo n.º 27
0
  protected String getRequiredServletContextNames(HotDeployEvent hotDeployEvent) {

    List<String> requiredServletContextNames = new ArrayList<>();

    for (String dependentServletContextName : hotDeployEvent.getDependentServletContextNames()) {

      if (!_deployedServletContextNames.contains(dependentServletContextName)) {

        requiredServletContextNames.add(dependentServletContextName);
      }
    }

    Collections.sort(requiredServletContextNames);

    return StringUtil.merge(requiredServletContextNames, ", ");
  }
Ejemplo n.º 28
0
  protected String getActionIds_5(
      long companyId, long roleId, String className, String primKey, List<String> actionIds)
      throws SystemException {

    List<String> availableActionIds = new ArrayList<String>(actionIds.size());

    for (String actionId : actionIds) {
      if (PermissionLocalServiceUtil.hasRolePermission(
          roleId, companyId, className, ResourceConstants.SCOPE_INDIVIDUAL, primKey, actionId)) {

        availableActionIds.add(actionId);
      }
    }

    return StringUtil.merge(availableActionIds);
  }
Ejemplo n.º 29
0
  @Override
  protected String doRender(Field field, Locale locale) throws Exception {
    Format format = FastDateFormatFactoryUtil.getDate(locale);

    List<String> values = new ArrayList<String>();

    for (Serializable value : field.getValues(locale)) {
      if (Validator.isNull(value)) {
        continue;
      }

      values.add(format.format(value));
    }

    return StringUtil.merge(values, StringPool.COMMA_AND_SPACE);
  }
  public String[] getDisplayViews() {
    if (_displayViews == null) {
      JournalWebConfiguration journalWebConfiguration =
          (JournalWebConfiguration) _request.getAttribute(JournalWebConfiguration.class.getName());

      _displayViews =
          StringUtil.split(
              PrefsParamUtil.getString(
                  _portletPreferences,
                  _request,
                  "displayViews",
                  StringUtil.merge(journalWebConfiguration.displayViews())));
    }

    return _displayViews;
  }