@Override
  public DBObject filterInternal(String url, WebPage webPage, DBObject parsedDBObject) {
    String pageText = webPage.getPageText();
    DocumentFragment doc = parse(pageText);

    // 获取产品信息
    NodeList nodes = selectNodeList(doc, "//UL[@class='xieceprodutu']/li");
    if (nodes != null && nodes.getLength() > 0) {
      for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);
        String content = n.getTextContent();
        // 中文冒号分隔
        String[] nodeTexts = StringUtils.split(content, ":");
        // 容错处理,英文冒号分隔
        if (nodeTexts.length <= 1) {
          nodeTexts = StringUtils.split(content, ":");
        }
        if (nodeTexts.length > 1) {
          putKeyValue(parsedDBObject, nodeTexts[0].trim(), nodeTexts[1].trim());
        }
      }
      return parsedDBObject;
    } else {

      return null;
    }
  }
  protected Map<String, String> extractDatabases(final String migrations)
      throws MojoExecutionException {
    String[] migrationNames = StringUtils.stripAll(StringUtils.split(migrations, ","));

    final List<String> availableDatabases = getAvailableDatabases();

    if (migrationNames == null) {
      return Collections.<String, String>emptyMap();
    }

    final Map<String, String> databases = Maps.newHashMap();

    if (migrationNames.length == 1 && migrationNames[0].equalsIgnoreCase("all")) {
      migrationNames = availableDatabases.toArray(new String[availableDatabases.size()]);
    }

    for (String migration : migrationNames) {
      final String[] migrationFields = StringUtils.stripAll(StringUtils.split(migration, "="));

      if (migrationFields == null || migrationFields.length < 1 || migrationFields.length > 2) {
        throw new MojoExecutionException("Migration " + migration + " is invalid.");
      }

      if (!availableDatabases.contains(migrationFields[0])) {
        throw new MojoExecutionException("Database " + migrationFields[0] + " is unknown!");
      }

      databases.put(migrationFields[0], (migrationFields.length == 1 ? null : migrationFields[1]));
    }

    return databases;
  }
  private Column getColumn(final Attributes attributes) {
    final String type = attributes.getValue("type");
    final String[] dataTypeAndName = StringUtils.split(type, ",");
    Validate.notNull(
        dataTypeAndName,
        "The 'type' attribute of the column element must contain a comma separated value pair, eg, type=\"12,varchar\"."
            + getErrorMessage());
    final int dataType = Integer.parseInt(dataTypeAndName[0]);
    final String typeName = dataTypeAndName[1];

    int columnSize;
    int scale = 0;
    final String size = attributes.getValue("size");
    if (size.contains(",")) {
      final String[] precisionScale = StringUtils.split(size, ",");
      columnSize = Integer.parseInt(precisionScale[0]);
      scale = Integer.parseInt(precisionScale[1]);
    } else {
      columnSize = Integer.parseInt(size);
    }

    if (StringUtils.isNotBlank(attributes.getValue("scale"))) {
      scale = Integer.parseInt(attributes.getValue("scale"));
    }

    final Column column =
        new Column(
            attributes.getValue(DatabaseXmlUtils.NAME), dataType, typeName, columnSize, scale);
    column.setDescription(attributes.getValue(DatabaseXmlUtils.DESCRIPTION));
    column.setPrimaryKey(Boolean.parseBoolean(attributes.getValue("primaryKey")));
    column.setRequired(Boolean.parseBoolean(attributes.getValue("required")));

    return column;
  }
Пример #4
0
 private void init() {
   List<String> lines = readUtil.readByLine();
   for (String line : lines) {
     String[] paras = StringUtils.split(line, "$");
     String[] words = StringUtils.split(paras[0], " ");
     Template template = new Template(words, paras[1]);
     templates.add(template);
   }
 }
 @SuppressWarnings("unused")
 @PostConstruct
 private void init() {
   if (!isBlank(typeSystemDescPathsString)) {
     typeSystemDescPaths = StringUtils.split(typeSystemDescPathsString, ";,");
   }
   if (!isBlank(typeSystemDescNamesString)) {
     typeSystemDescNames = StringUtils.split(typeSystemDescNamesString, ";,");
   }
 }
Пример #6
0
  private void loadPreferences() {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

    // User Interface
    theme = readThemeValue(sp.getString(PREF_THEME, "0"));
    if (sp.getBoolean(PREF_EXPANDED_NOTIFICATION, false)) {
      notifyPriority = NotificationCompat.PRIORITY_MAX;
    } else {
      notifyPriority = NotificationCompat.PRIORITY_DEFAULT;
    }
    hiddenDrawerItems =
        Arrays.asList(StringUtils.split(sp.getString(PREF_HIDDEN_DRAWER_ITEMS, ""), ','));
    persistNotify = sp.getBoolean(PREF_PERSISTENT_NOTIFICATION, false);

    // Queue
    enqueueAtFront = sp.getBoolean(PREF_QUEUE_ADD_TO_FRONT, false);

    // Playback
    pauseOnHeadsetDisconnect = sp.getBoolean(PREF_PAUSE_ON_HEADSET_DISCONNECT, true);
    unpauseOnHeadsetReconnect = sp.getBoolean(PREF_UNPAUSE_ON_HEADSET_RECONNECT, true);
    followQueue = sp.getBoolean(PREF_FOLLOW_QUEUE, false);
    autoDelete = sp.getBoolean(PREF_AUTO_DELETE, false);
    smartMarkAsPlayedSecs = Integer.valueOf(sp.getString(PREF_SMART_MARK_AS_PLAYED_SECS, "30"));
    playbackSpeedArray = readPlaybackSpeedArray(sp.getString(PREF_PLAYBACK_SPEED_ARRAY, null));
    pauseForFocusLoss = sp.getBoolean(PREF_PAUSE_PLAYBACK_FOR_FOCUS_LOSS, false);

    // Network
    updateInterval = readUpdateInterval(sp.getString(PREF_UPDATE_INTERVAL, "0"));
    allowMobileUpdate = sp.getBoolean(PREF_MOBILE_UPDATE, false);
    parallelDownloads = Integer.valueOf(sp.getString(PREF_PARALLEL_DOWNLOADS, "6"));
    EPISODE_CACHE_SIZE_UNLIMITED =
        context.getResources().getInteger(R.integer.episode_cache_size_unlimited);
    episodeCacheSize = readEpisodeCacheSizeInternal(sp.getString(PREF_EPISODE_CACHE_SIZE, "20"));
    enableAutodownload = sp.getBoolean(PREF_ENABLE_AUTODL, false);
    enableAutodownloadOnBattery = sp.getBoolean(PREF_ENABLE_AUTODL_ON_BATTERY, true);
    enableAutodownloadWifiFilter = sp.getBoolean(PREF_ENABLE_AUTODL_WIFI_FILTER, false);
    autodownloadSelectedNetworks =
        StringUtils.split(sp.getString(PREF_AUTODL_SELECTED_NETWORKS, ""), ',');

    // Services
    autoFlattr = sp.getBoolean(PREF_AUTO_FLATTR, false);
    autoFlattrPlayedDurationThreshold =
        sp.getFloat(
            PREF_AUTO_FLATTR_PLAYED_DURATION_THRESHOLD,
            PREF_AUTO_FLATTR_PLAYED_DURATION_THRESHOLD_DEFAULT);

    // MediaPlayer
    playbackSpeed = sp.getString(PREF_PLAYBACK_SPEED, "1.0");
    fastForwardSecs = sp.getInt(PREF_FAST_FORWARD_SECS, 30);
    rewindSecs = sp.getInt(PREF_REWIND_SECS, 30);
    queueLocked = sp.getBoolean(PREF_QUEUE_LOCKED, false);
  }
Пример #7
0
 /** 保存角色的系统菜单信息 */
 @RequestMapping("/saverole")
 @ResponseBody
 public Object save(@RequestParam Long roleId, @RequestParam String moduleIds) {
   try {
     ArrayList<Long> modulesIdList = Lists.newArrayList();
     if (null == roleId) {
       return new ExtReturn(false, "角色不能为空!");
     }
     if (StringUtils.isBlank(moduleIds)) {
       return new ExtReturn(false, "选择的资源不能为空!");
     } else {
       String[] modules = StringUtils.split(moduleIds, ",");
       if (null == modules || modules.length == 0) {
         return new ExtReturn(false, "选择的资源不能为空!");
       }
       for (int i = 0; i < modules.length; i++) {
         modulesIdList.add(new Long(modules[i]));
       }
     }
     logger.debug("save() - String roleId={}", roleId);
     logger.debug("save() - String moduleIds={}", moduleIds);
     String result = this.baseModulesService.saveModule(roleId, modulesIdList);
     if ("01".equals(result)) {
       return new ExtReturn(true, "保存成功!");
     } else if ("00".equals(result)) {
       return new ExtReturn(false, "保存失败!");
     } else {
       return new ExtReturn(false, result);
     }
   } catch (Exception e) {
     logger.error(WebConstants.EXCEPTION, e);
     return new ExceptionReturn(e);
   }
 }
Пример #8
0
  public Object getReferencedProperty(
      final GraphObject entity, final String refKey, final Object initialData, final int depth)
      throws FrameworkException {

    final String DEFAULT_VALUE_SEP = "!";
    final String[] parts = refKey.split("[\\.]+");
    Object _data = initialData;

    // walk through template parts
    for (int i = 0; i < parts.length; i++) {

      String key = parts[i];
      String defaultValue = null;

      if (StringUtils.contains(key, DEFAULT_VALUE_SEP)) {

        String[] ref = StringUtils.split(key, DEFAULT_VALUE_SEP);
        key = ref[0];

        if (ref.length > 1) {
          defaultValue = ref[1];
        }
      }

      _data = evaluate(entity, key, _data, defaultValue, i + depth);
    }

    return _data;
  }
Пример #9
0
  public void addItemToCart(Long itemId) {

    // 判断该商品是否存在购物车中
    // 如果存在,数量相加
    // 如果不存在,直接保存到数据库
    Cart record = new Cart();
    record.setItemId(itemId);
    record.setUserId(UserThreadLocal.get().getId());
    Cart cart = this.cartDao.selectOne(record);
    if (null == cart) {
      Item item = this.itemService.queryItemById(itemId);
      cart = new Cart();
      cart.setId(null);
      cart.setItemId(itemId);
      cart.setNum(1); // TODO 默认为1
      cart.setCreated(new Date());
      cart.setUpdated(cart.getCreated());
      cart.setUserId(record.getUserId());

      // 设置商品的基本数据
      cart.setItemTitle(item.getTitle());
      cart.setItemPrice(item.getPrice());
      String itemImage = item.getImage();
      if (StringUtils.isNotEmpty(itemImage)) {
        cart.setItemImage(StringUtils.split(itemImage, ",")[0]);
      }
      this.cartDao.insert(cart);
    } else {
      cart.setNum(cart.getNum() + 1); // TODO 先默认为1,项目实战中实现指定的购买数量
      cart.setUpdated(new Date());
      this.cartDao.updateByPrimaryKey(cart);
    }
  }
Пример #10
0
  /**
   * テキストでフィルタ
   *
   * @param ship
   * @param filter
   */
  private static boolean textFilter(ShipDto ship, ShipFilterDto filter) {
    // 検索ワード
    String[] words = StringUtils.split(filter.nametext, " ");
    // 検索対象
    // 名前
    String name = ship.getName();
    // 艦種
    String type = ship.getType();
    // 装備
    List<String> items = ship.getSlot();

    // テキストが入力されている場合処理する
    if (filter.regexp) {
      // 正規表現で検索
      for (int i = 0; i < words.length; i++) {
        Pattern pattern;
        try {
          pattern = Pattern.compile(words[i]);
        } catch (PatternSyntaxException e) {
          // 無効な正規表現はfalseを返す
          return false;
        }
        boolean find = false;

        // 名前で検索
        find = find ? find : pattern.matcher(name).find();
        // 艦種で検索
        find = find ? find : pattern.matcher(type).find();
        // 装備で検索
        for (String item : items) {
          find = find ? find : pattern.matcher(item).find();
        }

        if (!find) {
          // どれにもマッチしない場合
          return false;
        }
      }
    } else {
      // 部分一致で検索する
      for (int i = 0; i < words.length; i++) {
        boolean find = false;

        // 名前で検索
        find = find ? find : name.indexOf(words[i]) != -1;
        // 艦種で検索
        find = find ? find : type.indexOf(words[i]) != -1;
        // 装備で検索
        for (String item : items) {
          find = find ? find : item.indexOf(words[i]) != -1;
        }

        if (!find) {
          // どれにもマッチしない場合
          return false;
        }
      }
    }
    return true;
  }
 @Transactional
 public AccessKey updateAccessKeyFromOAuthGrant(OAuthGrant grant, User user, Date now) {
   AccessKey existing = find(grant.getAccessKey().getId(), user.getId());
   deleteAccessKeyPermissions(existing);
   if (grant.getAccessType().equals(AccessType.ONLINE)) {
     Date expirationDate = new Date(now.getTime() + 600000); // the key is valid for 10 minutes
     existing.setExpirationDate(expirationDate);
   } else {
     existing.setExpirationDate(null);
   }
   existing.setLabel(
       String.format(
           Messages.OAUTH_GRANT_TOKEN_LABEL,
           grant.getClient().getName(),
           System.currentTimeMillis()));
   Set<AccessKeyPermission> permissions = new HashSet<>();
   AccessKeyPermission permission = new AccessKeyPermission();
   permission.setDomainArray(grant.getClient().getDomain());
   permission.setActionsArray(StringUtils.split(grant.getScope(), ' '));
   permission.setSubnetsArray(grant.getClient().getSubnet());
   permission.setNetworkIds(grant.getNetworkIds());
   permissions.add(permission);
   existing.setPermissions(permissions);
   AccessKeyProcessor keyProcessor = new AccessKeyProcessor();
   String key = keyProcessor.generateKey();
   existing.setKey(key);
   for (AccessKeyPermission current : permissions) {
     current.setAccessKey(existing);
     genericDAO.persist(current);
   }
   return existing;
 }
 @Transactional
 public AccessKey createAccessKeyFromOAuthGrant(OAuthGrant grant, User user, Date now) {
   AccessKey newKey = new AccessKey();
   newKey.setType(AccessKeyType.OAUTH);
   if (grant.getAccessType().equals(AccessType.ONLINE)) {
     Date expirationDate = new Date(now.getTime() + 600000); // the key is valid for 10 minutes
     newKey.setExpirationDate(expirationDate);
   }
   newKey.setUser(user);
   newKey.setLabel(
       String.format(
           Messages.OAUTH_GRANT_TOKEN_LABEL,
           grant.getClient().getName(),
           System.currentTimeMillis()));
   Set<AccessKeyPermission> permissions = new HashSet<>();
   AccessKeyPermission permission = new AccessKeyPermission();
   permission.setDomainArray(grant.getClient().getDomain());
   permission.setActionsArray(StringUtils.split(grant.getScope(), ' '));
   permission.setSubnetsArray(grant.getClient().getSubnet());
   permission.setNetworkIds(grant.getNetworkIds());
   permissions.add(permission);
   newKey.setPermissions(permissions);
   create(user, newKey);
   return newKey;
 }
Пример #13
0
  @Override
  public String importQuestionnareOds(String filename, String questionnaireName) throws Exception {
    SpreadsheetDocument document = SpreadsheetDocument.loadDocument(new File(filename));
    Table sheet = document.getSheetByIndex(0);

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

    for (int i = 1; i < sheet.getRowList().size(); i++) {
      Row row = sheet.getRowList().get(i);

      String question = getCellStringValue(row, 0);

      if (StringUtils.isBlank(question)) {
        break;
      }

      String levelString = getCellStringValue(row, 1);
      long level = Long.valueOf(StringUtils.replace(levelString, "D", ""));
      String tagsString = getCellStringValue(row, 2);
      List<String> tags = Collections.emptyList();
      if (StringUtils.isNotBlank(tagsString)) {
        tags = Lists.newArrayList(StringUtils.split(tagsString, ", "));
      }
      String tip = StringUtils.defaultIfBlank(getCellStringValue(row, 3), null);

      XContentBuilder builder =
          jsonBuilder()
              .startObject()
              .field("title", question)
              .field("level", level)
              .field("tags", tags)
              .field("tip", tip)
              .endObject();

      IndexResponse indexResponse =
          client
              .prepareIndex(domainResolver.resolveQuestionIndex(), Types.question)
              .setSource(builder)
              .execute()
              .actionGet();

      questions.add(indexResponse.getId());
    }

    XContentBuilder questionnaireBuilder =
        jsonBuilder()
            .startObject()
            .field("name", questionnaireName)
            .field("questions", questions)
            .endObject();

    IndexResponse indexResponse =
        client
            .prepareIndex(domainResolver.resolveQuestionIndex(), Types.questionnaire)
            .setSource(questionnaireBuilder)
            .execute()
            .actionGet();

    return indexResponse.getId();
  }
  @RequestMapping("/ls")
  public String ls(HttpServletRequest request, Model model, String path) {
    String zkServer = (String) request.getSession().getAttribute(Keys.KEY_ZKSERVER);
    if (StringUtils.isBlank(zkServer)) {
      return "redirect:/";
    }

    // 处理zkPath
    path = this.processZkPath(path);
    model.addAttribute("paths", Arrays.asList(StringUtils.split(path, "/")));

    // zk数据读取
    ZkData zkData = this.readZkData(zkServer, path);
    if (null != zkData) {
      model.addAttribute("children", zkData.getChildren());
      model.addAttribute("data", zkData.getDataString());
      model.addAttribute("dataSize", zkData.getData().length);
      try {
        Map<String, Object> statMap = PropertyUtils.describe(zkData.getStat());
        statMap.remove("class");
        model.addAttribute("stat", statMap);
      } catch (Exception e) {
        LOGGER.error("", e);
      }
    }

    return "ls";
  }
  /**
   * Get a fastTrack token
   *
   * @param packageId The id of the package in which to get the FastTrack Token
   * @param signing whether signing or not
   * @return The fastTrack token
   */
  private String getFastTrackToken(PackageId packageId, Boolean signing) {
    String fastTrackUrl = getFastTrackUrl(packageId, signing);
    String finalUrl = RedirectResolver.resolveUrlAfterRedirect(fastTrackUrl);

    String[] split = StringUtils.split(finalUrl, '=');
    return split[split.length - 1];
  }
Пример #16
0
  private Card loadCardFromPSVLine(final String line) {
    final String[] lineValues = StringUtils.split(line, this.delimiter);
    int x = 0;

    // Name|Expansion|Action|Attack|Curse|Duration|Reaction|Treasure|Victory|Cost|Pot|Action|Buy|Card|Coin|VP|Text
    return new CardBuilder()
        .setName(lineValues[x++])
        .setIteration(lineValues[x++])
        .setAction(this.convertInputToBoolean(lineValues[x++]))
        .setAttack(this.convertInputToBoolean(lineValues[x++]))
        .setCurse(this.convertInputToBoolean(lineValues[x++]))
        .setDuration(this.convertInputToBoolean(lineValues[x++]))
        .setReaction(this.convertInputToBoolean(lineValues[x++]))
        .setTreasure(this.convertInputToBoolean(lineValues[x++]))
        .setVictory(this.convertInputToBoolean(lineValues[x++]))
        .setCost(NumberUtils.toInt(lineValues[x++]))
        .setPotionCost(NumberUtils.toInt(lineValues[x++]))
        .setPlusAction(NumberUtils.toInt(lineValues[x++]))
        .setPlusBuy(NumberUtils.toInt(lineValues[x++]))
        .setPlusCard(NumberUtils.toInt(lineValues[x++]))
        .setPlusCoin(NumberUtils.toInt(lineValues[x++]))
        .setVictoryPoints(NumberUtils.toInt(lineValues[x++]))
        .setCardText(lineValues[x])
        .build();
  }
  public static String normalize(String path) throws IllegalArgumentException {
    if (path == null) {
      return null;
    }

    String[] segs = StringUtils.split(path, SEPARATORS);
    List<String> names = new ArrayList<String>(segs.length < 32 ? segs.length : 32);
    for (String seg : segs) {
      if (seg.equals("")) {
        continue;
      }
      if (seg.equals(".")) {
        continue;
      }
      if (seg.equals("..")) {
        if (names.size() == 0) {
          continue;
        }
        names.remove(names.size() - 1);
        continue;
      }

      names.add(validateName(seg));
    }

    StringBuilder sb = new StringBuilder();
    for (String name : names) {
      sb.append(SEPARATOR);
      sb.append(name);
    }
    return sb.toString();
  }
  @Override
  public String locate(final String statementName, final StatementContext context)
      throws Exception {
    if (StringUtils.isEmpty(statementName)) {
      throw new IllegalStateException("Statement Name can not be empty/null!");
    }

    if (statementName.startsWith(markerString)) {
      return defaultSqlLocator.getTemplate(statementName.substring(markerString.length()), context);
    }

    final String[] fieldElements = StringUtils.split(statementName, ':');
    if (fieldElements.length != 2 || !fieldElements[1].startsWith(markerString)) {
      return defaultLocate(statementName, context);
    }

    // If the class in the tuple is actually the class for which this locator is intended, don't
    // load
    // everything again, just reuse the existing sqllocator.
    if (defaultClassName.equals(fieldElements[0])) {
      return defaultSqlLocator.getTemplate(
          fieldElements[1].substring(markerString.length()), context);
    }

    try {
      final SqlLocator sqlLocator = new SqlLocator(Class.forName(fieldElements[0]));
      return sqlLocator.getTemplate(fieldElements[1].substring(markerString.length()), context);
    } catch (ClassNotFoundException cnfe) {
      LOG.trace(cnfe, "Ignoring, falling back to default locator");
    } catch (IllegalArgumentException ex) {
      LOG.trace(ex, "Ignoring, falling back to default locator");
    }

    return defaultLocate(statementName, context);
  }
Пример #19
0
  /** searchParams中key的格式为OPERATOR_FIELDNAME */
  public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
    Map<String, SearchFilter> filters = Maps.newHashMap();

    for (Entry<String, Object> entry : searchParams.entrySet()) {
      // 过滤掉空值
      String key = entry.getKey();
      Object value = entry.getValue();
      if (StringUtils.isBlank((String) value)) {
        continue;
      }

      // 拆分operator与filedAttribute
      String[] names = StringUtils.split(key, "_");
      if (names.length != 2) {
        throw new IllegalArgumentException(key + " is not a valid search filter name");
      }
      String filedName = names[1];
      Operator operator = Operator.valueOf(names[0]);

      // 创建searchFilter
      SearchFilter filter = new SearchFilter(filedName, operator, value);
      filters.put(key, filter);
    }

    return filters;
  }
  public Collection<JSONObject> asJson() {
    Map<String, JSONObject> res = new HashMap<>();

    for (Entry<String, AtomicInteger> entry : stat.entrySet()) {
      String[] split = StringUtils.split(entry.getKey(), PATH_SEPARATOR);
      if (!res.containsKey(split[0])) {

        JSONObject obj = new JSONObject();

        obj.put("name", split[0]);
        obj.put("tags_info", new JSONObject());

        res.put(split[0], obj);
      }

      JSONObject tagInfo = res.get(split[0]).getJSONObject("tags_info").optJSONObject(split[1]);
      if (tagInfo == null) {
        tagInfo = new JSONObject();
        res.get(split[0]).getJSONObject("tags_info").put(split[1], tagInfo);
      }

      if (split.length > 2) {
        tagInfo.put(split[2], entry.getValue().get());
        if (!"_error".equals(split[2])) {
          tagInfo.put("_total", tagInfo.optInt("_total") + entry.getValue().get());
        }
      }
    }

    return res.values();
  }
Пример #21
0
  private boolean basicAuth(HttpServerRequest request, String encodedAuth) {
    byte[] authBytes = Base64.decodeBase64(encodedAuth);
    String decodedString = new String(authBytes);
    String[] splitAuth = StringUtils.split(StringUtils.trim(decodedString), ":"); // $NON-NLS-1$

    if (splitAuth.length != 2) return false;

    if (fileBasicAuthData.containsKey(splitAuth[0])) {
      String storedHash = new String(Base64.decodeBase64(fileBasicAuthData.get(splitAuth[0])));

      MessageDigest digest;
      try {
        digest = MessageDigest.getInstance("SHA-256"); // $NON-NLS-1$
        digest.update(splitAuth[1].getBytes());

        String receivedHash = new String(digest.digest());

        if (storedHash.equals(receivedHash)) {
          return true;
        }
      } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e.getCause());
      }
    }

    request
        .response()
        .headers()
        .add(
            "WWW-Authenticate",
            "Basic realm=\"" + config.getRealm() + "\""); // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$

    return false;
  }
Пример #22
0
 /**
  * Creating a map which its key is a gene name and its value is the mappability. It also
  * calculates the number of tiles which are within the gene.
  *
  * @param btOutputFileLines BowTie output file name
  * @param readFileLines Reads file content in a list
  * @param chr1FileLines chromosome file name in a list
  * @return
  * @throws IOException
  */
 private Map<String, Mappability> createMappability(
     List<String> btOutputFileLines, List<String> readFileLines, List<String> chr1FileLines)
     throws IOException {
   Map<String, Mappability> result = new HashMap<>();
   for (String btOutputLine : btOutputFileLines) {
     String[] splittedLine = StringUtils.split(btOutputLine, FileUtils.SEPARATOR_TAB);
     Integer tileStart = getTileStartIndex(splittedLine);
     Integer tileEnd = getTileEndIndex(splittedLine);
     Gene gene = getGeneId(splittedLine);
     String geneName = gene.getName();
     if (!result.containsKey(geneName)) {
       result.put(geneName, new Mappability(0, getTotalNumberOfTiles(geneName, readFileLines)));
     }
     Mappability output = result.get(geneName);
     if (isTileWithinGene(tileStart, tileEnd, gene)) {
       output.addNumberOfMatches();
     }
     result.put(geneName, output);
   }
   // Add the missing tiles from output
   for (int lineIndex = 0; lineIndex < chr1FileLines.size(); lineIndex++) {
     if (lineIndex % 2 == 0) {
       // Reading the first line
       String geneName =
           StringUtils.substringAfter(chr1FileLines.get(lineIndex), FileUtils.CHR_INDICATOR);
       if (!result.containsKey(geneName)) {
         result.put(geneName, null);
       }
     }
     chr1FileLines.get(lineIndex);
   }
   return result;
 }
Пример #23
0
  @Override
  public LongRange[] parsePatternData(String data) {
    if (data == null) {
      return null;
    }

    if (data.length() < 3) // smallest range is 3 chars, "1-2"
    {
      return null;
    }
    if ((data.charAt(0) == '[') && (data.charAt(data.length() - 1) == ']')) {
      if (data.length() < 5) // smallest multi-range is 5 chars, "[1-2]"
      {
        return null;
      }
      data = data.substring(1, data.length() - 1);
      final String[] ranges = StringUtils.split(data, ',');
      final LongRange[] result = new LongRange[ranges.length];
      for (int i = 0, rangesLength = ranges.length; i < rangesLength; i++) {
        final String str = ranges[i];
        final LongRange range = parseSingleRange(str);
        if (range == null) {
          return null;
        }
        result[i] = range;
      }
      return result;
    }
    final LongRange range = parseSingleRange(data);
    if (range == null) {
      return null;
    }
    return new LongRange[] {range};
  }
Пример #24
0
  @Override
  public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
    if (AppConfig.DEBUG) Log.d(TAG, "Registered change of user preferences. Key: " + key);

    if (key.equals(PREF_DOWNLOAD_MEDIA_ON_WIFI_ONLY)) {
      downloadMediaOnWifiOnly = sp.getBoolean(PREF_DOWNLOAD_MEDIA_ON_WIFI_ONLY, true);

    } else if (key.equals(PREF_MOBILE_UPDATE)) {
      allowMobileUpdate = sp.getBoolean(PREF_MOBILE_UPDATE, false);

    } else if (key.equals(PREF_FOLLOW_QUEUE)) {
      followQueue = sp.getBoolean(PREF_FOLLOW_QUEUE, false);

    } else if (key.equals(PREF_UPDATE_INTERVAL)) {
      updateInterval = readUpdateInterval(sp.getString(PREF_UPDATE_INTERVAL, "0"));
      restartUpdateAlarm(updateInterval);

    } else if (key.equals(PREF_AUTO_DELETE)) {
      autoDelete = sp.getBoolean(PREF_AUTO_DELETE, false);

    } else if (key.equals(PREF_DISPLAY_ONLY_EPISODES)) {
      displayOnlyEpisodes = sp.getBoolean(PREF_DISPLAY_ONLY_EPISODES, false);
    } else if (key.equals(PREF_THEME)) {
      theme = readThemeValue(sp.getString(PREF_THEME, ""));
    } else if (key.equals(PREF_ENABLE_AUTODL_WIFI_FILTER)) {
      enableAutodownloadWifiFilter = sp.getBoolean(PREF_ENABLE_AUTODL_WIFI_FILTER, false);
    } else if (key.equals(PREF_AUTODL_SELECTED_NETWORKS)) {
      autodownloadSelectedNetworks =
          StringUtils.split(sp.getString(PREF_AUTODL_SELECTED_NETWORKS, ""), ',');
    } else if (key.equals(PREF_EPISODE_CACHE_SIZE)) {
      episodeCacheSize = Integer.valueOf(sp.getString(PREF_EPISODE_CACHE_SIZE, "20"));
    }
  }
Пример #25
0
 /**
  * Extracts the geneID out of the splitted file line.
  *
  * @param splittedLine
  * @return
  */
 private Gene getGeneId(String[] splittedLine) {
   String[] geneSplittedStr = StringUtils.split(splittedLine[3], FileUtils.SEPARATOR_DOT);
   return new Gene(
       Integer.valueOf(geneSplittedStr[1]),
       Integer.valueOf(geneSplittedStr[2]),
       StringUtils.substringBeforeLast(splittedLine[3], FileUtils.SEPARATOR_DOT));
 }
 private LocalTime getLocalTime(String str) {
   if (str.contains(":")) {
     String[] parts = StringUtils.split(str, ':');
     return new LocalTime(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
   }
   return new LocalTime(Integer.parseInt(str), 0);
 }
Пример #27
0
  @Override
  public synchronized void init(XWikiContext context) {
    LOGGER.debug("Lucene plugin: in init");

    this.indexDirs = context.getWiki().Param(PROP_INDEX_DIR);
    if (StringUtils.isEmpty(this.indexDirs)) {
      File workDir = getLuceneWorkDirectory();
      this.indexDirs = workDir.getAbsolutePath();
    }
    String indexDir = StringUtils.split(this.indexDirs, ",")[0];

    File f = new File(indexDir);
    Directory directory;
    try {
      if (!f.exists()) {
        f.mkdirs();
      }
      directory = FSDirectory.open(f);
    } catch (IOException e) {
      LOGGER.error("Failed to open the index directory: ", e);
      throw new RuntimeException(e);
    }

    init(directory, context);
  }
 private Range<Integer> parseDayOfMonthRange(String dayOfMonth) {
   if (StringUtils.isBlank(dayOfMonth)) {
     return null;
   }
   String dom = normalize(dayOfMonth);
   String[] parts = StringUtils.split(dom, '-');
   return Range.between(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
 }
 private Range<Integer> parseDayOfWeekRange(String dayOfWeek) {
   if (StringUtils.isBlank(dayOfWeek)) {
     return null;
   }
   String dow = normalize(dayOfWeek);
   String[] parts = StringUtils.split(dow, '-');
   return Range.between(getDOW(parts[0]), getDOW(parts[1]));
 }
 public static String getTopLevelPath(String path) {
   String segs[] = StringUtils.split(normalize(path), SEPARATOR_CHAR);
   if (segs.length < 1) {
     return ROOT_PATH;
   } else {
     return SEPARATOR + segs[0];
   }
 }