org.apache.commons.lang3.StringUtils Java Examples

The following examples show how to use org.apache.commons.lang3.StringUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SonosService.java    From airsonic-advanced with GNU General Public License v3.0 11 votes vote down vote up
protected SortedSet<Integer> parsePlaylistIndices(String indices) {
    // Comma-separated, may include ranges:  1,2,4-7
    SortedSet<Integer> result = new TreeSet<Integer>();

    for (String part : StringUtils.split(indices, ',')) {
        if (StringUtils.isNumeric(part)) {
            result.add(Integer.parseInt(part));
        } else {
            int dashIndex = part.indexOf('-');
            int from = Integer.parseInt(part.substring(0, dashIndex));
            int to = Integer.parseInt(part.substring(dashIndex + 1));
            for (int i = from; i <= to; i++) {
                result.add(i);
            }
        }
    }
    return result;
}
 
Example #2
Source File: TestFullRestore.java    From hbase with Apache License 2.0 8 votes vote down vote up
/**
 * Verify that multiple tables are restored to new tables.
 *
 * @throws Exception if doing the backup, restoring it or an operation on the tables fails
 */
@Test
public void testFullRestoreMultipleCommand() throws Exception {
  LOG.info("create full backup image on multiple tables: command-line");
  List<TableName> tables = Lists.newArrayList(table2, table3);
  String backupId = fullTableBackup(tables);
  assertTrue(checkSucceeded(backupId));

  TableName[] restore_tableset = new TableName[] { table2, table3 };
  TableName[] tablemap = new TableName[] { table2_restore, table3_restore };

  // restore <backup_root_path> <backup_id> <tables> [tableMapping]
  String[] args =
      new String[] { BACKUP_ROOT_DIR, backupId, "-t", StringUtils.join(restore_tableset, ","),
        "-m", StringUtils.join(tablemap, ",") };
  // Run backup
  int ret = ToolRunner.run(conf1, new RestoreDriver(), args);

  assertTrue(ret == 0);
  Admin hba = TEST_UTIL.getAdmin();
  assertTrue(hba.tableExists(table2_restore));
  assertTrue(hba.tableExists(table3_restore));
  TEST_UTIL.deleteTable(table2_restore);
  TEST_UTIL.deleteTable(table3_restore);
  hba.close();
}
 
Example #3
Source File: MetaServiceImpl.java    From Jantent with MIT License 6 votes vote down vote up
@Override
    public void saveMeta(String type, String name, Integer mid) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(name)) {
            MetaVoExample metaVoExample = new MetaVoExample();
            metaVoExample.createCriteria().andTypeEqualTo(type).andNameEqualTo(name);
            List<MetaVo> metaVos = metaDao.selectByExample(metaVoExample);
            MetaVo metas;
            if (metaVos.size() != 0) {
                throw new TipException("已经存在该项");
            } else {
                metas = new MetaVo();
                metas.setName(name);
                if (null != mid) {
                    MetaVo original = metaDao.selectByPrimaryKey(mid);
                    metas.setMid(mid);
                    metaDao.updateByPrimaryKeySelective(metas);
//                    更新原有文章的categories
                    contentService.updateCategory(original.getName(),name);
                } else {
                    metas.setType(type);
                    metaDao.insertSelective(metas);
                }
            }
        }
    }
 
Example #4
Source File: TestInspectorImpl.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private static InspectorImpl initInspector(String urlPrefix) {
  SCBEngine scbEngine = SCBBootstrap.createSCBEngineForTest();
  scbEngine.getTransportManager().clearTransportBeforeInit();

  if (StringUtils.isNotEmpty(urlPrefix)) {
    Map<String, Transport> transportMap = Deencapsulation.getField(scbEngine.getTransportManager(), "transportMap");
    transportMap.put(RESTFUL, new ServletRestTransport());
    ClassLoaderScopeContext.setClassLoaderScopeProperty(DefinitionConst.URL_PREFIX, urlPrefix);
  }

  scbEngine.run();
  SwaggerProducer producer = CoreMetaUtils
      .getSwaggerProducer(scbEngine.getProducerMicroserviceMeta().findSchemaMeta("inspector"));
  InspectorImpl inspector = (InspectorImpl) producer.getProducerInstance();
  return new InspectorImpl(scbEngine, inspector.getInspectorConfig(), new LinkedHashMap<>(schemas));
}
 
Example #5
Source File: ZKScheduleManager.java    From uncode-schedule with GNU General Public License v2.0 6 votes vote down vote up
private TaskDefine getTaskDefine(Runnable task){
	TaskDefine taskDefine = new TaskDefine();
	if(task instanceof org.springframework.scheduling.support.ScheduledMethodRunnable){
		taskDefine.setType(TaskDefine.TASK_TYPE_QS);
		taskDefine.setStartTime(new Date());
		org.springframework.scheduling.support.ScheduledMethodRunnable springScheduledMethodRunnable = (org.springframework.scheduling.support.ScheduledMethodRunnable)task;
		Method targetMethod = springScheduledMethodRunnable.getMethod();
		String[] beanNames = applicationcontext.getBeanNamesForType(targetMethod.getDeclaringClass());
    	if(null != beanNames && StringUtils.isNotEmpty(beanNames[0])){
    		taskDefine.setTargetBean(beanNames[0]);
    		taskDefine.setTargetMethod(targetMethod.getName());
    		LOGGER.info("----------------------name:" + taskDefine.stringKey());
    	}
	}
	return taskDefine;
}
 
Example #6
Source File: AndroidConfig.java    From MixPush with Apache License 2.0 6 votes vote down vote up
/**
 * check androidConfig's parameters
 *
 * @param notification whcic is in message
 */
public void check(Notification notification) {
    if (this.collapseKey != null) {
        ValidatorUtils.checkArgument((this.collapseKey >= -1 && this.collapseKey <= 100), "Collapse Key should be [-1, 100]");
    }

    if (this.urgency != null) {
        ValidatorUtils.checkArgument(StringUtils.equals(this.urgency, Urgency.HIGH.getValue())
                        || StringUtils.equals(this.urgency, Urgency.NORMAL.getValue()),
                "urgency shouid be [HIGH, NORMAL]");
    }

    if (StringUtils.isNotEmpty(this.ttl)) {
        ValidatorUtils.checkArgument(this.ttl.matches(AndroidConfig.TTL_PATTERN), "The TTL's format is wrong");
    }

    if (this.fastAppTargetType != null) {
        ValidatorUtils.checkArgument(this.fastAppTargetType == 1 || this.fastAppTargetType == 2, "Invalid fast app target type[one of 1 or 2]");
    }

    if (null != this.notification) {
        this.notification.check(notification);
    }
}
 
Example #7
Source File: HBase_1_1_2_ClientService.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void deleteCells(String tableName, List<DeleteRequest> deletes) throws IOException {
    List<Delete> deleteRequests = new ArrayList<>();
    for (int index = 0; index < deletes.size(); index++) {
        DeleteRequest req = deletes.get(index);
        Delete delete = new Delete(req.getRowId())
            .addColumn(req.getColumnFamily(), req.getColumnQualifier());
        if (!StringUtils.isEmpty(req.getVisibilityLabel())) {
            delete.setCellVisibility(new CellVisibility(req.getVisibilityLabel()));
        }
        deleteRequests.add(delete);
    }
    batchDelete(tableName, deleteRequests);
}
 
Example #8
Source File: StringUtilities.java    From StatsAgg with Apache License 2.0 6 votes vote down vote up
public static List<String> getListOfStringsFromDelimitedString(String newlineDelimitedString, char delimiter) {
    
    if ((newlineDelimitedString == null) || newlineDelimitedString.isEmpty()) {
        return new ArrayList<>();
    }
    
    String[] stringArray = org.apache.commons.lang.StringUtils.split(newlineDelimitedString, delimiter);
    if (stringArray.length == 0) return new ArrayList<>();
    List<String> stringList = new ArrayList<>();
    stringList.addAll(Arrays.asList(stringArray));
    return stringList;
}
 
Example #9
Source File: LogicalPlanConfiguration.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Get the application alias name for an application class if one is available.
 * The path for the application class is specified as a parameter. If an alias was specified
 * in the configuration file or configuration opProps for the application class it is returned
 * otherwise null is returned.
 *
 * @param appPath The path of the application class in the jar
 * @return The alias name if one is available, null otherwise
 */
public String getAppAlias(String appPath)
{
  String appAlias;
  if (appPath.endsWith(CLASS_SUFFIX)) {
    appPath = appPath.replace("/", KEY_SEPARATOR).substring(0, appPath.length() - CLASS_SUFFIX.length());
  }
  appAlias = stramConf.appAliases.get(appPath);
  if (appAlias == null) {
    try {
      ApplicationAnnotation an = Thread.currentThread().getContextClassLoader().loadClass(appPath).getAnnotation(ApplicationAnnotation.class);
      if (an != null && StringUtils.isNotBlank(an.name())) {
        appAlias = an.name();
      }
    } catch (ClassNotFoundException e) {
      // ignore
    }
  }
  return appAlias;
}
 
Example #10
Source File: HBaseTableInfo.java    From DDMQ with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validate() throws ConfigException {
    if (StringUtils.isEmpty(hbaseTable)) {
        throw new ConfigException("hbaseTable is empty");
    }
    if (StringUtils.isEmpty(columnFamily)) {
        throw new ConfigException("columnFamily is empty");
    }
    if (StringUtils.isEmpty(nameSpace)) {
        throw new ConfigException("nameSpace is empty");
    }
    if (CollectionUtils.isEmpty(columns)) {
        throw new ConfigException("columns is empty");
    }
    for (HBaseColumnInfo column : columns) {
        if (!column.validate()) {
            throw new ConfigException("column is invalid");
        }
    }
    if (keyCol != null && !keyCol.validate()) {
        throw new ConfigException("keyCol is invalid");
    }
    return true;
}
 
Example #11
Source File: ReflectUtils.java    From RuoYi-Vue with MIT License 6 votes vote down vote up
/**
 * 调用Setter方法, 仅匹配方法名。
 * 支持多级,如:对象名.对象名.方法
 */
public static <E> void invokeSetter(Object obj, String propertyName, E value)
{
    Object object = obj;
    String[] names = StringUtils.split(propertyName, ".");
    for (int i = 0; i < names.length; i++)
    {
        if (i < names.length - 1)
        {
            String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
            object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
        }
        else
        {
            String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
            invokeMethodByName(object, setterMethodName, new Object[] { value });
        }
    }
}
 
Example #12
Source File: RecordPermissionsRest.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Iterates over the JSONArray of users or groups and adds an AllOf with a single Match to the provided AnyOf.
 *
 * @param array The JSONArray of users or groups to iterate over
 * @param attributeDesignator the AttributeDesignatorType to apply to the MatchType
 * @param anyOfArray the AnyOfType to add the AllOf statement to
 */
private void addUsersOrGroupsToAnyOf(JSONArray array, AttributeDesignatorType attributeDesignator,
                                     AnyOfType... anyOfArray) {
    for (int i = 0; i < array.size(); i++) {
        String value = array.optString(i);
        if (StringUtils.isEmpty(value)) {
            throw new IllegalArgumentException("Invalid JSON representation of a Policy."
                    + " User or group not set properly.");
        }
        AttributeValueType userAttrVal = createAttributeValue(XSD.STRING, value);

        MatchType userMatch = createMatch(XACML.STRING_EQUALS, attributeDesignator, userAttrVal);
        AllOfType userAllOf = new AllOfType();
        userAllOf.getMatch().add(userMatch);
        for (AnyOfType anyOf : anyOfArray) {
            anyOf.getAllOf().add(userAllOf);
        }
    }
}
 
Example #13
Source File: BlackDuckIntegrationTest.java    From synopsys-detect with Apache License 2.0 6 votes vote down vote up
@BeforeAll
public static void setup() {
    logger = new BufferedIntLogger();

    Assumptions.assumeTrue(StringUtils.isNotBlank(System.getenv().get(TEST_BLACKDUCK_URL_KEY)));
    Assumptions.assumeTrue(StringUtils.isNotBlank(System.getenv().get(TEST_BLACKDUCK_USERNAME_KEY)));
    Assumptions.assumeTrue(StringUtils.isNotBlank(System.getenv().get(TEST_BLACKDUCK_PASSWORD_KEY)));

    final BlackDuckServerConfigBuilder blackDuckServerConfigBuilder = BlackDuckServerConfig.newBuilder();
    blackDuckServerConfigBuilder.setProperties(System.getenv().entrySet());
    blackDuckServerConfigBuilder.setUrl(System.getenv().get(TEST_BLACKDUCK_URL_KEY));
    blackDuckServerConfigBuilder.setUsername(System.getenv().get(TEST_BLACKDUCK_USERNAME_KEY));
    blackDuckServerConfigBuilder.setPassword(System.getenv().get(TEST_BLACKDUCK_PASSWORD_KEY));
    blackDuckServerConfigBuilder.setTrustCert(true);
    blackDuckServerConfigBuilder.setTimeoutInSeconds(5 * 60);

    blackDuckServicesFactory = blackDuckServerConfigBuilder.build().createBlackDuckServicesFactory(logger);
    blackDuckService = blackDuckServicesFactory.createBlackDuckService();
    projectService = blackDuckServicesFactory.createProjectService();
    projectBomService = blackDuckServicesFactory.createProjectBomService();
    codeLocationService = blackDuckServicesFactory.createCodeLocationService();
    reportService = blackDuckServicesFactory.createReportService(120 * 1000);

    previousShouldExit = Application.shouldExit();
    Application.setShouldExit(false);
}
 
Example #14
Source File: Mapper4ORM.java    From S-mall-ssm with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 写入时,处理所有 Enum 的填充
 *
 * @param object 被填充的对象
 * @throws Exception 反射异常
 */
public void fillEnumOnWriting(Object object) throws Exception {
    if (object == null) {
        return;
    }
    Class clazz = object.getClass();
    // 获取所有 ManyToOne注解的Filed
    List<Field> result = getFieldsEquals(clazz, Enumerated.class);
    for (Field field : result) {
        //获取Enum对应的,String类型的变量名
        String varName = field.getAnnotation(Enumerated.class).var();

        //获取 Enum
        Enum enumObj = (Enum) clazz.
                getMethod("get" + StringUtils.capitalize(field.getName())).invoke(object);

        // 转成 String,插回 varName
        String enumString = enumObj.name();
        clazz.getMethod("set" + StringUtils.capitalize(varName), String.class)
                .invoke(object, enumString);
    }
}
 
Example #15
Source File: AbstractRestController.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
protected Location getLocation(Tenant tenant, Application application, String locationName) throws BadServiceResponseException, NotFoundResponseException {

        if (StringUtils.isBlank(locationName)) {
            return null;
        }

        ServiceResponse<Location> applicationResponse = locationSearchService.findByName(tenant, application, locationName, true);
        if (!applicationResponse.isOk()) {
            if (applicationResponse.getResponseMessages().containsKey(LocationService.Messages.LOCATION_NOT_FOUND.getCode())) {
                throw new NotFoundResponseException(applicationResponse);

            } else {
                Set<String> validationsCode = new HashSet<>();
                for (LocationService.Validations value : LocationService.Validations.values()) {
                    validationsCode.add(value.getCode());
                }

                throw new BadServiceResponseException( applicationResponse, validationsCode);
            }
        }

        return applicationResponse.getResult();

    }
 
Example #16
Source File: NumberDatatype.java    From cuba with Apache License 2.0 6 votes vote down vote up
/**
 * Creates non-localized format.
 */
protected NumberFormat createFormat() {
    if (formatPattern != null) {
        DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();

        if (!StringUtils.isBlank(decimalSeparator))
            formatSymbols.setDecimalSeparator(decimalSeparator.charAt(0));

        if (!StringUtils.isBlank(groupingSeparator))
            formatSymbols.setGroupingSeparator(groupingSeparator.charAt(0));

        return new DecimalFormat(formatPattern, formatSymbols);
    } else {
        return NumberFormat.getNumberInstance();
    }
}
 
Example #17
Source File: BlockImageNode.java    From swagger2markup with Apache License 2.0 6 votes vote down vote up
@Override
public void processPositionalAttributes() {
    String attr1 = pop("1", "alt");
    if (StringUtils.isNotBlank(attr1)) {
        attrs.add(attr1);
    }

    String attr2 = pop("2", "width");
    if (StringUtils.isNotBlank(attr2)) {
        attrs.add(attr2);
    }

    String attr3 = pop("3", "height");
    if (StringUtils.isNotBlank(attr3)) {
        attrs.add(attr3);
    }
}
 
Example #18
Source File: RouteEnhanceCacheServiceImpl.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Override
public void removeBlackList(BlackList blackList) {
    String key = StringUtils.isNotBlank(blackList.getIp()) ?
            RouteEnhanceCacheUtil.getBlackListCacheKey(blackList.getIp()) :
            RouteEnhanceCacheUtil.getBlackListCacheKey();
    redisService.setRemove(key, JSONObject.toJSONString(blackList));
}
 
Example #19
Source File: SmsUtils.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static User getUser( String sender, SMSCommand smsCommand, List<User> userList )
{
    OrganisationUnit orgunit = null;
    User user = null;

    for ( User u : userList )
    {
        OrganisationUnit ou = u.getOrganisationUnit();

        if ( ou != null )
        {
            if ( orgunit == null )
            {
                orgunit = ou;
            }
            else if ( orgunit.getId() == ou.getId() )
            {
            }
            else
            {
                throw new SMSParserException( StringUtils.defaultIfBlank( smsCommand.getMoreThanOneOrgUnitMessage(),
                    SMSCommand.MORE_THAN_ONE_ORGUNIT_MESSAGE ) );
            }
        }

        user = u;
    }

    if ( user == null )
    {
        throw new SMSParserException( "User is not associated with any orgunit. Please contact your supervisor." );
    }

    return user;
}
 
Example #20
Source File: ProgramArguments.java    From javaccPlugin with MIT License 5 votes vote down vote up
public void add(String name, String value) {
    String argument = value;
    if (!StringUtils.isEmpty(name)) {
        argument = String.format(JAVACC_PROGRAM_ARGUMENT_FORMAT, name, value);
    }

    if (!filenameAdded) {
        programArguments.add(argument);
    } else {
        programArguments.add(programArguments.size() - 1, argument);
    }
}
 
Example #21
Source File: MyFileUtils.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        File big = new File("F:\\gho\\win7_32.gho");

        String[] filter = {"pdf", "jpg"};

        File dir = new File("G:\\魏勃资料库");
        File dir2 = new File("G:\\2017-\\1\\2018_04\\");
        File dir3 = new File("G:\\2017-\\2\\2018_04\\");
        File dir4 = new File("D:\\01");
        File dir5 = new File("D:\\01\\01");

        //  System.out.println(Arrays.asList(dir.listFiles()));
        // System.out.println("file name = "+dir.getName());

        // System.out.println(new ArrayList<>(3).size());


//        Map<String, List<String>> lists = findDuplicateFiles(Arrays.asList(dir2, dir3));
//        MyFastJsonUtils.prettyPrint(lists);

        System.out.println(StringUtils.center("splite", 80, "*"));

        deleteDuplicateFiles("G:\\2017-\\1\\", Arrays.asList(dir2, dir3));
//        long start1 = System.nanoTime();
//        String hash1 = DigestUtils.md5Hex(new FileInputStream(big));
//        System.out.println(hash1 + " : " + (System.nanoTime() - start1));
//
//        long start2 = System.nanoTime();
//        HashCode hc = Files.hash(big, Hashing.md5());
//        System.out.println(hc.toString() + " : " + (System.nanoTime() - start2));

    }
 
Example #22
Source File: MyHandshakeInterceptor.java    From MyBlog with Apache License 2.0 5 votes vote down vote up
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
    Subject subject = SecurityUtils.getSubject();
    //未登录则不建立连接
    if (!subject.isAuthenticated() && !subject.isRemembered()) {
        return false;
    }
    String username = (String) SecurityUtils.getSubject().getPrincipal();
    if (StringUtils.isBlank(username)) {
        //用户名为空则不建立连接
        return false;
    }
    attributes.put("username", username);
    return true;
}
 
Example #23
Source File: CmdSources.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@Override
void runCmd() throws Exception {
    admin.sources().getBuiltInSources().stream().filter(x -> !StringUtils.isEmpty(x.getSourceClass()))
            .forEach(connector -> {
                System.out.println(connector.getName());
                System.out.println(WordUtils.wrap(connector.getDescription(), 80));
                System.out.println("----------------------------------------");
            });
}
 
Example #24
Source File: WebAbstractTable.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public String getStyleName() {
    String styleName = super.getStyleName();
    for (String internalStyle : internalStyles) {
        styleName = styleName.replace(internalStyle, "");
    }
    return StringUtils.normalizeSpace(styleName);
}
 
Example #25
Source File: DateUtils.java    From azeroth with Apache License 2.0 5 votes vote down vote up
/**
 * 格式化日期为日期字符串<br>
 * generate by: vakin jiang at 2012-3-7
 *
 * @param orig
 * @param patterns
 * @return
 */
public static String format(Date date, String... patterns) {
    if (date == null) { return ""; }
    String pattern = TIMESTAMP_PATTERN;
    if (patterns != null && patterns.length > 0 && StringUtils.isNotBlank(patterns[0])) {
        pattern = patterns[0];
    }
    return DateFormatUtils.format(date, pattern);
}
 
Example #26
Source File: HaloInterceptor.java    From Milkomeda with MIT License 5 votes vote down vote up
@SuppressWarnings({"unchecked", "rawtypes"})
private Object warpIntercept(Invocation invocation, MappedStatement mappedStatement, String sql, Object param) throws Throwable {
    // 如果处理器为空,直接返回
    if (CollectionUtils.isEmpty(HaloContext.getTableNameMap())) {
        return invocation.proceed();
    }
    String tableName = MybatisUtil.getFirstTableName(sql);
    if (StringUtils.isEmpty(tableName)) {
        return invocation.proceed();
    }

    // Mybatis map参数获取不存在时会抛异常,转为普通map
    if (param instanceof DefaultSqlSession.StrictMap) {
        param = new HashMap((Map) param);
    }

    // 匹配所有
    invokeWithTable(tableName,"*", sql, mappedStatement, param, null, HaloType.PRE);
    // 完全匹配
    invokeWithTable(tableName, tableName, sql, mappedStatement, param, null, HaloType.PRE);
    Object result = invocation.proceed();
    // 匹配所有
    invokeWithTable(tableName, "*", sql, mappedStatement, param, result, HaloType.POST);
    // 完全匹配
    invokeWithTable(tableName, tableName, sql, mappedStatement, param, result, HaloType.POST);
    return result;
}
 
Example #27
Source File: ApiArticleService.java    From codeway_service with GNU General Public License v3.0 5 votes vote down vote up
public Page<Article> findArticleByCondition(Article article, String keyword, Pageable pageable) {
	// 默认首页
	Specification<Article> condition = (root, query, builder) -> {
		List<javax.persistence.criteria.Predicate> predicates = new ArrayList<>();
		if (StringUtils.isNotEmpty(article.getCategoryId())) {
			predicates.add(builder.equal(root.get("categoryId"), article.getTitle()));
		}
		if (StringUtils.isNotEmpty(keyword)) {
			predicates.add(builder.like(root.get("title"), "%" + keyword + "%"));
		}
		return query.where(predicates.toArray(new javax.persistence.criteria.Predicate[0])).getRestriction();
	};
	return articleDao.findAll(condition, pageable);
}
 
Example #28
Source File: KinesisTestUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static com.amazonaws.services.kinesis.model.Record getConsumerTestRecord(int seqNo) {
  com.amazonaws.services.kinesis.model.Record record = new com.amazonaws.services.kinesis.model.Record()
      .withData(ByteBuffer.wrap(String.format("{\"seq\": %s}", seqNo).getBytes()))
      .withPartitionKey(StringUtils.repeat("0", 19))
      .withSequenceNumber(String.valueOf(seqNo))
      .withApproximateArrivalTimestamp(Calendar.getInstance().getTime());

  return new UserRecord(record);
}
 
Example #29
Source File: GitHubAuthFilter.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Handles an authentication request.
 * @param request HTTP request
 * @param response HTTP response
 * @return an authentication object that contains the principal object if successful.
 * @throws IOException ex
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
	final String requestURI = request.getRequestURI();
	UserAuthentication userAuth = null;

	if (requestURI.endsWith(GITHUB_ACTION)) {
		String authCode = request.getParameter("code");
		if (!StringUtils.isBlank(authCode)) {
			String appid = SecurityUtils.getAppidFromAuthRequest(request);
			String redirectURI = SecurityUtils.getRedirectUrl(request);
			App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
			String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.GITHUB_PREFIX);
			String entity = Utils.formatMessage(PAYLOAD, authCode, Utils.urlEncode(redirectURI), keys[0], keys[1]);

			HttpPost tokenPost = new HttpPost(TOKEN_URL);
			tokenPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
			tokenPost.setHeader(HttpHeaders.ACCEPT, "application/json");
			tokenPost.setEntity(new StringEntity(entity, "UTF-8"));
			try (CloseableHttpResponse resp1 = httpclient.execute(tokenPost)) {
				if (resp1 != null && resp1.getEntity() != null) {
					Map<String, Object> token = jreader.readValue(resp1.getEntity().getContent());
					if (token != null && token.containsKey("access_token")) {
						userAuth = getOrCreateUser(app, (String) token.get("access_token"));
					}
					EntityUtils.consumeQuietly(resp1.getEntity());
				}
			}
		}
	}

	return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
}
 
Example #30
Source File: DemoTest.java    From mybatis-dynamic-query with Apache License 2.0 5 votes vote down vote up
@Test
public void testIgnoreFieldOperation() {
    DynamicQuery<Product> dynamicQuery = DynamicQuery.createQuery(Product.class)
            .ignore(Product::getProductId)
            .and(Product::getPrice, greaterThan(BigDecimal.valueOf(16)))
            .orderBy(Product::getPrice, desc())
            .orderBy(Product::getProductId, desc());
    List<Product> products = PageHelper.startPage(0, 100, false)
            .doSelectPage(() -> productDao.selectByDynamicQuery(dynamicQuery));

    for (Product p : products) {
        // categoryID ignore to select
        assertEquals(true, StringUtils.isNotBlank(p.getProductName()));
    }
}