示例#1
0
 /**
  * 添加一个定时任务
  *
  * @param jobName 任务名
  * @param jobGroupName 任务组名
  * @param triggerName 触发器名
  * @param triggerGroupName 触发器组名
  * @param job 任务
  * @param cronExpression 时间设置,参考quartz说明文档
  */
 public static void addJob(
     String jobName,
     String jobGroupName,
     String triggerName,
     String triggerGroupName,
     Job job,
     String cronExpression)
     throws SchedulerException, ParseException {
   if (StringUtils.isBlank(jobGroupName)) {
     jobGroupName = JOB_GROUP_NAME;
   }
   if (StringUtils.isBlank(triggerGroupName)) {
     triggerGroupName = TRIGGER_GROUP_NAME;
   }
   Scheduler sched = sf.getScheduler();
   //	       JobDetail jobDetail = new JobDetail(jobName, jobGroupName,
   // job.getClass());//任务名,任务组,任务执行类
   //	       CronTrigger  trigger = new
   // CronTrigger(jobName,triggerGroupName,cronExpression);//触发器名,触发器组,cron表达式
   //	       sched.scheduleJob(jobDetail,trigger);
   // 启动
   if (!sched.isShutdown()) {
     sched.start();
   }
 }
示例#2
0
 public void putInPioche(DragDropEvent ddEvent) {
   Map<String, String> params =
       FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
   String left = params.get("class");
   String[] sClass = left.split(" ");
   String idTmp = "";
   int colTmp = -1;
   int ligneTmp = 0;
   for (String s : sClass) {
     if (StringUtils.startsWith(s, "colonne_")) {
       String c = s.replace("colonne_", "");
       colTmp = Integer.valueOf(c);
     }
     if (StringUtils.startsWith(s, "ligne_")) {
       String c = s.replace("ligne_", "");
       ligneTmp = Integer.valueOf(c);
     }
     if (StringUtils.startsWith(s, "id_")) {
       idTmp = s.replace("id_", "");
     }
   }
   if (colTmp != -1) {
     Cell c = list.get(ligneTmp).get(colTmp);
     c.setType(Cell.CELL_EMPTY);
     c.setAngle(-1);
   }
   if (idTmp.equals(Cell.CELL_MIRROR) || idTmp.equals(Cell.CELL_SPLIT)) {
     Cell c = new Cell(idTmp);
     c.setAngle(0);
     pioche.add(c);
   }
 }
  protected List<OrderByClause> getOrderByClauses(final String orderBy) {
    if (StringUtils.isBlank(orderBy)) {
      return Collections.<OrderByClause>emptyList();
    }

    List<OrderByClause> result = new ArrayList<>();

    for (String clause : orderBy.split(",")) {
      String[] elems = clause.split(" ");

      if (elems.length > 0 && StringUtils.isNotBlank(elems[0])) {
        OrderByClause obc = new OrderByClause();
        obc.setField(elems[0].trim());
        if (elems.length > 1 && StringUtils.isNotBlank(elems[1])) {
          obc.setDirection(
              elems[1].trim().equalsIgnoreCase(OrderByClause.Direction.ASC.name())
                  ? OrderByClause.Direction.ASC
                  : OrderByClause.Direction.DESC);
        }
        result.add(obc);
      }
    }

    return result;
  }
示例#4
0
 public static boolean writeString2File(String content, String path) throws Exception {
   if (StringUtils.isBlank(content)) {
     return false;
   }
   if (StringUtils.isBlank(path)) {
     return false;
   }
   File file = new File(path);
   FileWriter fileWriter = null;
   try {
     fileWriter = new FileWriter(file);
     fileWriter.write(content);
     return true;
   } catch (IOException e) {
     e.printStackTrace();
   } finally {
     if (fileWriter != null) {
       try {
         fileWriter.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
       fileWriter = null;
     }
     if (file != null) {
       file = null;
     }
   }
   return false;
 }
 private void setJsonTree(List<String> path, JSONArray parent, GadgetSpec gadgetSpec)
     throws JSONException {
   String tempId = "root"; // Temp variable to keep track of parent ID.
   for (int i = 0; i < path.size(); i++) {
     JSONObject newNode = new JSONObject();
     if (!this.isNodeExisting(path.get(i), parent)) {
       // If node is a GadgetSpec (last in path)
       if (i == path.size() - 1) {
         newNode.put("name", StringUtils.capitalize(gadgetSpec.getTitle()));
         newNode.put("hasChildren", false);
         newNode.put("isDefault", gadgetSpec.isDefault());
         newNode.put("id", gadgetSpec.getId());
       }
       // Id node is a unique folder
       else {
         newNode.put("name", StringUtils.capitalize(path.get(i)));
         newNode.put("hasChildren", true);
         newNode.put("isDefault", false);
         newNode.put("id", getFolderId(path.get(i)));
       }
       newNode.put("parent", tempId);
       parent.put(newNode);
     }
     tempId = getFolderId(path.get(i));
   }
 }
示例#6
0
  public static String signUp(
      String userName, String firstName, String lastName, String email, String password) {
    String message = "Sign up failed. Please try again.";
    if (StringUtils.isBlank(userName)) {
      return "User name is required.";
    }

    if (StringUtils.isBlank(firstName)) {
      return "First name is required.";
    }

    if (StringUtils.isBlank(lastName)) {
      return "Last name is required.";
    }

    if (StringUtils.isBlank(password)) {
      return "Password is required and must be at least 6 characters.";
    }

    if (userExist(userName)) {
      message = "The username you input has been used. Please choose another.";
    } else {
      int row =
          getJdbcTemplate()
              .update(CREATE_USER, firstName + " " + lastName, userName, password, email);
      if (row > 0) {
        message = "";
      }
    }
    return message;
  }
示例#7
0
  /**
   * 注册验证
   *
   * @return
   */
  public boolean registervalidation() {
    boolean register = false;
    this.setMsg("");
    if (StringUtils.isNotBlank(this.getLoginname())) {
      if (this.getLoginname().length() < 6) {
        this.setMsg("1");
        return register;
      } else if (this.getLoginname().length() > 20) {
        this.setMsg("1");
        return register;
      }
    } else {
      this.setMsg("1");
      return register;
    }
    if (StringUtils.isNotBlank(this.getLoginpwd())) {
      if (this.getLoginpwd().length() < 6) {
        this.setMsg("2");
        return register;
      } else if (this.getLoginpwd().length() > 20) {
        this.setMsg("2");
        return register;
      }
    } else {
      this.setMsg("2");
      return register;
    }

    if (!StringUtils.isNotBlank(this.getEmail())) {
      this.setMsg("3");
      return register;
    }
    register = true;
    return register;
  }
示例#8
0
  /** 分析并设置contentType与headers. */
  private static HttpServletResponse initResponseHeader(
      final String contentType, final String... headers) {
    // 分析headers参数
    String encoding = DEFAULT_ENCODING;
    boolean noCache = DEFAULT_NOCACHE;
    for (String header : headers) {
      String headerName = StringUtils.substringBefore(header, ":");
      String headerValue = StringUtils.substringAfter(header, ":");

      if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
        encoding = headerValue;
      } else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
        noCache = Boolean.parseBoolean(headerValue);
      } else {
        throw new IllegalArgumentException(headerName + "不是一个合法的header类型");
      }
    }

    HttpServletResponse response = ServletActionContext.getResponse();

    // 设置headers参数
    String fullContentType = contentType + ";charset=" + encoding;
    response.setContentType(fullContentType);
    if (noCache) {
      ServletUtils.setDisableCacheHeader(response);
    }

    return response;
  }
  /**
   * Create a target URL from given parameters, adding the template name.
   *
   * @param space space name to use, "Main" is used if null
   * @param page page name to use, "WebHome" is used if null
   * @param parameter parameter name to add, omitted if null or empty string
   * @param value parameter value, empty string is used if null
   * @return the resulting absolute URL
   * @see #createUrl(String, String, String, java.util.Map)
   */
  protected String createUrl(String space, String page, String parameter, String value) {
    String skin = "default";
    if (this.name.startsWith("skins")) {
      skin = this.name.replaceFirst("^\\w+/", "").replaceAll("/.+$", "");
    }

    final String TEMPLATES_DIR = "templates" + File.separator;
    final String SKINS_DIR = "skins" + File.separator;
    String template;
    if (this.name.startsWith(TEMPLATES_DIR)) {
      template = StringUtils.removeStart(this.name, TEMPLATES_DIR);
    } else if (this.name.startsWith(SKINS_DIR)) {
      template = StringUtils.removeStart(this.name, SKINS_DIR + skin + File.separator);
    } else {
      template = this.name.replaceAll("^(.+)/", "");
    }

    HashMap<String, String> parameters = new HashMap<String, String>();
    parameters.put("skin", skin);
    if ("xpart".equals(parameter)) {
      // xpart=something must be tested differently
      parameters.put("xpage", template).replaceAll("\\.\\w+$", "");
    } else {
      // this variant initializes some commonly used variables
      parameters.put("xpage", "xpart");
      parameters.put("vm", template);
    }
    if (parameter != null) {
      parameters.put(parameter, value);
    }
    return createUrl(null, space, page, parameters);
  }
  private boolean validateReplaceeReplacer(PersonMassChange personMassChange) {
    boolean isValid = true;

    if (personMassChange.getReplaceePersonId() == null
        && personMassChange.getReplaceeRolodexId() == null) {
      isValid = false;
      reportError(REPLACEE_FULL_NAME_FIELD, KeyConstants.ERROR_PERSON_MASS_CHANGE_REPLACEE_EMPTY);
      return isValid;
    }

    if (personMassChange.getReplacerPersonId() == null
        && personMassChange.getReplacerRolodexId() == null) {
      isValid = false;
      reportError(REPLACER_FULL_NAME_FIELD, KeyConstants.ERROR_PERSON_MASS_CHANGE_REPLACER_EMPTY);
      return isValid;
    }

    if ((personMassChange.getReplacerPersonId() != null
            && StringUtils.equalsIgnoreCase(
                personMassChange.getReplacerPersonId(), personMassChange.getReplaceePersonId()))
        || (personMassChange.getReplacerRolodexId() != null
            && StringUtils.equalsIgnoreCase(
                String.valueOf(personMassChange.getReplacerRolodexId()),
                String.valueOf(personMassChange.getReplaceeRolodexId())))) {
      isValid = false;
      reportError(REPLACER_FULL_NAME_FIELD, KeyConstants.ERROR_PERSON_MASS_CHANGE_SAME_PERSONS);
    }

    return isValid;
  }
 @Override
 public DashboardSectionDecoration getDecoration(Entity entity, int stampId) {
   if (!extensionManager.isExtensionEnabled(JenkinsExtension.EXTENSION)) {
     return null;
   } else if (entity == Entity.VALIDATION_STAMP) {
     // Gets the Jenkins URL for this validation stamp
     String jobUrl =
         propertiesService.getPropertyValue(
             Entity.VALIDATION_STAMP,
             stampId,
             JenkinsExtension.EXTENSION,
             JenkinsUrlPropertyDescriptor.NAME);
     if (StringUtils.isNotBlank(jobUrl)) {
       // Gets the corresponding job
       JenkinsJob job = jenkinsClient.getJob(jobUrl, false);
       // State
       return new DashboardSectionDecoration(
           Collections.singleton("jenkins-job-" + StringUtils.lowerCase(job.getState().name())),
           jobUrl);
     } else {
       return null;
     }
   } else {
     return null;
   }
 }
示例#12
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;
 }
示例#13
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));
 }
示例#14
0
 protected static String getFinalTarget(ResourceHandle resource, List<String> trace)
     throws RedirectLoopException {
   String finalTarget = null;
   if (resource.isValid()) {
     String path = resource.getPath();
     if (trace.contains(path)) {
       throw new RedirectLoopException(trace, path);
     }
     String redirect = resource.getProperty(PROP_TARGET);
     if (StringUtils.isBlank(redirect)) {
       redirect = resource.getProperty(PROP_REDIRECT);
     }
     if (StringUtils.isNotBlank(redirect)) {
       trace.add(path);
       finalTarget = redirect;
       if (!URL_PATTERN.matcher(finalTarget).matches()) {
         ResourceResolver resolver = resource.getResourceResolver();
         Resource targetResource = resolver.getResource(finalTarget);
         if (targetResource != null) {
           String target = getFinalTarget(ResourceHandle.use(targetResource), trace);
           if (StringUtils.isNotBlank(target)) {
             finalTarget = target;
           }
         }
       }
     }
   }
   return finalTarget;
 }
示例#15
0
 public void send(String message, String username)
     throws PushNotInitializedException, UserNotFoundException, SqlInjectionException,
         InvalidRequestException, IOException, UnknownHostException {
   if (Logger.isDebugEnabled())
     Logger.debug("Try to send a message (" + message + ") to " + username);
   UserDao udao = UserDao.getInstance();
   ODocument user = udao.getByUserName(username);
   if (user == null) {
     if (Logger.isDebugEnabled()) Logger.debug("User " + username + " does not exist");
     throw new UserNotFoundException("User " + username + " does not exist");
   }
   ODocument userSystemProperties = user.field(UserDao.ATTRIBUTES_SYSTEM);
   if (Logger.isDebugEnabled()) Logger.debug("userSystemProperties: " + userSystemProperties);
   List<ODocument> loginInfos = userSystemProperties.field(UserDao.USER_LOGIN_INFO);
   if (Logger.isDebugEnabled()) Logger.debug("Sending to " + loginInfos.size() + " devices");
   for (ODocument loginInfo : loginInfos) {
     String pushToken = loginInfo.field(UserDao.USER_PUSH_TOKEN);
     String vendor = loginInfo.field(UserDao.USER_DEVICE_OS);
     if (Logger.isDebugEnabled()) Logger.debug("push token: " + pushToken);
     if (Logger.isDebugEnabled()) Logger.debug("vendor: " + vendor);
     if (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(pushToken)) {
       VendorOS vos = VendorOS.getVendorOs(vendor);
       if (Logger.isDebugEnabled()) Logger.debug("vos: " + vos);
       if (vos != null) {
         IPushServer pushServer = Factory.getIstance(vos);
         pushServer.setConfiguration(getPushParameters());
         pushServer.send(message, pushToken);
       } // vos!=null
     } // (!StringUtils.isEmpty(vendor) && !StringUtils.isEmpty(deviceId)
   } // for (ODocument loginInfo : loginInfos)
 } // send
 @Override
 public void build(String input) {
   if (validate(input)) {
     if (input.length() < maxLength) {
       input = StringUtils.rightPad(input, maxLength, " ");
     }
     try {
       String values[] = MyStringUtil.splitByFixedLengths(input, new int[] {1, 400});
       this.resultado = values[0];
       if (this.resultado.equals("1")) {
         String empresaValues[] =
             StringUtils.splitPreserveAllTokens(values[1], Cuerpo.FIELD_SEPARATOR_CHAR);
         this.empresa = new Empresa();
         this.empresa.setRuc(empresaValues[0]);
         this.empresa.setNombre(empresaValues[1]);
         this.empresa.setTelefono(empresaValues[2]);
         this.empresa.setDireccion(empresaValues[3]);
         this.empresa.setUsuario(empresaValues[4]);
         this.empresa.setPassword(empresaValues[5]);
       }
     } catch (Exception ex) {
       Logger.getLogger(AutenticacionEmpresaRS.class.getName()).log(Level.SEVERE, null, ex);
     }
   }
 }
  private void authorizeSystem() {
    final NiFiUser user = NiFiUserUtils.getNiFiUser();

    final Map<String, String> userContext;
    if (!StringUtils.isBlank(user.getClientAddress())) {
      userContext = new HashMap<>();
      userContext.put(UserContextKeys.CLIENT_ADDRESS.name(), user.getClientAddress());
    } else {
      userContext = null;
    }

    final AuthorizationRequest request =
        new AuthorizationRequest.Builder()
            .resource(ResourceFactory.getSystemResource())
            .identity(user.getIdentity())
            .anonymous(user.isAnonymous())
            .accessAttempt(true)
            .action(RequestAction.READ)
            .userContext(userContext)
            .build();

    final AuthorizationResult result = authorizer.authorize(request);
    if (!Result.Approved.equals(result.getResult())) {
      final String message =
          StringUtils.isNotBlank(result.getExplanation())
              ? result.getExplanation()
              : "Access is denied";
      throw new AccessDeniedException(message);
    }
  }
示例#18
0
  /**
   * 创建权限类型实例<br>
   *
   * @param authType
   * @param name
   * @param description
   * @param isViewAble
   * @param isConfigAble
   * @return
   */
  public synchronized AuthTypeItem registeAuthTypeItem(
      String authType,
      String name,
      String description,
      boolean isViewAble,
      boolean isConfigAble,
      int orderIndex) {
    if (StringUtils.isEmpty(authType)) {
      throw new NullArgException("authType is empty");
    }

    AuthTypeItem res = null;
    if (authTypeItemMapping.containsKey(authType)) {
      res = authTypeItemMapping.get(authType);
      if (!StringUtils.isEmpty(name)) {
        res.setName(name);
      }
      if (!StringUtils.isEmpty(description)) {
        res.setDescription(description);
      }
      // 如果其中有一个与默认值不同,则认为不同的该值将生效
      // 如果其中有任意一个设置为不可见,则认为该类型可见
      if (!isViewAble) {
        res.setViewAble(isViewAble);
      }
      // 如果其中有任意一个设置为不可编辑,则认为不可编辑
      if (!isConfigAble) {
        res.setConfigAble(isConfigAble);
      }
    } else {
      res = new AuthTypeItem(authType, name, description, isViewAble, isConfigAble, orderIndex);
      authTypeItemMapping.put(authType, res);
    }
    return res;
  }
 @Override
 public boolean isValid(
     EntityWithClassLevelConstraint entity, ConstraintValidatorContext context) {
   return entity != null
       && StringUtils.isNotBlank(entity.firstname)
       && StringUtils.isNotBlank(entity.lastname);
 }
  /**
   * 保存指定状态的原始订单至数据库
   *
   * @param originalOrderList
   */
  public void saveOriginalOrders(List<OriginalOrder> originalOrderList) {

    if (CollectionUtils.isEmpty(originalOrderList)) {
      return;
    }

    for (OriginalOrder originalOrder : originalOrderList) {

      if (!(StringUtils.equalsIgnoreCase(
              originalOrder.getStatus(), OriginalOrderStatus.WAIT_SELLER_SEND_GOODS.toString())
          || StringUtils.equalsIgnoreCase(
              originalOrder.getStatus(), OriginalOrderStatus.WAIT_BUYER_CONFIRM_GOODS.toString())
          || StringUtils.equalsIgnoreCase(
              originalOrder.getStatus(), OriginalOrderStatus.TRADE_FINISHED.toString()))) {
        continue;
      }
      // 保存原始订单
      saveOriginalOrder(originalOrder);
      for (OriginalOrderItem originalOrderItem : originalOrder.getOriginalOrderItemList()) {
        // 保存原始订单项
        originalOrderItem.setOriginalOrderId(originalOrder.getId());
        saveOriginalOrderItem(originalOrderItem);
      }
      for (PromotionInfo promotionInfo : originalOrder.getPromotionInfoList()) {
        // 保存订单优惠记录
        promotionInfo.setOriginalOrderId(originalOrder.getId());
        savePromotionInfo(promotionInfo);
      }
    }
  }
示例#21
0
  /**
   * 查询区域树节点
   *
   * @param regionId 区域ID
   * @return
   */
  @RequestMapping(value = "/findRegionTreeNode")
  @ResponseBody
  public List<TRegion> findRegionTreeNode(String regionId, HttpSession session) {

    List<TRegion> data = new ArrayList<TRegion>();

    User user = (User) session.getAttribute(UserService.USER_CODE);
    if (user == null) {
      return data;
    }

    if (user.isSuperAdmin()) { // 超级管理员,可查看所有正常状态的区域信息
      if (StringUtils.isBlank(regionId)) { // 第一次加载
        data.addAll(regionService.findAllTopInNormal());
      } else {
        data.addAll(regionService.findChildrenByRegionIdInNormal(NumberUtils.toInt(regionId)));
      }
    } else {
      if (StringUtils.isBlank(regionId)) { // 第一次加载,获取当前登录用户归属公司的所在区域
        data.addAll(regionService.findByCompanyIdForTree(user.getCompanyId()));
      } else {
        data.addAll(regionService.findChildrenByRegionIdForTree(NumberUtils.toInt(regionId)));
      }
    }

    return data;
  }
示例#22
0
  public void load() throws IOException, SQLException {
    conn = Mysql.getConn("semsearch");
    List<String> lines = FileUtils.readLines(new File(this.filePath));
    AANPaper paper = new AANPaper();
    for (int i = 0; i < lines.size(); i++) {
      String line = lines.get(i).trim();
      if (line.equals("")) {
        process(paper);
      }
      if (line.startsWith("id")) {
        paper = new AANPaper();
        String temp = StringUtils.substringAfter(line, "{").trim();
        temp = StringUtils.substringBeforeLast(temp, "}");
        paper.setId(temp);
      } else if (line.startsWith("author")) {
        String temp = StringUtils.substringAfter(line, "{").trim();
        temp = StringUtils.substringBeforeLast(temp, "}");
        paper.setAuthor(temp);
      } else if (line.startsWith("title")) {
        String temp = StringUtils.substringAfter(line, "{").trim();
        temp = StringUtils.substringBeforeLast(temp, "}");
        paper.setTitle(temp);
      } else if (line.startsWith("venue")) {
        String temp = StringUtils.substringAfter(line, "{").trim();
        temp = StringUtils.substringBeforeLast(temp, "}");
        paper.setVenue(temp);
      } else if (line.startsWith("year")) {
        String temp = StringUtils.substringAfter(line, "{").trim();
        temp = StringUtils.substringBeforeLast(temp, "}");
        paper.setYear(temp);
      }

      System.out.println(line);
    }
  }
示例#23
0
 public static Map<String, String> readFile2Map(String path, String regular) throws IOException {
   if (StringUtils.isBlank(regular)) {
     return null;
   }
   if (StringUtils.isBlank(path)) {
     return null;
   }
   Map<String, String> map = new HashMap<String, String>();
   File file = new File(path);
   FileReader fReader = new FileReader(file);
   BufferedReader bReader = new BufferedReader(fReader);
   String temp = null;
   String[] tempArr = (String[]) null;
   while ((temp = bReader.readLine()) != null) {
     if (StringUtils.isNotBlank(temp)) {
       tempArr = temp.split(regular);
       if (tempArr.length > 1) {
         String username = tempArr[0];
         String password = tempArr[1];
         if ((StringUtils.isNotBlank(username)) && (StringUtils.isNotBlank(password))) {
           map.put(username.trim(), password.trim());
         }
       }
     }
     temp = null;
     tempArr = (String[]) null;
   }
   bReader.close();
   fReader.close();
   file = null;
   return map;
 }
示例#24
0
 private SearchRequestBuilder criteria2builder(ElasticSearchCriteria criteria) {
   String[] indices = criteria.getIndices();
   if (indices == null || indices.length == 0)
     indices = new String[] {indexManager.getIndexName()};
   SearchRequestBuilder srb = client.prepareSearch(indices);
   srb.setTimeout(new TimeValue(10, TimeUnit.SECONDS));
   String[] types = criteria.getTypes();
   if (types != null && types.length > 0) srb.setTypes(types);
   QueryBuilder qb = criteria.getQueryBuilder();
   String query = criteria.getQuery();
   if (qb == null && StringUtils.isBlank(query))
     throw new NullPointerException("queryBuilder is null and queryString is blank");
   if (qb == null && StringUtils.isNotBlank(query)) {
     if (wildcardQueryPattern.matcher(query).matches()) {
       String[] arr = query.split(":", 2);
       qb = QueryBuilders.wildcardQuery(arr[0], arr[1]);
     } else {
       QueryStringQueryBuilder qsqb = new QueryStringQueryBuilder(query);
       qsqb.defaultOperator(Operator.AND);
       qb = qsqb;
     }
   }
   srb.setQuery(qb);
   Map<String, Boolean> sorts = criteria.getSorts();
   for (Map.Entry<String, Boolean> entry : sorts.entrySet())
     srb.addSort(entry.getKey(), entry.getValue() ? SortOrder.DESC : SortOrder.ASC);
   return srb;
 }
  private boolean isValidPort(String text) {
    if (StringUtils.isBlank(text)) return false;
    String[] ports = text.trim().split(",");
    boolean ok = false;
    // linux (and OSX?)
    if (SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC_OSX) {
      // each will be /dev/tty* or /dev/cu*
      for (String port : ports) {
        if (StringUtils.isBlank(port)) continue;
        if (portNamesRegexLinux.matcher(port.trim()).matches()) {
          // must be at least one good
          ok = true;
        } else {
          // doesnt match, its bad so outa here.
          return false;
        }
      }
    }

    // windows
    if (SystemUtils.IS_OS_WINDOWS) {
      // each will be COM*
      for (String port : ports) {
        if (StringUtils.isBlank(port)) continue;
        if (portNamesRegexWindows.matcher(port.trim()).matches()) {
          // must be at least one good
          ok = true;
        } else {
          // doesnt match, its bad so outa here.
          return false;
        }
      }
    }
    return ok;
  }
  /**
   * Use resource key(Optional) and rest json entry as a template and fill in template using Avro as
   * a reference. e.g: Rest JSON entry HOCON template:
   * AccountId=${sf_account_id},Member_Id__c=${member_id} Avro:
   * {"sf_account_id":{"string":"0016000000UiCYHAA3"},"member_id":{"long":296458833}}
   *
   * <p>Converted Json: {"AccountId":"0016000000UiCYHAA3","Member_Id__c":296458833}
   *
   * <p>As it's template based approach, it can produce nested JSON structure even Avro is flat (or
   * vice versa).
   *
   * <p>e.g: Rest resource template: /sobject/account/memberId/${member_id} Avro:
   * {"sf_account_id":{"string":"0016000000UiCYHAA3"},"member_id":{"long":296458833}} Converted
   * resource: /sobject/account/memberId/296458833
   *
   * <p>Converted resource will be used to form end point.
   * http://www.server.com:9090/sobject/account/memberId/296458833
   *
   * <p>{@inheritDoc}
   *
   * @see gobblin.converter.Converter#convertRecord(java.lang.Object, java.lang.Object,
   *     gobblin.configuration.WorkUnitState)
   */
  @Override
  public Iterable<RestEntry<JsonObject>> convertRecord(
      Void outputSchema, GenericRecord inputRecord, WorkUnitState workUnit)
      throws DataConversionException {

    Config srcConfig =
        ConfigFactory.parseString(
            inputRecord.toString(), ConfigParseOptions.defaults().setSyntax(ConfigSyntax.JSON));

    String resourceKey = workUnit.getProp(CONVERTER_AVRO_REST_ENTRY_RESOURCE_KEY, "");
    if (!StringUtils.isEmpty(resourceKey)) {
      final String dummyKey = "DUMMY";
      Config tmpConfig =
          ConfigFactory.parseString(dummyKey + "=" + resourceKey).resolveWith(srcConfig);
      resourceKey = tmpConfig.getString(dummyKey);
    }

    String hoconInput = workUnit.getProp(CONVERTER_AVRO_REST_JSON_ENTRY_TEMPLATE);
    if (StringUtils.isEmpty(hoconInput)) {
      return new SingleRecordIterable<>(
          new RestEntry<>(resourceKey, parser.parse(inputRecord.toString()).getAsJsonObject()));
    }

    Config destConfig = ConfigFactory.parseString(hoconInput).resolveWith(srcConfig);
    JsonObject json =
        parser.parse(destConfig.root().render(ConfigRenderOptions.concise())).getAsJsonObject();
    return new SingleRecordIterable<>(new RestEntry<>(resourceKey, json));
  }
示例#27
0
  public void releaseObject(DragDropEvent ddEvent) {
    Map<String, String> params =
        FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
    String left = params.get("class");
    String[] sClass = left.split(" ");
    int col = 0;
    int ligne = 0;
    int item = 0;
    for (String s : sClass) {
      if (StringUtils.startsWith(s, "colonne_")) {
        String c = s.replace("colonne_", "");
        col = Integer.valueOf(c);
      }
      if (StringUtils.startsWith(s, "ligne_")) {
        String c = s.replace("ligne_", "");
        ligne = Integer.valueOf(c);
      }
      if (StringUtils.startsWith(s, "position_")) {
        String c = s.replace("position_", "");
        item = Integer.valueOf(c);
      }
    }
    if (col == 0 && ligne == 0) {
      pioche.remove(item);
    } else {
      Cell c = list.get(ligne).get(col);
      c.setType(Cell.CELL_EMPTY);
      c.setAngle(-1);
    }

    System.out.println("drop");
  }
 public DefaultUserNotification(final String title, final String content) {
   if (StringUtils.isNotBlank(title) && StringUtils.isNotBlank(content)) {
     notification = new NotificationMetaData(NotifMessageType.NORMAL.getId(), title, content);
   } else {
     notification = new NotificationMetaData();
   }
 }
 @Test
 public void lengthExceedLimit() {
   eventStore.onEvent(
       create(
           System.currentTimeMillis() - 30000,
           EventType.LOGIN,
           "realmId",
           StringUtils.repeat("clientId", 100),
           "userId",
           "127.0.0.1",
           "error"));
   eventStore.onEvent(
       create(
           System.currentTimeMillis() - 30000,
           EventType.LOGIN,
           StringUtils.repeat("realmId", 100),
           "clientId",
           "userId",
           "127.0.0.1",
           "error"));
   eventStore.onEvent(
       create(
           System.currentTimeMillis() - 30000,
           EventType.LOGIN,
           "realmId",
           "clientId",
           StringUtils.repeat("userId", 100),
           "127.0.0.1",
           "error"));
 }
示例#30
0
 /**
  * Checks if a subject is allowed to call method X on resource Y.
  *
  * @param subjectid subject id
  * @param resourceName resource name (type)
  * @param httpMethod HTTP method name
  * @return true if allowed
  */
 public boolean isAllowedTo(String subjectid, String resourceName, String httpMethod) {
   boolean allow = false;
   if (subjectid != null
       && !StringUtils.isBlank(resourceName)
       && !StringUtils.isBlank(httpMethod)) {
     if (getResourcePermissions().isEmpty()) {
       // Default policy is "deny all". Returning true here would make it "allow all".
       return false;
     }
     if (getResourcePermissions().containsKey(subjectid)
         && getResourcePermissions().get(subjectid).containsKey(resourceName)) {
       // subject-specific permissions have precedence over wildcard permissions
       // i.e. only the permissions for that subjectid are checked, other permissions are ignored
       allow = isAllowed(subjectid, resourceName, httpMethod);
     } else {
       allow =
           isAllowed(subjectid, resourceName, httpMethod)
               || isAllowed(subjectid, ALLOW_ALL, httpMethod)
               || isAllowed(ALLOW_ALL, resourceName, httpMethod)
               || isAllowed(ALLOW_ALL, ALLOW_ALL, httpMethod);
     }
   }
   boolean isRootApp = StringUtils.equals(App.id(Config.APP_NAME_NS), getId());
   boolean isRootAppAccessAllowed =
       Config.getConfigBoolean("clients_can_access_root_app", !Config.IN_PRODUCTION);
   return isRootApp ? (isRootAppAccessAllowed && allow) : allow;
 }