示例#1
0
 public String getValue() {
   if (ArrayUtil.isNotEmpty(_values)) {
     return _values[0];
   } else {
     return null;
   }
 }
  @Override
  public void connect() {
    ImmutableSettings.Builder builder = ImmutableSettings.settingsBuilder();

    loadOptionalDefaultConfigurations(builder);

    String[] additionalConfigurations = elasticsearchConfiguration.additionalConfigurations();

    if (ArrayUtil.isNotEmpty(additionalConfigurations)) {
      StringBundler sb = new StringBundler(additionalConfigurations.length * 2);

      for (String additionalConfiguration : additionalConfigurations) {
        sb.append(additionalConfiguration);
        sb.append(StringPool.NEW_LINE);
      }

      builder.loadFromSource(sb.toString());
    }

    loadRequiredDefaultConfigurations(builder);

    loadSettingsContributors(builder);

    _client = createClient(builder);
  }
示例#3
0
  public Boolean isEnableConversions() throws Exception {
    if (_enableConversions == null) {
      _enableConversions = isOpenOfficeServerEnabled() && ArrayUtil.isNotEmpty(getExtensions());
    }

    return _enableConversions;
  }
示例#4
0
  @Override
  public List<ShoppingItem> findByKeywords(
      long groupId, long[] categoryIds, String keywords, int start, int end)
      throws SystemException {

    Session session = null;

    try {
      session = openSession();

      StringBundler query = new StringBundler();

      query.append("SELECT {ShoppingItem.*} FROM ShoppingItem ");
      query.append("WHERE ");
      query.append("ShoppingItem.groupId = ? AND (");

      if (ArrayUtil.isNotEmpty(categoryIds)) {
        query.append(StringPool.OPEN_PARENTHESIS);

        for (int i = 0; i < categoryIds.length; i++) {
          query.append("ShoppingItem.categoryId = ? ");

          if ((i + 1) < categoryIds.length) {
            query.append("OR ");
          }
        }

        query.append(") AND ");
      }

      query.append("(ShoppingItem.name LIKE ? OR ");
      query.append("ShoppingItem.description LIKE ? OR ");
      query.append("ShoppingItem.properties LIKE ?))");

      keywords = '%' + keywords + '%';

      SQLQuery q = session.createSynchronizedSQLQuery(query.toString());

      q.addEntity("ShoppingItem", ShoppingItemImpl.class);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(groupId);

      for (long categoryId : categoryIds) {
        qPos.add(categoryId);
      }

      qPos.add(keywords);
      qPos.add(keywords);
      qPos.add(keywords);

      return (List<ShoppingItem>) QueryUtil.list(q, getDialect(), start, end);
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
示例#5
0
  @Override
  public List<ShoppingItem> findByFeatured(long groupId, long[] categoryIds, int numOfItems)
      throws SystemException {

    int countByFeatured = countByFeatured(groupId, categoryIds);

    Session session = null;

    try {
      session = openSession();

      StringBundler query = new StringBundler();

      query.append("SELECT {ShoppingItem.*} FROM ShoppingItem ");
      query.append("WHERE ");
      query.append("ShoppingItem.groupId = ? AND (");

      if (ArrayUtil.isNotEmpty(categoryIds)) {
        query.append(StringPool.OPEN_PARENTHESIS);

        for (int i = 0; i < categoryIds.length; i++) {
          query.append("ShoppingItem.categoryId = ? ");

          if ((i + 1) < categoryIds.length) {
            query.append("OR ");
          }
        }

        query.append(") AND ");
      }

      query.append("ShoppingItem.featured = ? AND ");
      query.append("ShoppingItem.smallImage = ?");

      SQLQuery q = session.createSynchronizedSQLQuery(query.toString());

      q.addEntity("ShoppingItem", ShoppingItemImpl.class);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(groupId);

      for (long categoryId : categoryIds) {
        qPos.add(categoryId);
      }

      qPos.add(true);
      qPos.add(true);

      return (List<ShoppingItem>)
          QueryUtil.randomList(q, getDialect(), countByFeatured, numOfItems);
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
示例#6
0
  public void addArguments(Object[] arguments) {
    if (_queryType.equals(QueryType.STANDARD)) {
      throw new IllegalStateException("Standard queries cannot accept query arguments");
    }

    if (ArrayUtil.isNotEmpty(arguments)) {
      _arguments.addAll(Arrays.asList(arguments));
    }
  }
  @Override
  public void postProcessContextQuery(BooleanQuery contextQuery, SearchContext searchContext)
      throws Exception {

    addStatus(contextQuery, searchContext);

    if (searchContext.isIncludeAttachments()) {
      addRelatedClassNames(contextQuery, searchContext);
    }

    contextQuery.addRequiredTerm(Field.HIDDEN, searchContext.isIncludeAttachments());

    addSearchClassTypeIds(contextQuery, searchContext);

    String ddmStructureFieldName = (String) searchContext.getAttribute("ddmStructureFieldName");
    Serializable ddmStructureFieldValue = searchContext.getAttribute("ddmStructureFieldValue");

    if (Validator.isNotNull(ddmStructureFieldName) && Validator.isNotNull(ddmStructureFieldValue)) {

      String[] ddmStructureFieldNameParts =
          StringUtil.split(ddmStructureFieldName, StringPool.SLASH);

      DDMStructure structure =
          DDMStructureLocalServiceUtil.getStructure(
              GetterUtil.getLong(ddmStructureFieldNameParts[1]));

      String fieldName =
          StringUtil.replaceLast(
              ddmStructureFieldNameParts[2],
              StringPool.UNDERLINE.concat(LocaleUtil.toLanguageId(searchContext.getLocale())),
              StringPool.BLANK);

      try {
        ddmStructureFieldValue =
            DDMUtil.getIndexedFieldValue(ddmStructureFieldValue, structure.getFieldType(fieldName));
      } catch (StructureFieldException sfe) {
      }

      contextQuery.addRequiredTerm(
          ddmStructureFieldName, StringPool.QUOTE + ddmStructureFieldValue + StringPool.QUOTE);
    }

    String[] mimeTypes = (String[]) searchContext.getAttribute("mimeTypes");

    if (ArrayUtil.isNotEmpty(mimeTypes)) {
      BooleanQuery mimeTypesQuery = BooleanQueryFactoryUtil.create(searchContext);

      for (String mimeType : mimeTypes) {
        mimeTypesQuery.addTerm(
            "mimeType", StringUtil.replace(mimeType, CharPool.FORWARD_SLASH, CharPool.UNDERLINE));
      }

      contextQuery.add(mimeTypesQuery, BooleanClauseOccur.MUST);
    }
  }
示例#8
0
  protected List<File> getInstalledDirectories(final String context) throws Exception {

    List<File> installedDirs = new ArrayList<>();

    String installedDirName = DeployManagerUtil.getInstalledDir();

    File installedDir = new File(installedDirName, context);

    if (installedDir.exists()) {
      installedDirs.add(installedDir);
    } else {
      File deployWarDir = new File(installedDirName, context + ".war");

      installedDirs.add(deployWarDir);
    }

    if (ServerDetector.isTomcat()) {
      File tempDir = new File(SystemProperties.get(SystemProperties.TMP_DIR));

      File[] tempContextDirs =
          tempDir.listFiles(
              new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                  if (name.endsWith("-" + context)) {
                    return true;
                  }

                  return false;
                }
              });

      if (ArrayUtil.isNotEmpty(tempContextDirs)) {
        Arrays.sort(
            tempContextDirs,
            new Comparator<File>() {

              @Override
              public int compare(File file1, File file2) {
                String fileName1 = file1.getName();
                String fileName2 = file2.getName();

                return fileName1.compareTo(fileName2);
              }
            });

        File tempContextDir = tempContextDirs[tempContextDirs.length - 1];

        installedDirs.add(tempContextDir);
      }
    }

    return installedDirs;
  }
  protected DynamicQuery buildDynamicQuery(
      Long userId,
      String[] assetClassNames,
      Long[] assetClassPKs,
      Boolean completed,
      ServiceContext serviceContext) {

    DynamicQuery dynamicQuery =
        DynamicQueryFactoryUtil.forClass(KaleoInstance.class, getClassLoader());

    Property companyIdProperty = PropertyFactoryUtil.forName("companyId");

    dynamicQuery.add(companyIdProperty.eq(serviceContext.getCompanyId()));

    if (userId != null) {
      Property userIdProperty = PropertyFactoryUtil.forName("userId");

      dynamicQuery.add(userIdProperty.eq(userId));
    }

    if (ArrayUtil.isNotEmpty(assetClassNames)) {
      dynamicQuery.add(getAssetClassNames(assetClassNames));
    }

    if (ArrayUtil.isNotEmpty(assetClassPKs)) {
      dynamicQuery.add(getAssetClassPKs(assetClassPKs));
    }

    if (completed != null) {
      if (completed) {
        Property completionDateProperty = PropertyFactoryUtil.forName("completionDate");

        dynamicQuery.add(completionDateProperty.isNotNull());
      } else {
        Property completionDateProperty = PropertyFactoryUtil.forName("completionDate");

        dynamicQuery.add(completionDateProperty.isNull());
      }
    }

    return dynamicQuery;
  }
示例#10
0
  public static String getParentMessageIdString(Message message) throws Exception {

    // If the previous block failed, try to get the parent message ID from
    // the "References" header as explained in
    // http://cr.yp.to/immhf/thread.html. Some mail clients such as Yahoo!
    // Mail use the "In-Reply-To" header, so we check that as well.

    String parentHeader = null;

    String[] references = message.getHeader("References");

    if (ArrayUtil.isNotEmpty(references)) {
      String reference = references[0];

      int x = reference.lastIndexOf("<mb.");

      if (x > -1) {
        int y = reference.indexOf(">", x);

        parentHeader = reference.substring(x, y);
      }
    }

    if (parentHeader == null) {
      String[] inReplyToHeaders = message.getHeader("In-Reply-To");

      if (ArrayUtil.isNotEmpty(inReplyToHeaders)) {
        parentHeader = inReplyToHeaders[0];
      }
    }

    if (Validator.isNull(parentHeader) || !parentHeader.startsWith(MESSAGE_POP_PORTLET_PREFIX, 1)) {

      parentHeader = _getParentMessageIdFromSubject(message);
    }

    return parentHeader;
  }
  @Override
  public String getParameter(String name) {
    String[] values = _params.get(name);

    if (_inherit && (values == null)) {
      return super.getParameter(name);
    }

    if (ArrayUtil.isNotEmpty(values)) {
      return values[0];
    } else {
      return null;
    }
  }
  protected List<byte[]> getImages(UploadPortletRequest uploadPortletRequest, String imagePrefix)
      throws Exception {

    List<byte[]> images = new ArrayList<>();

    for (String name : getSortedParameterNames(uploadPortletRequest, imagePrefix)) {

      String contentType = uploadPortletRequest.getContentType(name);

      if (!MimeTypesUtil.isWebImage(contentType)) {
        throw new ProductEntryScreenshotsException();
      }

      int priority = GetterUtil.getInteger(name.substring(imagePrefix.length()));

      boolean preserveScreenshot =
          ParamUtil.getBoolean(uploadPortletRequest, "preserveScreenshot" + priority);

      byte[] bytes = null;

      if (preserveScreenshot) {
        SCProductScreenshot productScreenshot =
            getProductScreenshot(uploadPortletRequest, priority);

        Image image = null;

        if (imagePrefix.equals("fullImage")) {
          image = ImageLocalServiceUtil.getImage(productScreenshot.getFullImageId());
        } else {
          image = ImageLocalServiceUtil.getImage(productScreenshot.getThumbnailId());
        }

        bytes = image.getTextObj();
      } else {
        InputStream inputStream = uploadPortletRequest.getFileAsStream(name);

        if (inputStream != null) {
          bytes = FileUtil.getBytes(inputStream);
        }
      }

      if (ArrayUtil.isNotEmpty(bytes)) {
        images.add(bytes);
      } else {
        throw new ProductEntryScreenshotsException();
      }
    }

    return images;
  }
示例#13
0
  @Override
  public String format(
      HttpServletRequest request,
      String pattern,
      LanguageWrapper[] arguments,
      boolean translateArguments) {

    if (PropsValues.TRANSLATIONS_DISABLED) {
      return pattern;
    }

    String value = null;

    try {
      pattern = get(request, pattern);

      if (ArrayUtil.isNotEmpty(arguments)) {
        pattern = _escapePattern(pattern);

        Object[] formattedArguments = new Object[arguments.length];

        for (int i = 0; i < arguments.length; i++) {
          if (translateArguments) {
            formattedArguments[i] =
                arguments[i].getBefore()
                    + get(request, arguments[i].getText())
                    + arguments[i].getAfter();
          } else {
            formattedArguments[i] =
                arguments[i].getBefore() + arguments[i].getText() + arguments[i].getAfter();
          }
        }

        value = MessageFormat.format(pattern, formattedArguments);
      } else {
        value = pattern;
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e, e);
      }
    }

    return value;
  }
  protected void importLayoutIconImage(
      PortletDataContext portletDataContext, Layout importedLayout, Element layoutElement)
      throws Exception {

    String iconImagePath = layoutElement.elementText("icon-image-path");

    byte[] iconBytes = portletDataContext.getZipEntryAsByteArray(iconImagePath);

    if (ArrayUtil.isNotEmpty(iconBytes)) {
      if (importedLayout.getIconImageId() == 0) {
        long iconImageId = _counterLocalService.increment();

        importedLayout.setIconImageId(iconImageId);
      }

      _imageLocalService.updateImage(importedLayout.getIconImageId(), iconBytes);
    }
  }
示例#15
0
  protected String getImageFieldValue(UploadRequest uploadRequest, String fieldNameValue) {

    try {
      byte[] bytes = getImageBytes(uploadRequest, fieldNameValue);

      if (ArrayUtil.isNotEmpty(bytes)) {
        JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

        jsonObject.put("alt", uploadRequest.getParameter(fieldNameValue + "Alt"));
        jsonObject.put("data", UnicodeFormatter.bytesToHex(bytes));

        return jsonObject.toString();
      }
    } catch (Exception e) {
    }

    return StringPool.BLANK;
  }
  protected void getFileNames(List<String> fileNames, String dirName, String path) {

    String[] pathDirNames = FileUtil.listDirs(path);

    if (ArrayUtil.isNotEmpty(pathDirNames)) {
      for (String pathDirName : pathDirNames) {
        String subdirName = null;

        if (Validator.isBlank(dirName)) {
          subdirName = pathDirName;
        } else {
          subdirName = dirName + StringPool.SLASH + pathDirName;
        }

        getFileNames(fileNames, subdirName, path + StringPool.SLASH + pathDirName);
      }
    } else if (new File(path).isDirectory()) {
      fileNames.add(dirName);
    }
  }
示例#17
0
  @Override
  public String format(
      ResourceBundle resourceBundle,
      String pattern,
      Object[] arguments,
      boolean translateArguments) {

    if (PropsValues.TRANSLATIONS_DISABLED) {
      return pattern;
    }

    String value = null;

    try {
      pattern = get(resourceBundle, pattern);

      if (ArrayUtil.isNotEmpty(arguments)) {
        pattern = _escapePattern(pattern);

        Object[] formattedArguments = new Object[arguments.length];

        for (int i = 0; i < arguments.length; i++) {
          if (translateArguments) {
            formattedArguments[i] = get(resourceBundle, arguments[i].toString());
          } else {
            formattedArguments[i] = arguments[i];
          }
        }

        value = MessageFormat.format(pattern, formattedArguments);
      } else {
        value = pattern;
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn(e, e);
      }
    }

    return value;
  }
示例#18
0
  protected byte[] getImageBytes(UploadRequest uploadRequest, String fieldNameValue)
      throws Exception {

    File file = uploadRequest.getFile(fieldNameValue + "File");

    byte[] bytes = FileUtil.getBytes(file);

    if (ArrayUtil.isNotEmpty(bytes)) {
      return bytes;
    }

    String url = uploadRequest.getParameter(fieldNameValue + "URL");

    long imageId = GetterUtil.getLong(HttpUtil.getParameter(url, "img_id", false));

    Image image = ImageLocalServiceUtil.fetchImage(imageId);

    if (image == null) {
      return null;
    }

    return image.getTextObj();
  }
示例#19
0
  public Map<String, Serializable> getAttributes() {
    if (_attributes != null) {
      return _attributes;
    }

    _attributes = new HashMap<>();

    Map<String, String[]> parameters = _request.getParameterMap();

    for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
      String name = entry.getKey();
      String[] values = entry.getValue();

      if (ArrayUtil.isNotEmpty(values)) {
        if (values.length == 1) {
          _attributes.put(name, values[0]);
        } else {
          _attributes.put(name, values);
        }
      }
    }

    return _attributes;
  }
  @Override
  public void execute() throws MojoExecutionException {
    try {
      if (buildContext.isIncremental()) {
        Scanner scanner = buildContext.newScanner(baseDir);

        String[] includes = {"", "**/*.scss"};

        scanner.setIncludes(includes);

        scanner.scan();

        String[] includedFiles = scanner.getIncludedFiles();

        if (ArrayUtil.isNotEmpty(includedFiles)) {
          CSSBuilderInvoker.invoke(baseDir, _cssBuilderArgs);
        }
      } else {
        CSSBuilderInvoker.invoke(baseDir, _cssBuilderArgs);
      }
    } catch (Exception e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
  public static List<Portlet> getPortletDataHandlerPortlets(List<Layout> layouts) throws Exception {

    List<Portlet> portlets = new ArrayList<Portlet>();
    Set<String> rootPortletIds = new HashSet<String>();

    for (Layout layout : layouts) {
      if (!layout.isTypePortlet()) {
        continue;
      }

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

      for (String portletId : layoutTypePortlet.getPortletIds()) {
        Portlet portlet = PortletLocalServiceUtil.getPortletById(layout.getCompanyId(), portletId);

        if ((portlet == null) || rootPortletIds.contains(portlet.getRootPortletId())) {

          continue;
        }

        PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

        PortletDataHandlerControl[] portletDataHandlerControls =
            portletDataHandler.getExportConfigurationControls(
                layout.getCompanyId(), layout.getGroupId(), portlet, layout.getPrivateLayout());

        if (ArrayUtil.isNotEmpty(portletDataHandlerControls)) {
          rootPortletIds.add(portlet.getRootPortletId());

          portlets.add(portlet);
        }
      }
    }

    return portlets;
  }
  protected int doCountByC_G_C_N_D(
      long companyId,
      long[] groupIds,
      long[] calendarResourceIds,
      String[] names,
      String[] descriptions,
      boolean andOperator,
      boolean inlineSQLHelper)
      throws SystemException {

    if (groupIds == null) {
      groupIds = new long[0];
    }

    names = CustomSQLUtil.keywords(names);
    descriptions = CustomSQLUtil.keywords(descriptions, false);

    Session session = null;

    try {
      session = openSession();

      String sql = CustomSQLUtil.get(COUNT_BY_C_G_C_N_D);

      if (inlineSQLHelper) {
        sql =
            InlineSQLHelperUtil.replacePermissionCheck(
                sql, Calendar.class.getName(), "Calendar.calendarId", groupIds);
      }

      sql = StringUtil.replace(sql, "[$GROUP_ID$]", getGroupIds(groupIds));
      sql =
          StringUtil.replace(
              sql, "[$CALENDAR_RESOURCE_ID$]", getCalendarResourceIds(calendarResourceIds));
      sql = CustomSQLUtil.replaceKeywords(sql, "lower(name)", StringPool.LIKE, false, names);
      sql = CustomSQLUtil.replaceKeywords(sql, "description", StringPool.LIKE, false, descriptions);
      sql = CustomSQLUtil.replaceAndOperator(sql, andOperator);

      SQLQuery q = session.createSynchronizedSQLQuery(sql);

      q.addScalar(COUNT_COLUMN_NAME, Type.LONG);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(companyId);
      qPos.add(groupIds);

      if (ArrayUtil.isNotEmpty(calendarResourceIds)) {
        qPos.add(calendarResourceIds);
      }

      qPos.add(names, 2);
      qPos.add(descriptions, 2);

      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);
    }
  }
  protected FileEntry addFileEntry(ActionRequest actionRequest) throws Exception {

    UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

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

    long folderId = ParamUtil.getLong(uploadPortletRequest, "folderId");
    String sourceFileName = uploadPortletRequest.getFileName("file");
    String title = ParamUtil.getString(uploadPortletRequest, "title");
    String description = ParamUtil.getString(uploadPortletRequest, "description");
    String changeLog = ParamUtil.getString(uploadPortletRequest, "changeLog");

    if (folderId > 0) {
      Folder folder = DLAppServiceUtil.getFolder(folderId);

      if (folder.getGroupId() != themeDisplay.getScopeGroupId()) {
        throw new NoSuchFolderException("{folderId=" + folderId + "}");
      }
    }

    InputStream inputStream = null;

    try {
      String contentType = uploadPortletRequest.getContentType("file");

      long size = uploadPortletRequest.getSize("file");

      if (size == 0) {
        contentType = MimeTypesUtil.getContentType(title);
      }

      if (size > 0) {
        HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);

        String[] mimeTypes = DocumentSelectorUtil.getMimeTypes(request);

        if (ArrayUtil.isNotEmpty(mimeTypes) && !ArrayUtil.contains(mimeTypes, contentType)) {

          throw new FileMimeTypeException(contentType);
        }
      }

      inputStream = uploadPortletRequest.getFileAsStream("file");

      ServiceContext serviceContext =
          ServiceContextFactory.getInstance(DLFileEntry.class.getName(), uploadPortletRequest);

      FileEntry fileEntry =
          DLAppServiceUtil.addFileEntry(
              themeDisplay.getScopeGroupId(),
              folderId,
              sourceFileName,
              contentType,
              title,
              description,
              changeLog,
              inputStream,
              size,
              serviceContext);

      AssetPublisherUtil.addRecentFolderId(actionRequest, DLFileEntry.class.getName(), folderId);

      return fileEntry;
    } catch (Exception e) {
      UploadException uploadException =
          (UploadException) actionRequest.getAttribute(WebKeys.UPLOAD_EXCEPTION);

      if (uploadException != null) {
        if (uploadException.isExceededLiferayFileItemSizeLimit()) {
          throw new LiferayFileItemException();
        } else if (uploadException.isExceededSizeLimit()) {
          throw new FileSizeException(uploadException.getCause());
        }
      }

      throw e;
    } finally {
      StreamUtil.cleanUp(inputStream);
    }
  }
  @Override
  public void postProcessContextBooleanFilter(
      BooleanFilter contextBooleanFilter, SearchContext searchContext) throws Exception {

    addStatus(contextBooleanFilter, searchContext);

    if (searchContext.isIncludeAttachments()) {
      addRelatedClassNames(contextBooleanFilter, searchContext);
    }

    if (ArrayUtil.contains(
        searchContext.getFolderIds(), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {

      contextBooleanFilter.addRequiredTerm(Field.HIDDEN, searchContext.isIncludeAttachments());
    }

    addSearchClassTypeIds(contextBooleanFilter, searchContext);

    String ddmStructureFieldName = (String) searchContext.getAttribute("ddmStructureFieldName");
    Serializable ddmStructureFieldValue = searchContext.getAttribute("ddmStructureFieldValue");

    if (Validator.isNotNull(ddmStructureFieldName) && Validator.isNotNull(ddmStructureFieldValue)) {

      String[] ddmStructureFieldNameParts =
          StringUtil.split(ddmStructureFieldName, DDMIndexer.DDM_FIELD_SEPARATOR);

      DDMStructure structure =
          DDMStructureLocalServiceUtil.getStructure(
              GetterUtil.getLong(ddmStructureFieldNameParts[1]));

      String fieldName =
          StringUtil.replaceLast(
              ddmStructureFieldNameParts[2],
              StringPool.UNDERLINE.concat(LocaleUtil.toLanguageId(searchContext.getLocale())),
              StringPool.BLANK);

      try {
        ddmStructureFieldValue =
            DDMUtil.getIndexedFieldValue(ddmStructureFieldValue, structure.getFieldType(fieldName));
      } catch (StructureFieldException sfe) {
        if (_log.isDebugEnabled()) {
          _log.debug(sfe, sfe);
        }
      }

      BooleanQuery booleanQuery = new BooleanQueryImpl();

      booleanQuery.addRequiredTerm(
          ddmStructureFieldName, StringPool.QUOTE + ddmStructureFieldValue + StringPool.QUOTE);

      contextBooleanFilter.add(new QueryFilter(booleanQuery));
    }

    String[] mimeTypes = (String[]) searchContext.getAttribute("mimeTypes");

    if (ArrayUtil.isNotEmpty(mimeTypes)) {
      BooleanFilter mimeTypesBooleanFilter = new BooleanFilter();

      for (String mimeType : mimeTypes) {
        mimeTypesBooleanFilter.addTerm(
            "mimeType", StringUtil.replace(mimeType, CharPool.FORWARD_SLASH, CharPool.UNDERLINE));
      }

      contextBooleanFilter.add(mimeTypesBooleanFilter, BooleanClauseOccur.MUST);
    }
  }
  public static void main(String[] args) throws Exception {
    Map<String, String> arguments = ArgumentsUtil.parseArguments(args);

    try {
      SourceFormatterArgs sourceFormatterArgs = new SourceFormatterArgs();

      boolean autoFix =
          GetterUtil.getBoolean(arguments.get("source.auto.fix"), SourceFormatterArgs.AUTO_FIX);

      sourceFormatterArgs.setAutoFix(autoFix);

      String baseDirName =
          GetterUtil.getString(arguments.get("source.base.dir"), SourceFormatterArgs.BASE_DIR_NAME);

      sourceFormatterArgs.setBaseDirName(baseDirName);

      boolean formatCurrentBranch =
          GetterUtil.getBoolean(
              arguments.get("format.current.branch"), SourceFormatterArgs.FORMAT_CURRENT_BRANCH);

      sourceFormatterArgs.setFormatCurrentBranch(formatCurrentBranch);

      boolean formatLatestAuthor =
          GetterUtil.getBoolean(
              arguments.get("format.latest.author"), SourceFormatterArgs.FORMAT_LATEST_AUTHOR);

      sourceFormatterArgs.setFormatLatestAuthor(formatLatestAuthor);

      boolean formatLocalChanges =
          GetterUtil.getBoolean(
              arguments.get("format.local.changes"), SourceFormatterArgs.FORMAT_LOCAL_CHANGES);

      sourceFormatterArgs.setFormatLocalChanges(formatLocalChanges);

      if (formatCurrentBranch) {
        sourceFormatterArgs.setRecentChangesFileNames(
            GitUtil.getCurrentBranchFileNames(baseDirName));
      } else if (formatLatestAuthor) {
        sourceFormatterArgs.setRecentChangesFileNames(
            GitUtil.getLatestAuthorFileNames(baseDirName));
      } else if (formatLocalChanges) {
        sourceFormatterArgs.setRecentChangesFileNames(
            GitUtil.getLocalChangesFileNames(baseDirName));
      }

      String copyrightFileName =
          GetterUtil.getString(
              arguments.get("source.copyright.file"), SourceFormatterArgs.COPYRIGHT_FILE_NAME);

      sourceFormatterArgs.setCopyrightFileName(copyrightFileName);

      String[] fileNames = StringUtil.split(arguments.get("source.files"), StringPool.COMMA);

      if (ArrayUtil.isNotEmpty(fileNames)) {
        sourceFormatterArgs.setFileNames(Arrays.asList(fileNames));
      }

      boolean printErrors =
          GetterUtil.getBoolean(
              arguments.get("source.print.errors"), SourceFormatterArgs.PRINT_ERRORS);

      sourceFormatterArgs.setPrintErrors(printErrors);

      boolean throwException =
          GetterUtil.getBoolean(
              arguments.get("source.throw.exception"), SourceFormatterArgs.THROW_EXCEPTION);

      sourceFormatterArgs.setThrowException(throwException);

      boolean useProperties =
          GetterUtil.getBoolean(
              arguments.get("source.use.properties"), SourceFormatterArgs.USE_PROPERTIES);

      sourceFormatterArgs.setUseProperties(useProperties);

      SourceFormatter sourceFormatter = new SourceFormatter(sourceFormatterArgs);

      sourceFormatter.format();
    } catch (GitException ge) {
      System.out.println(ge.getMessage());

      System.exit(0);
    } catch (Exception e) {
      ArgumentsUtil.processMainException(arguments, e);
    }
  }
示例#26
0
  @Override
  public int countByFeatured(long groupId, long[] categoryIds) throws SystemException {

    Session session = null;

    try {
      session = openSession();

      StringBundler query = new StringBundler();

      query.append("SELECT COUNT(*) AS COUNT_VALUE FROM ShoppingItem ");
      query.append("WHERE ");
      query.append("ShoppingItem.groupId = ? AND (");

      if (ArrayUtil.isNotEmpty(categoryIds)) {
        query.append(StringPool.OPEN_PARENTHESIS);

        for (int i = 0; i < categoryIds.length; i++) {
          query.append("ShoppingItem.categoryId = ? ");

          if ((i + 1) < categoryIds.length) {
            query.append("OR ");
          }
        }

        query.append(") AND ");
      }

      query.append("ShoppingItem.featured = ? AND ");
      query.append("ShoppingItem.smallImage = ?");

      SQLQuery q = session.createSynchronizedSQLQuery(query.toString());

      q.addScalar(COUNT_COLUMN_NAME, Type.LONG);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(groupId);

      for (long categoryId : categoryIds) {
        qPos.add(categoryId);
      }

      qPos.add(true);
      qPos.add(true);

      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);
    }
  }
示例#27
0
  public Hits search(
      long companyId,
      long userId,
      String portletId,
      long groupId,
      long[] repositoryIds,
      String keywords,
      int start,
      int end) {

    try {
      SearchContext searchContext = new SearchContext();

      searchContext.setCompanyId(companyId);
      searchContext.setEnd(end);
      searchContext.setEntryClassNames(new String[] {DLFileEntryConstants.getClassName()});
      searchContext.setGroupIds(new long[] {groupId});

      Indexer indexer = IndexerRegistryUtil.getIndexer(DLFileEntryConstants.getClassName());

      searchContext.setSearchEngineId(indexer.getSearchEngineId());

      searchContext.setStart(start);
      searchContext.setUserId(userId);

      BooleanQuery contextQuery = BooleanQueryFactoryUtil.create(searchContext);

      contextQuery.addRequiredTerm(Field.PORTLET_ID, portletId);

      if (groupId > 0) {
        Group group = groupLocalService.getGroup(groupId);

        if (group.isLayout()) {
          contextQuery.addRequiredTerm(Field.SCOPE_GROUP_ID, groupId);

          groupId = group.getParentGroupId();
        }

        contextQuery.addRequiredTerm(Field.GROUP_ID, groupId);
      }

      if (ArrayUtil.isNotEmpty(repositoryIds)) {
        BooleanQuery repositoryIdsQuery = BooleanQueryFactoryUtil.create(searchContext);

        for (long repositoryId : repositoryIds) {
          try {
            if (userId > 0) {
              PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

              DLFolderPermission.check(permissionChecker, groupId, repositoryId, ActionKeys.VIEW);
            }

            if (repositoryId == DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {

              repositoryId = groupId;
            }

            TermQuery termQuery =
                TermQueryFactoryUtil.create(searchContext, "repositoryId", repositoryId);

            repositoryIdsQuery.add(termQuery, BooleanClauseOccur.SHOULD);
          } catch (Exception e) {
          }
        }

        contextQuery.add(repositoryIdsQuery, BooleanClauseOccur.MUST);
      }

      BooleanQuery searchQuery = BooleanQueryFactoryUtil.create(searchContext);

      searchQuery.addTerms(_KEYWORDS_FIELDS, keywords);

      BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext);

      fullQuery.add(contextQuery, BooleanClauseOccur.MUST);

      List<BooleanClause> clauses = searchQuery.clauses();

      if (!clauses.isEmpty()) {
        fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
      }

      return SearchEngineUtil.search(searchContext, fullQuery);
    } catch (Exception e) {
      throw new SystemException(e);
    }
  }
  protected List<Calendar> doFindByC_G_C_N_D(
      long companyId,
      long[] groupIds,
      long[] calendarResourceIds,
      String[] names,
      String[] descriptions,
      boolean andOperator,
      int start,
      int end,
      OrderByComparator orderByComparator,
      boolean inlineSQLHelper)
      throws SystemException {

    if (groupIds == null) {
      groupIds = new long[0];
    }

    names = CustomSQLUtil.keywords(names);
    descriptions = CustomSQLUtil.keywords(descriptions, false);

    Session session = null;

    try {
      session = openSession();

      String sql = CustomSQLUtil.get(FIND_BY_C_G_C_N_D);

      if (inlineSQLHelper) {
        sql =
            InlineSQLHelperUtil.replacePermissionCheck(
                sql, Calendar.class.getName(), "Calendar.calendarId", groupIds);
      }

      sql = StringUtil.replace(sql, "[$GROUP_ID$]", getGroupIds(groupIds));
      sql =
          StringUtil.replace(
              sql, "[$CALENDAR_RESOURCE_ID$]", getCalendarResourceIds(calendarResourceIds));
      sql = CustomSQLUtil.replaceKeywords(sql, "lower(name)", StringPool.LIKE, false, names);
      sql = CustomSQLUtil.replaceKeywords(sql, "description", StringPool.LIKE, false, descriptions);
      sql = CustomSQLUtil.replaceAndOperator(sql, andOperator);

      StringBundler sb = new StringBundler();

      if (orderByComparator != null) {
        appendOrderByComparator(sb, "Calendar.", orderByComparator);
      }

      sql = StringUtil.replace(sql, "[$ORDER_BY$]", sb.toString());

      SQLQuery q = session.createSynchronizedSQLQuery(sql);

      q.addEntity("Calendar", CalendarImpl.class);

      QueryPos qPos = QueryPos.getInstance(q);

      qPos.add(companyId);
      qPos.add(groupIds);

      if (ArrayUtil.isNotEmpty(calendarResourceIds)) {
        qPos.add(calendarResourceIds);
      }

      qPos.add(names, 2);
      qPos.add(descriptions, 2);

      return (List<Calendar>) QueryUtil.list(q, getDialect(), start, end);
    } catch (Exception e) {
      throw new SystemException(e);
    } finally {
      closeSession(session);
    }
  }
  protected static Map<String, Serializable> buildSettingsMap(
      long userId,
      long sourceGroupId,
      long sourcePlid,
      long targetGroupId,
      long targetPlid,
      String portletId,
      Boolean privateLayout,
      Map<Long, Boolean> layoutIdMap,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      String remoteAddress,
      int remotePort,
      String remotePathContext,
      Boolean secureConnection,
      Boolean remotePrivateLayout,
      Locale locale,
      TimeZone timeZone,
      String fileName) {

    Map<String, Serializable> settingsMap = new HashMap<>();

    if (Validator.isNotNull(fileName)) {
      settingsMap.put("fileName", fileName);
    }

    if (MapUtil.isNotEmpty(layoutIdMap)) {
      HashMap<Long, Boolean> serializableLayoutIdMap = new HashMap<>(layoutIdMap);

      settingsMap.put("layoutIdMap", serializableLayoutIdMap);
    }

    if (ArrayUtil.isNotEmpty(layoutIds)) {
      settingsMap.put("layoutIds", layoutIds);
    }

    if (locale != null) {
      settingsMap.put("locale", locale);
    }

    if (parameterMap != null) {
      HashMap<String, String[]> serializableParameterMap = new HashMap<>(parameterMap);

      if (layoutIds != null) {
        serializableParameterMap.remove("layoutIds");
      }

      settingsMap.put("parameterMap", serializableParameterMap);
    }

    if (Validator.isNotNull(portletId)) {
      settingsMap.put("portletId", portletId);
    }

    if (privateLayout != null) {
      settingsMap.put("privateLayout", privateLayout);
    }

    if (Validator.isNotNull(remoteAddress)) {
      settingsMap.put("remoteAddress", remoteAddress);
    }

    if (Validator.isNotNull(remotePathContext)) {
      settingsMap.put("remotePathContext", remotePathContext);
    }

    if (remotePort > 0) {
      settingsMap.put("remotePort", remotePort);
    }

    if (remotePrivateLayout != null) {
      settingsMap.put("remotePrivateLayout", remotePrivateLayout);
    }

    if (secureConnection != null) {
      settingsMap.put("secureConnection", secureConnection);
    }

    if (sourceGroupId > 0) {
      settingsMap.put("sourceGroupId", sourceGroupId);
    }

    if (sourcePlid > 0) {
      settingsMap.put("sourcePlid", sourcePlid);
    }

    if (targetGroupId > 0) {
      settingsMap.put("targetGroupId", targetGroupId);
    }

    if (targetPlid > 0) {
      settingsMap.put("targetPlid", targetPlid);
    }

    if (timeZone != null) {
      settingsMap.put("timezone", timeZone);
    }

    settingsMap.put("userId", userId);

    return settingsMap;
  }