コード例 #1
0
ファイル: UserController.java プロジェクト: weiq/cunframework
  private void fillUserOrganization(User m, Long[] organizationIds, Long[][] jobIds) {
    if (ArrayUtils.isEmpty(organizationIds)) {
      return;
    }
    for (int i = 0, l = organizationIds.length; i < l; i++) {

      // 仅新增/修改一个 spring会自动split(“,”)--->给数组
      if (l == 1) {
        for (int j = 0, l2 = jobIds.length; j < l2; j++) {
          UserOrganizationJob userOrganizationJob = new UserOrganizationJob();
          userOrganizationJob.setOrganizationId(organizationIds[i]);
          userOrganizationJob.setJobId(jobIds[j][0]);
          m.addOrganizationJob(userOrganizationJob);
        }
      } else {
        Long[] jobId = jobIds[i];
        for (int j = 0, l2 = jobId.length; j < l2; j++) {
          UserOrganizationJob userOrganizationJob = new UserOrganizationJob();
          userOrganizationJob.setOrganizationId(organizationIds[i]);
          userOrganizationJob.setJobId(jobId[j]);
          m.addOrganizationJob(userOrganizationJob);
        }
      }
    }
  }
コード例 #2
0
  @Transactional
  public void delete(Serializable[] ids) {
    if (ArrayUtils.isEmpty(ids)) {
      return;
    }

    List idList = new ArrayList();
    for (Serializable id : ids) {
      idList.add(id);
    }

    boolean logicDeleteableEntity = LogicDeleteable.class.isAssignableFrom(this.entityClass);

    if (logicDeleteableEntity) {
      String ql =
          String.format(
              "update %s x set x.isDeleted='1', x.updateDate = ?2, x.updateBy = ?3 where x.%s in (?1)",
              new Object[] {this.entityName, this.idName});
      this.repositoryHelper.batchUpdate(ql, new Object[] {idList, new Date(), getCurrentAuditor()});
    } else {
      String ql =
          String.format(
              "delete from %s x where x.%s in (?1)", new Object[] {this.entityName, this.idName});
      this.repositoryHelper.batchUpdate(ql, new Object[] {idList});
    }
  }
コード例 #3
0
ファイル: BaseService.java プロジェクト: kanabc12/es
  /**
   * 根据主键删除相应实体
   *
   * @param ids 实体
   */
  @Transactional
  public void delete(ID[] ids) {
    if (ArrayUtils.isEmpty(ids)) {
      return;
    }
    List<M> models = new ArrayList<M>();
    for (ID id : ids) {
      M model = null;
      try {
        model = (M) entityClass.newInstance();
      } catch (Exception e) {
        throw new RuntimeException("batch delete " + entityClass.getName() + " error", e);
      }
      try {
        BeanUtils.setProperty(model, "id", id);
      } catch (Exception e) {
        throw new RuntimeException(
            "batch delete " + entityClass.getName() + " error, can not set id", e);
      }

      models.add(model);
    }

    if (models.get(0) instanceof LogicDeleteable) {
      String hql =
          String.format(
              "update %s o set o.deleted=true where o in (?1)", this.entityClass.getSimpleName());
      baseDefaultRepositoryImpl.batchUpdate(hql, models);
    } else {
      baseRepository.deleteInBatch(models);
    }
  }
コード例 #4
0
 private void displayExtraTypeIcon(
     String cardName,
     ParcelableMedia[] media,
     ParcelableLocation location,
     String placeFullName,
     boolean sensitive) {
   if (TwitterCardUtils.CARD_NAME_AUDIO.equals(cardName)) {
     extraTypeView.setImageResource(
         sensitive ? R.drawable.ic_action_warning : R.drawable.ic_action_music);
     extraTypeView.setVisibility(View.VISIBLE);
   } else if (TwitterCardUtils.CARD_NAME_ANIMATED_GIF.equals(cardName)) {
     extraTypeView.setImageResource(
         sensitive ? R.drawable.ic_action_warning : R.drawable.ic_action_movie);
     extraTypeView.setVisibility(View.VISIBLE);
   } else if (TwitterCardUtils.CARD_NAME_PLAYER.equals(cardName)) {
     extraTypeView.setImageResource(
         sensitive ? R.drawable.ic_action_warning : R.drawable.ic_action_play_circle);
     extraTypeView.setVisibility(View.VISIBLE);
   } else if (!ArrayUtils.isEmpty(media)) {
     if (hasVideo(media)) {
       extraTypeView.setImageResource(
           sensitive ? R.drawable.ic_action_warning : R.drawable.ic_action_movie);
     } else {
       extraTypeView.setImageResource(
           sensitive ? R.drawable.ic_action_warning : R.drawable.ic_action_gallery);
     }
     extraTypeView.setVisibility(View.VISIBLE);
   } else if (ParcelableLocationUtils.isValidLocation(location)
       || !TextUtils.isEmpty(placeFullName)) {
     extraTypeView.setImageResource(R.drawable.ic_action_location);
     extraTypeView.setVisibility(View.VISIBLE);
   } else {
     extraTypeView.setVisibility(View.GONE);
   }
 }
コード例 #5
0
ファイル: WebUtils.java プロジェクト: zyyecho/venues
 public static List<RequestKV> getParameterMap(
     HttpServletRequest req, Map<String, String> skipParam) {
   @SuppressWarnings("unchecked")
   Enumeration<String> it = req.getParameterNames();
   Set<String> keys = new HashSet<String>();
   List<RequestKV> list = new ArrayList<RequestKV>();
   while (it.hasMoreElements()) {
     String key = it.nextElement();
     if ((skipParam != null) && skipParam.containsKey(key)) {
       continue;
     }
     if (keys.contains(key)) {
       continue;
     }
     keys.add(key);
     String values[] = req.getParameterValues(key);
     if (!ArrayUtils.isEmpty(values)) {
       for (String v : values) {
         RequestKV kv = new RequestKV(key, v);
         list.add(kv);
       }
     }
   }
   return list;
 }
コード例 #6
0
  public SetSearchField(String oper, T... vals) {
    if (!ArrayUtils.isEmpty(vals)) {
      CollectionUtils.addAll(values, vals);
    }

    this.operation = oper;
  }
コード例 #7
0
ファイル: Base64.java プロジェクト: adchilds/Secuur
  /**
   * Encodes the given array of bytes using the Base64 encoding algorithm.
   *
   * @param bytesToEncode the array of bytes to encode
   * @return a new array of encoded bytes
   */
  public static byte[] encode(byte[] bytesToEncode) {
    if (ArrayUtils.isEmpty(bytesToEncode)) {
      return new byte[0];
    }

    return ENCODER.encode(bytesToEncode).getBytes();
  }
コード例 #8
0
 public JarDuplicates(JarFile... jarFiles) {
   super();
   if (ArrayUtils.isEmpty(jarFiles) || jarFiles.length < 2) {
     throw new IllegalArgumentException("Must have 2 or more jar files.");
   }
   this.jarFiles = jarFiles;
 }
コード例 #9
0
  @RequestMapping(value = "/upload", method = RequestMethod.POST)
  @ResponseBody
  public AjaxUploadResponse upload(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam("parentPath") String parentPath,
      @RequestParam("conflict") String conflict,
      @RequestParam(value = "files[]", required = false) MultipartFile[] files)
      throws UnsupportedEncodingException {

    String rootPath = sc.getRealPath(ROOT_DIR);
    parentPath = URLDecoder.decode(parentPath, Constants.ENCODING);
    File parent = new File(rootPath + File.separator + parentPath);

    // The file upload plugin makes use of an Iframe Transport module for browsers like Microsoft
    // Internet Explorer and Opera, which do not yet support XMLHTTPRequest file uploads.
    response.setContentType("text/plain");

    AjaxUploadResponse ajaxUploadResponse = new AjaxUploadResponse();

    if (ArrayUtils.isEmpty(files)) {
      return ajaxUploadResponse;
    }

    for (MultipartFile file : files) {
      String filename = file.getOriginalFilename();
      long size = file.getSize();
      try {
        File current = new File(parent, filename);
        if (current.exists() && "ignore".equals(conflict)) {
          ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.conflict.error"));
          continue;
        }
        String url =
            FileUploadUtils.upload(request, parentPath, file, ALLOWED_EXTENSION, MAX_SIZE, false);
        String deleteURL =
            viewName("/delete") + "?paths=" + URLEncoder.encode(url, Constants.ENCODING);

        ajaxUploadResponse.add(filename, size, url, deleteURL);

        continue;
      } catch (IOException e) {
        LogUtils.logError("file upload error", e);
        ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.server.error"));
        continue;
      } catch (InvalidExtensionException e) {
        ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.not.allow.extension"));
        continue;
      } catch (FileUploadBase.FileSizeLimitExceededException e) {
        ajaxUploadResponse.add(filename, size, MessageUtils.message("upload.exceed.maxSize"));
        continue;
      } catch (FileNameLengthLimitExceededException e) {
        ajaxUploadResponse.add(
            filename, size, MessageUtils.message("upload.filename.exceed.length"));
        continue;
      }
    }
    return ajaxUploadResponse;
  }
コード例 #10
0
ファイル: NodeOrgServiceImpl.java プロジェクト: caidongyun/CS
 public void preOrgDelete(Integer[] ids) {
   if (ArrayUtils.isEmpty(ids)) {
     return;
   }
   for (Integer id : ids) {
     dao.deleteByOrgId(id);
   }
 }
コード例 #11
0
ファイル: Base64.java プロジェクト: adchilds/Secuur
  /**
   * Decodes the given array of bytes using the Base64 decoding algorithm.
   *
   * @param bytesToDecode the array of bytes to encode
   * @return a new array of decoded bytes
   */
  public static byte[] decode(byte[] bytesToDecode) {
    if (ArrayUtils.isEmpty(bytesToDecode)) {
      return new byte[0];
    }

    String decodedString = decode(new String(bytesToDecode, Charsets.UTF_8));
    return decodedString.getBytes();
  }
コード例 #12
0
  /**
   * 从请求生成url地址
   *
   * @param req
   * @param skipPageParam 是否跳过分页
   * @param parameter 需要添加在后面的默认的参数列表
   * @return
   */
  @SuppressWarnings("unchecked")
  private static String initUrl(
      HttpServletRequest req, Map<String, String> parameter, Map<String, String> skipParam) {
    StringBuffer sb = new StringBuffer();
    Enumeration<String> it = req.getParameterNames();
    int pos = 0;
    Set<String> keys = new HashSet<String>();
    while (it.hasMoreElements()) {
      String key = it.nextElement();
      if (skipParam != null && skipParam.containsKey(key)) {
        continue;
      }
      if (parameter != null && parameter.containsKey(key)) // 如果在默认参数列表当中已经
      continue;
      if (keys.contains(key)) // 去掉重复的key
      continue;
      keys.add(key);
      String values[] = req.getParameterValues(key);
      if (!ArrayUtils.isEmpty(values)) {
        for (String v : values) {
          if (pos++ > 0) {
            sb.append("&");
          }
          sb.append(key);
          sb.append("=");
          sb.append(v);
        }
      }
    }
    if (parameter != null && !parameter.isEmpty()) {
      for (String key : parameter.keySet()) {
        if (pos++ > 0) {
          sb.append("&");
        }
        sb.append(key);
        sb.append("=");
        sb.append(parameter.get(key));
      }
    }
    if (sb.length() > 0) {
      sb.append("&");
    }
    sb.append("page=");
    StringBuffer uri = new StringBuffer();
    uri.append(req.getRequestURI());
    if (sb.length() > 1) {
      uri.append("?");
      uri.append(sb.toString());
    }

    // 去掉url当中出现多次/的情况
    String url = uri.toString().replaceAll("/{1,}", "/");
    //		if(url.startsWith("/")){
    //			url=url.substring(1);
    //		}

    return url;
  }
コード例 #13
0
 private static CacheListApp[] getMultiPointNavigationApps() {
   if (ArrayUtils.isEmpty(apps)) {
     apps =
         new CacheListApp[] {
           new InternalCacheListMap(), new LocusCacheListApp(false), new LocusCacheListApp(true)
         };
   }
   return apps;
 }
コード例 #14
0
  public static String printArr(Object[] objArr) {
    if (ArrayUtils.isEmpty(objArr)) return StringUtils.EMPTY;

    StringBuilder sbd = new StringBuilder();
    for (Object obj : objArr) {
      sbd.append(obj).append(",");
    }
    if (sbd.length() > 0) sbd.deleteCharAt(sbd.length() - 1);
    return sbd.toString();
  }
コード例 #15
0
 private boolean needLazyInit(String beanName) {
   if (ArrayUtils.isEmpty(noneLazyBeanNames)) {
     return true;
   }
   for (String noneLazyBeanName : noneLazyBeanNames) {
     if (beanName.equals(noneLazyBeanName)) {
       return false;
     }
   }
   return true;
 }
コード例 #16
0
 /**
  * Whether all jar files share the same version or if at least one of them have a different
  * version.
  *
  * @return <code>true</code> if at least one jar file has a different version
  */
 public boolean hasVersionConflict() {
   if (ArrayUtils.isEmpty(jarFiles)) {
     return false;
   }
   String version = jarFiles[0].getVersion();
   for (JarFile jarFile : jarFiles) {
     if (!Objects.equals(version, jarFile.getVersion())) {
       return true;
     }
   }
   return false;
 }
コード例 #17
0
ファイル: Login.java プロジェクト: mambaliu/c-geo-opensource
 /** put viewstates into request parameters */
 public static void putViewstates(final Parameters params, final String[] viewstates) {
   if (ArrayUtils.isEmpty(viewstates)) {
     return;
   }
   params.put("__VIEWSTATE", viewstates[0]);
   if (viewstates.length > 1) {
     for (int i = 1; i < viewstates.length; i++) {
       params.put("__VIEWSTATE" + i, viewstates[i]);
     }
     params.put("__VIEWSTATEFIELDCOUNT", String.valueOf(viewstates.length));
   }
 }
コード例 #18
0
 /**
  * 设置等级
  *
  * @param dealerJoin
  * @param idAry
  * @return
  * @throws BusinessException
  * @author 施建波
  */
 @RequiresPermissions("brand:center")
 @ResponseBody
 @RequestMapping(value = "/setDealer")
 public JsonMessage setDealer(DealerJoin dealerJoin, String[] idAry) throws BusinessException {
   if (ArrayUtils.isEmpty(idAry) || StringUtils.isBlank(dealerJoin.getBrandsId())) {
     throw new BusinessException(CommonConst.PARAM_NULL);
   }
   UserPrincipal userPrincipal = OnLineUserUtils.getCurrentBrand();
   String brandId = brandLevelService.getBrandParentRefrenceId(userPrincipal.getRefrenceId());
   dealerJoin.setBrandId(brandId);
   dealerJoinService.updateDealerLevel(dealerJoin, idAry);
   return this.getJsonMessage(CommonConst.SUCCESS);
 }
コード例 #19
0
 public static String tagsToHtml(Tag[] tags) {
   String result = "<div class=\"feature-tags\"></div>";
   if (!ArrayUtils.isEmpty(tags)) {
     List<String> tagList = new ArrayList<>();
     for (Tag tag : tags) {
       String link = tag.getName().replace("@", "").trim() + ".html";
       String ref = "<a href=\"" + link + "\">" + tag.getName() + "</a>";
       tagList.add(ref);
     }
     result = "<div class=\"feature-tags\">" + StringUtils.join(tagList.toArray(), ",") + "</div>";
   }
   return result;
 }
コード例 #20
0
  private String getFilename(final ProfilesSelection profileSelection, final ISelection selection) {
    final String fileName = ExportShapeUtils.guessExportFileName(selection);
    if (!StringUtils.isEmpty(fileName)) return fileName;

    // if no theme, we should use the container.
    final Feature container = profileSelection.getContainer();
    if (container != null)
      return FeatureHelper.getAnnotationValue(container, IAnnotation.ANNO_LABEL);

    final IProfileFeature[] profiles = profileSelection.getProfiles();
    if (!ArrayUtils.isEmpty(profiles)) return profiles[0].getName();

    return null;
  }
コード例 #21
0
 public List<Node> findByIds(Integer[] ids, Integer selfId) {
   List<Node> list = new ArrayList<Node>();
   if (!ArrayUtils.isEmpty(ids)) {
     Set<Integer> idSet = new HashSet<Integer>();
     for (Integer id : ids) {
       if (!idSet.contains(id) && !id.equals(selfId)) {
         idSet.add(id);
         list.add(get(id));
       }
     }
   }
   list.add(get(selfId));
   return list;
 }
コード例 #22
0
 private void build() {
   this.description = Description.createSuiteDescription(this.suiteClass);
   final Method[] methods = this.suiteClass.getMethods();
   if (!ArrayUtils.isEmpty(methods)) {
     this.testMethod = new TestMethod[methods.length];
     int index = 0;
     for (Method method : methods) {
       this.addTestMethod(new TestMethodImpl(method), index++);
     }
     Arrays.sort(this.getTestMethods(), TestMethodComparator.getInstance());
   }
   this.annotations = this.suiteClass.getAnnotations();
   this.qunitReqources = this.suiteClass.getAnnotation(QUnitResources.class).value();
   final Method deployMethod =
       ReflectOperations.findFirstMethodWithAnnotation(
           getSuiteClass().getMethods(), Deployment.class);
   this.deploymentMethod = (deployMethod != null) ? new DeploymentMethodImpl(deployMethod) : null;
   return;
 }
コード例 #23
0
ファイル: SimpleBaseRepository.java プロジェクト: Newsite/es
 /**
  * 根据主键删除相应实体
  *
  * @param ids 实体
  */
 public void delete(final ID[] ids) {
   if (ArrayUtils.isEmpty(ids)) {
     return;
   }
   List<M> models = new ArrayList<M>();
   for (ID id : ids) {
     M model = null;
     try {
       model = entityClass.newInstance();
     } catch (Exception e) {
       throw new RuntimeException("batch delete " + entityClass + " error", e);
     }
     try {
       BeanUtils.setProperty(model, idName, id);
     } catch (Exception e) {
       throw new RuntimeException("batch delete " + entityClass + " error, can not set id", e);
     }
     models.add(model);
   }
   deleteInBatch(models);
 }
コード例 #24
0
  /**
   * Construct a MOLGENIS generator
   *
   * @param options with generator settings
   * @param generatorsToUse optional list of generator classes to include
   * @throws Exception
   */
  public <E extends Generator> Molgenis(
      MolgenisOptions options, String outputPath, Class<? extends Generator>... generatorsToUse)
      throws Exception {
    BasicConfigurator.configure();

    this.loadFieldTypes();

    this.options = options;

    Logger.getLogger("freemarker.cache").setLevel(Level.INFO);
    logger.info("\nMOLGENIS version " + org.molgenis.Version.convertToString());
    logger.info("working dir: " + System.getProperty("user.dir"));

    // clean options
    if (outputPath != null) {
      // workaround for java string escaping bug in freemarker (see
      // UsedMolgenisOptionsGen.ftl)
      outputPath = outputPath.replace('\\', '/');
      if (!outputPath.endsWith("/")) outputPath = outputPath + "/";
    }

    options.output_src = outputPath != null ? outputPath + options.output_src : options.output_src;
    if (!options.output_src.endsWith("/"))
      options.output_src = options.output_src.endsWith("/") + "/";
    options.output_hand =
        outputPath != null ? outputPath + options.output_hand : options.output_hand;
    if (!options.output_hand.endsWith("/")) options.output_hand = options.output_hand + "/";
    options.output_web = outputPath != null ? outputPath + options.output_web : options.output_web;
    if (!options.output_web.endsWith("/")) options.output_web = options.output_web + "/";
    options.output_doc = outputPath != null ? outputPath + options.output_doc : options.output_doc;
    if (!options.output_doc.endsWith("/")) options.output_doc = options.output_doc + "/";

    // DOCUMENTATION
    if (options.generate_doc) {
      generators.add(new FileFormatDocGen());
      // check if dot is available to prevent error lists in the build logs
      try {
        Runtime.getRuntime().exec("dot -?");
        generators.add(new DotDocGen());
        generators.add(new DotDocMinimalGen());
      } catch (Exception e) {
        // dot not available
      }
      generators.add(new ObjectModelDocGen());
      generators.add(new DotDocModuleDependencyGen());
    } else {
      logger.info("Skipping documentation ....");
    }

    if (options.generate_jpa) {
      if (options.generate_db) {
        generators.add(new DatabaseConfigGen());
      }

      generators.add(new DataTypeGen());
      generators.add(new EntityMetaDataGen());
      generators.add(new JpaRepositoryGen());
      generators.add(new JDBCMetaDatabaseGen());

      if (options.generate_persistence) {
        generators.add(new PersistenceGen());
      }

      if (options.generate_jpa_repository_source) {
        generators.add(new JpaRepositorySourceGen());
      }
    } else {
      logger.info("SEVERE: Skipping ALL SQL ....");
    }

    if (options.generate_entityio) {
      generators.add(new EntitiesImporterGen());
      generators.add(new EntitiesValidatorGen());
    }

    // clean out generators
    List<Generator> use = new ArrayList<Generator>();
    if (!ArrayUtils.isEmpty(generatorsToUse)) {
      for (Class<? extends Generator> c : generatorsToUse) {
        use.add(c.newInstance());
      }
      generators = use;
    }

    logger.debug("\nUsing generators:\n" + toString());

    // parsing model
    model = MolgenisModel.parse(options);
  }
コード例 #25
0
 @Override
 public void update() {
   final IPolygonWithName[] elements = m_data.getElements();
   setEnabled(!ArrayUtils.isEmpty(elements));
 }
コード例 #26
0
 public List<Node> findByIds(Integer... ids) {
   if (ArrayUtils.isEmpty(ids)) {
     return Collections.emptyList();
   }
   return dao.findAll(Arrays.asList(ids));
 }
コード例 #27
0
 protected String getParameter(String name) {
   String[] _value = paraMap.get(name);
   return ArrayUtils.isEmpty(_value) ? null : _value[0];
 }
コード例 #28
0
  private boolean needRemove(String beanName, BeanDefinition beanDefinition) {

    if (ArrayUtils.isNotEmpty(removedBeanNames)) {
      for (String removedBeanName : removedBeanNames) {
        if (beanName.equals(removedBeanName)) {
          return true;
        }
        if (beanDefinition.getBeanClassName().equals(removedBeanName)) {
          return true;
        }
      }
    }

    if (this.removedBeanProperties != null) {
      Set<String[]> propertiesSet = removedBeanProperties.get(beanName);
      if (propertiesSet != null) {
        Iterator<String[]> iter = propertiesSet.iterator();
        MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();

        while (iter.hasNext()) {
          String[] properties = iter.next();
          if (properties.length == 1) {

            // 先移除
            propertyValues.removePropertyValue(properties[0]);

            // 如果需要替换,替换掉值(只支持基本属性)
            if (this.replaceBeanProperties != null) {
              String key = beanName + "@" + properties[0];
              if (this.replaceBeanProperties.containsKey(key)) {
                propertyValues.add(properties[0], this.replaceBeanProperties.get(key));
              }
            }
          } else {
            PropertyValue propertyValue = propertyValues.getPropertyValue(properties[0]);
            if (propertyValue != null) {
              Object nextValue = propertyValue.getValue();
              // 目前只支持 二级 + 移除Map的
              if (nextValue instanceof ManagedMap) {

                TypedStringValue typedStringValue = new TypedStringValue(properties[1]);
                ((ManagedMap) nextValue).remove(typedStringValue);

                // 如果需要替换,替换掉值(只支持基本属性)
                if (this.replaceBeanProperties != null) {
                  String key = beanName + "@" + properties[0] + "@" + properties[1];
                  if (this.replaceBeanProperties.containsKey(key)) {
                    ((ManagedMap) nextValue)
                        .put(properties[1], this.replaceBeanProperties.get(key));
                  }
                }
              }
            }
          }
        }
      }
    }

    String className = beanDefinition.getBeanClassName();

    // spring data jpa
    if (className.equals("com.sishuok.es.common.repository.support.SimpleBaseRepositoryFactoryBean")
        || className.equals(
            "org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean")) {
      PropertyValue repositoryInterfaceValue =
          beanDefinition.getPropertyValues().getPropertyValue("repositoryInterface");
      if (repositoryInterfaceValue != null) {
        className = repositoryInterfaceValue.getValue().toString();
      }
    }

    if (ArrayUtils.isEmpty(this.removedClassPatterns)) {
      return false;
    }

    if (ArrayUtils.isNotEmpty(this.includeClassPatterns)) {
      for (String includeClassPattern : includeClassPatterns) {
        if (className.matches(includeClassPattern)) {
          return false;
        }
      }
    }

    for (String removedClassPattern : removedClassPatterns) {
      if (className.matches(removedClassPattern)) {
        return true;
      }
    }

    return false;
  }
コード例 #29
0
  @Override
  public void displayStatus(
      @NonNull final ParcelableStatus status,
      final boolean displayInReplyTo,
      final boolean shouldDisplayExtraType) {

    final MediaLoaderWrapper loader = adapter.getMediaLoader();
    final AsyncTwitterWrapper twitter = adapter.getTwitterWrapper();
    final TwidereLinkify linkify = adapter.getTwidereLinkify();
    final BidiFormatter formatter = adapter.getBidiFormatter();
    final Context context = adapter.getContext();
    final boolean nameFirst = adapter.isNameFirst();
    final boolean showCardActions = isCardActionsShown();

    actionButtons.setVisibility(showCardActions ? View.VISIBLE : View.GONE);
    itemMenu.setVisibility(showCardActions ? View.VISIBLE : View.GONE);
    if (statusContentLowerSpace != null) {
      statusContentLowerSpace.setVisibility(showCardActions ? View.GONE : View.VISIBLE);
    }

    final long replyCount = status.reply_count;
    final long retweetCount;
    final long favoriteCount;

    if (TwitterCardUtils.isPoll(status)) {
      statusInfoLabel.setText(R.string.label_poll);
      statusInfoIcon.setImageResource(R.drawable.ic_activity_action_poll);
      statusInfoLabel.setVisibility(View.VISIBLE);
      statusInfoIcon.setVisibility(View.VISIBLE);

      if (statusContentUpperSpace != null) {
        statusContentUpperSpace.setVisibility(View.GONE);
      }
    } else if (status.retweet_id != null) {
      final String retweetedBy =
          UserColorNameManager.decideDisplayName(
              status.retweet_user_nickname,
              status.retweeted_by_user_name,
              status.retweeted_by_user_screen_name,
              nameFirst);
      statusInfoLabel.setText(
          context.getString(R.string.name_retweeted, formatter.unicodeWrap(retweetedBy)));
      statusInfoIcon.setImageResource(R.drawable.ic_activity_action_retweet);
      statusInfoLabel.setVisibility(View.VISIBLE);
      statusInfoIcon.setVisibility(View.VISIBLE);

      if (statusContentUpperSpace != null) {
        statusContentUpperSpace.setVisibility(View.GONE);
      }
    } else if (status.in_reply_to_status_id != null
        && status.in_reply_to_user_id != null
        && displayInReplyTo) {
      final String inReplyTo =
          UserColorNameManager.decideDisplayName(
              status.in_reply_to_user_nickname,
              status.in_reply_to_name,
              status.in_reply_to_screen_name,
              nameFirst);
      statusInfoLabel.setText(
          context.getString(R.string.in_reply_to_name, formatter.unicodeWrap(inReplyTo)));
      statusInfoIcon.setImageResource(R.drawable.ic_activity_action_reply);
      statusInfoLabel.setVisibility(View.VISIBLE);
      statusInfoIcon.setVisibility(View.VISIBLE);

      if (statusContentUpperSpace != null) {
        statusContentUpperSpace.setVisibility(View.GONE);
      }
    } else {
      statusInfoLabel.setVisibility(View.GONE);
      statusInfoIcon.setVisibility(View.GONE);

      if (statusContentUpperSpace != null) {
        statusContentUpperSpace.setVisibility(View.VISIBLE);
      }
    }

    boolean skipLinksInText = status.extras != null && status.extras.support_entities;
    if (status.is_quote) {

      quotedNameView.setVisibility(View.VISIBLE);
      quotedTextView.setVisibility(View.VISIBLE);
      quoteIndicator.setVisibility(View.VISIBLE);

      quotedNameView.setName(
          UserColorNameManager.decideNickname(
              status.quoted_user_nickname, status.quoted_user_name));
      quotedNameView.setScreenName("@" + status.quoted_user_screen_name);

      if (adapter.getLinkHighlightingStyle() != VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE) {
        final SpannableStringBuilder text =
            SpannableStringBuilder.valueOf(status.quoted_text_unescaped);
        ParcelableStatusUtils.applySpans(text, status.quoted_spans);
        linkify.applyAllLinks(
            text,
            status.account_key,
            getLayoutPosition(),
            status.is_possibly_sensitive,
            adapter.getLinkHighlightingStyle(),
            skipLinksInText);
        quotedTextView.setText(text);
      } else {
        final String text = status.quoted_text_unescaped;
        quotedTextView.setText(text);
      }

      quoteIndicator.setColor(status.quoted_user_color);
      itemContent.drawStart(status.user_color);
    } else {

      quotedNameView.setVisibility(View.GONE);
      quotedTextView.setVisibility(View.GONE);
      quoteIndicator.setVisibility(View.GONE);

      if (status.is_retweet) {
        final int retweetUserColor = status.retweet_user_color;
        final int userColor = status.user_color;
        if (retweetUserColor == 0) {
          itemContent.drawStart(userColor);
        } else if (userColor == 0) {
          itemContent.drawStart(retweetUserColor);
        } else {
          itemContent.drawStart(retweetUserColor, userColor);
        }
      } else {
        itemContent.drawStart(status.user_color);
      }
    }

    if (status.is_retweet) {
      timeView.setTime(status.retweet_timestamp);
    } else {
      timeView.setTime(status.timestamp);
    }
    nameView.setName(UserColorNameManager.decideNickname(status.user_nickname, status.user_name));
    nameView.setScreenName("@" + status.user_screen_name);

    if (statusInfoSpace != null) {
      statusInfoSpace.setVisibility(View.VISIBLE);
    }

    if (adapter.isProfileImageEnabled()) {
      profileImageView.setVisibility(View.VISIBLE);
      if (profileImageSpace != null) {
        profileImageSpace.setVisibility(View.VISIBLE);
      }
      loader.displayProfileImage(profileImageView, status);

      profileTypeView.setImageResource(
          getUserTypeIconRes(status.user_is_verified, status.user_is_protected));
      profileTypeView.setVisibility(View.VISIBLE);
    } else {
      profileTypeView.setVisibility(View.GONE);
      profileImageView.setVisibility(View.GONE);
      if (profileImageSpace != null) {
        profileImageSpace.setVisibility(View.GONE);
      }

      loader.cancelDisplayTask(profileImageView);

      profileTypeView.setImageDrawable(null);
      profileTypeView.setVisibility(View.GONE);
    }

    if (adapter.shouldShowAccountsColor()) {
      itemContent.drawEnd(status.account_color);
    } else {
      itemContent.drawEnd();
    }

    if (adapter.isMediaPreviewEnabled()
        && (adapter.isSensitiveContentEnabled() || !status.is_possibly_sensitive)) {
      mediaPreview.setStyle(adapter.getMediaPreviewStyle());
      quoteMediaPreview.setStyle(adapter.getMediaPreviewStyle());

      final boolean showQuotedMedia = !ArrayUtils.isEmpty(status.quoted_media);
      final boolean showMedia = !showQuotedMedia && !ArrayUtils.isEmpty(status.media);

      mediaPreview.setVisibility(showMedia ? View.VISIBLE : View.GONE);
      if (textMediaSpace != null) {
        textMediaSpace.setVisibility(
            !status.is_quote && (showMedia || showCardActions) ? View.GONE : View.VISIBLE);
      }
      quoteMediaPreview.setVisibility(showQuotedMedia ? View.VISIBLE : View.GONE);
      if (quotedTextMediaSpace != null) {
        quotedTextMediaSpace.setVisibility(
            !status.is_quote || showQuotedMedia ? View.GONE : View.VISIBLE);
      }

      mediaPreview.displayMedia(
          status.media, loader, status.account_key, -1, this, adapter.getMediaLoadingHandler());
      quoteMediaPreview.displayMedia(
          status.quoted_media,
          loader,
          status.account_key,
          -1,
          this,
          adapter.getMediaLoadingHandler());
    } else {
      mediaPreview.setVisibility(View.GONE);
      quoteMediaPreview.setVisibility(View.GONE);
      if (textMediaSpace != null) {
        textMediaSpace.setVisibility(
            showCardActions && !status.is_quote ? View.GONE : View.VISIBLE);
      }
      if (quotedTextMediaSpace != null) {
        quotedTextMediaSpace.setVisibility(status.is_quote ? View.VISIBLE : View.GONE);
      }
    }

    if (adapter.getLinkHighlightingStyle() != VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE) {
      final SpannableStringBuilder text = SpannableStringBuilder.valueOf(status.text_unescaped);
      ParcelableStatusUtils.applySpans(text, status.spans);
      linkify.applyAllLinks(
          text,
          status.account_key,
          getLayoutPosition(),
          status.is_possibly_sensitive,
          adapter.getLinkHighlightingStyle(),
          skipLinksInText);
      textView.setText(text);
    } else {
      textView.setText(status.text_unescaped);
    }

    if (replyCount > 0) {
      replyCountView.setText(UnitConvertUtils.calculateProperCount(replyCount));
      replyCountView.setVisibility(View.VISIBLE);
    } else {
      replyCountView.setText(null);
      replyCountView.setVisibility(View.GONE);
    }

    if (twitter.isDestroyingStatus(status.account_key, status.my_retweet_id)) {
      retweetIconView.setActivated(false);
      retweetCount = Math.max(0, status.retweet_count - 1);
    } else {
      final boolean creatingRetweet = twitter.isCreatingRetweet(status.account_key, status.id);
      retweetIconView.setActivated(
          creatingRetweet
              || status.retweeted
              || Utils.isMyRetweet(
                  status.account_key, status.retweeted_by_user_key, status.my_retweet_id));
      retweetCount = status.retweet_count + (creatingRetweet ? 1 : 0);
    }

    if (retweetCount > 0) {
      retweetCountView.setText(UnitConvertUtils.calculateProperCount(retweetCount));
      retweetCountView.setVisibility(View.VISIBLE);
    } else {
      retweetCountView.setText(null);
      retweetCountView.setVisibility(View.GONE);
    }
    if (twitter.isDestroyingFavorite(status.account_key, status.id)) {
      favoriteIconView.setActivated(false);
      favoriteCount = Math.max(0, status.favorite_count - 1);
    } else {
      final boolean creatingFavorite = twitter.isCreatingFavorite(status.account_key, status.id);
      favoriteIconView.setActivated(creatingFavorite || status.is_favorite);
      favoriteCount = status.favorite_count + (creatingFavorite ? 1 : 0);
    }
    if (favoriteCount > 0) {
      favoriteCountView.setText(UnitConvertUtils.calculateProperCount(favoriteCount));
      favoriteCountView.setVisibility(View.VISIBLE);
    } else {
      favoriteCountView.setText(null);
      favoriteCountView.setVisibility(View.GONE);
    }
    if (shouldDisplayExtraType) {
      displayExtraTypeIcon(
          status.card_name,
          status.media,
          status.location,
          status.place_full_name,
          status.is_possibly_sensitive);
    } else {
      extraTypeView.setVisibility(View.GONE);
    }

    nameView.updateText(formatter);
    quotedNameView.updateText(formatter);
  }
コード例 #30
0
  private String exportXAR(XWikiContext context)
      throws XWikiException, IOException, FilterException {
    XWikiRequest request = context.getRequest();

    boolean history = Boolean.valueOf(request.get("history"));
    boolean backup = Boolean.valueOf(request.get("backup"));
    String author = request.get("author");
    String description = request.get("description");
    String licence = request.get("licence");
    String version = request.get("version");
    String name = request.get("name");
    String[] pages = request.getParameterValues("pages");
    boolean all = ArrayUtils.isEmpty(pages);

    if (!context.getWiki().getRightService().hasWikiAdminRights(context)) {
      context.put("message", "needadminrights");
      return "exception";
    }

    if (name == null) {
      return "export";
    }

    if (StringUtils.isBlank(name)) {
      if (all) {
        name = "backup";
      } else {
        name = "export";
      }
    }

    if (context.getWiki().ParamAsLong("xwiki.action.export.xar.usefilter", 1) == 1) {
      // Create input wiki stream
      DocumentInstanceInputProperties inputProperties = new DocumentInstanceInputProperties();

      // We don't want to log the details
      inputProperties.setVerbose(false);

      inputProperties.setWithJRCSRevisions(history);
      inputProperties.setWithRevisions(false);

      EntityReferenceSet entities = new EntityReferenceSet();

      if (all) {
        entities.includes(new WikiReference(context.getWikiId()));
      } else {
        // Find all page references and add them for processing
        Collection<String> pageList = getPagesToExport(pages, context);
        DocumentReferenceResolver<String> resolver =
            Utils.getComponent(DocumentReferenceResolver.TYPE_STRING, "current");
        for (String pageName : pageList) {
          entities.includes(resolver.resolve(pageName));
        }
      }

      inputProperties.setEntities(entities);

      InputFilterStreamFactory inputFilterStreamFactory =
          Utils.getComponent(
              InputFilterStreamFactory.class, FilterStreamType.XWIKI_INSTANCE.serialize());

      InputFilterStream inputFilterStream =
          inputFilterStreamFactory.createInputFilterStream(inputProperties);

      // Create output wiki stream
      XAROutputProperties xarProperties = new XAROutputProperties();

      // We don't want to log the details
      xarProperties.setVerbose(false);

      XWikiResponse response = context.getResponse();

      xarProperties.setTarget(new DefaultOutputStreamOutputTarget(response.getOutputStream()));
      xarProperties.setPackageName(name);
      if (description != null) {
        xarProperties.setPackageDescription(description);
      }
      if (licence != null) {
        xarProperties.setPackageLicense(licence);
      }
      if (author != null) {
        xarProperties.setPackageAuthor(author);
      }
      if (version != null) {
        xarProperties.setPackageVersion(version);
      }
      xarProperties.setPackageBackupPack(backup);
      xarProperties.setPreserveVersion(backup || history);

      BeanOutputFilterStreamFactory<XAROutputProperties> xarFilterStreamFactory =
          Utils.getComponent(
              (Type) OutputFilterStreamFactory.class, FilterStreamType.XWIKI_XAR_11.serialize());

      OutputFilterStream outputFilterStream =
          xarFilterStreamFactory.createOutputFilterStream(xarProperties);

      // Export
      response.setContentType("application/zip");
      response.addHeader(
          "Content-disposition", "attachment; filename=" + Util.encodeURI(name, context) + ".xar");

      inputFilterStream.read(outputFilterStream.getFilter());

      inputFilterStream.close();
      outputFilterStream.close();

      // Flush
      response.getOutputStream().flush();

      // Indicate that we are done with the response so no need to add anything
      context.setFinished(true);
    } else {
      PackageAPI export = ((PackageAPI) context.getWiki().getPluginApi("package", context));
      if (export == null) {
        // No Packaging plugin configured
        return "exception";
      }

      export.setWithVersions(history);

      if (author != null) {
        export.setAuthorName(author);
      }

      if (description != null) {
        export.setDescription(description);
      }

      if (licence != null) {
        export.setLicence(licence);
      }

      if (version != null) {
        export.setVersion(version);
      }

      export.setBackupPack(backup);

      export.setName(name);

      if (all) {
        export.backupWiki();
      } else {
        if (pages != null) {
          for (int i = 0; i < pages.length; i++) {
            String pageName = pages[i];
            String defaultAction = request.get("action_" + pageName);
            int iAction;
            try {
              iAction = Integer.parseInt(defaultAction);
            } catch (Exception e) {
              iAction = 0;
            }
            export.add(pageName, iAction);
          }
        }
        export.export();
      }
    }

    return null;
  }