Java Code Examples for com.beust.jcommander.internal.Maps

The following examples show how to use com.beust.jcommander.internal.Maps. These examples are extracted from open source projects. 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 Project: seezoon-framework-all   Source File: WechatServiceAPI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * author token 换取用户信息
 * @param accessToken
 * @return
 */
public UserInfo userinfo(AuthAccessToken accessToken) {
	Assert.notNull(accessToken,"accessToken 为null");
	Assert.hasLength(accessToken.getAccess_token(),"accessToken 为空");
	Assert.hasLength(accessToken.getOpenid(),"openid 为空");
	Map<String,String> params = Maps.newHashMap();
	params.put("access_token",accessToken.getAccess_token());
	params.put("openid",accessToken.getOpenid());
	params.put("lang","zh_CN");
	params.put("grant_type","authorization_code");
	UserInfo userInfo = HttpRequestUtils.doGet("https://api.weixin.qq.com/sns/userinfo", params,UserInfo.class);
	if (userInfo.isSuccess()) {
		return userInfo;
	} else {
		throw new ServiceException(accessToken.getErrmsg());
	}
}
 
Example 2
Source Project: seezoon-framework-all   Source File: WechatServiceAPI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取接口操作token
 * @return
 */
public String getToken() {
	Map<String,String> params = Maps.newHashMap();
	params.put("grant_type","client_credential");
	params.put("appid",appId);
	params.put("secret",appsecret);
	String cachedToken = valueOperations.get("wx_token");
	Long expire = valueOperations.getOperations().getExpire("wx_token", TimeUnit.SECONDS);
	if (StringUtils.isNotEmpty(cachedToken) && expire > 3600) {//缓存两小时,剩余时间小于1小时就重新拿
		return cachedToken;
	}  else {
		Token token = HttpRequestUtils.doGet("https://api.weixin.qq.com/cgi-bin/token", params,Token.class);
		if (token.isSuccess())  {
			valueOperations.set("wx_token", token.getAccess_token(),7200,TimeUnit.SECONDS);
			return token.getAccess_token();
		} else {
			throw new ServiceException(token.getErrmsg());
		}
	}
}
 
Example 3
Source Project: seezoon-framework-all   Source File: WechatServiceAPI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * h5 js api ticket
 * 
 * @return
 */
public String getJsApiTicket() {
	String token = this.getToken();
	Assert.hasLength(token,"token 为null");
	Map<String,String> params = Maps.newHashMap();
	params.put("access_token",token);
	params.put("type","jsapi");
	String cachedTicket = valueOperations.get("wx_js_ticket");
	Long expire = valueOperations.getOperations().getExpire("wx_js_ticket", TimeUnit.SECONDS);
	if (StringUtils.isNotEmpty(cachedTicket) && expire > 3600) {//缓存两小时,剩余时间小于1小时就重新拿
		return cachedTicket;
	}  else {
		JsApiTicket jsApiTicket = HttpRequestUtils.doGet("https://api.weixin.qq.com/cgi-bin/ticket/getticket", params,JsApiTicket.class);
		if (jsApiTicket.isSuccess())  {
			valueOperations.set("wx_js_ticket", jsApiTicket.getTicket(),7200,TimeUnit.SECONDS);
			return jsApiTicket.getTicket();
		} else {
			throw new ServiceException(jsApiTicket.getErrmsg());
		}
	}
}
 
Example 4
@Override
public void createProducers(List<String> topics) {
    List<List<String>> topicsPerProducer = ListPartition.partitionList(topics,
                                                        producerWorkers.size());
    Map<String, List<String>> topicsPerProducerMap = Maps.newHashMap();
    int i = 0;
    for (List<String> assignedTopics : topicsPerProducer) {
        topicsPerProducerMap.put(producerWorkers.get(i++), assignedTopics);
    }

    // Number of actually used workers might be less than available workers
    numberOfUsedProducerWorkers = i;

    List<CompletableFuture<Void>> futures = topicsPerProducerMap.keySet().stream().map(producer -> {
        try {
            return sendPost(producer, "/create-producers",
                    writer.writeValueAsBytes(topicsPerProducerMap.get(producer)));
        } catch (Exception e) {
            CompletableFuture<Void> future = new CompletableFuture<>();
            future.completeExceptionally(e);
            return future;
        }
    }).collect(toList());

    FutureUtil.waitForAll(futures).join();
}
 
Example 5
@Override
public void createConsumers(ConsumerAssignment overallConsumerAssignment) {
    List<List<TopicSubscription>> subscriptionsPerConsumer = ListPartition.partitionList(
                                                                    overallConsumerAssignment.topicsSubscriptions,
                                                                    consumerWorkers.size());
    Map<String, ConsumerAssignment> topicsPerWorkerMap = Maps.newHashMap();
    int i = 0;
    for (List<TopicSubscription> tsl : subscriptionsPerConsumer) {
        ConsumerAssignment individualAssignement = new ConsumerAssignment();
        individualAssignement.topicsSubscriptions = tsl;
        topicsPerWorkerMap.put(consumerWorkers.get(i++), individualAssignement);
    }

    List<CompletableFuture<Void>> futures = topicsPerWorkerMap.keySet().stream().map(consumer -> {
        try {
            return sendPost(consumer, "/create-consumers",
                    writer.writeValueAsBytes(topicsPerWorkerMap.get(consumer)));
        } catch (Exception e) {
            CompletableFuture<Void> future = new CompletableFuture<>();
            future.completeExceptionally(e);
            return future;
        }
    }).collect(toList());

    FutureUtil.waitForAll(futures).join();
}
 
Example 6
Source Project: wish-pay   Source File: ZxingUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将内容contents生成长为width,宽为width的图片,图片路径由imgPath指定
 */
public static File getQRCodeImge(String contents, int width, int height, String imgPath) {
    try {
        Map<EncodeHintType, Object> hints = Maps.newHashMap();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF8");

        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);

        File imageFile = new File(imgPath);
        writeToFile(bitMatrix, "png", imageFile);

        return imageFile;

    } catch (Exception e) {
        log.error("create QR code error!", e);
        return null;
    }
}
 
Example 7
Source Project: wish-pay   Source File: ZxingUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 将内容contents生成长为width,宽为width的图片,返回刘文静
 */
public static ServletOutputStream getQRCodeImge(String contents, int width, int height) throws IOException {
    ServletOutputStream stream = null;
    try {
        Map<EncodeHintType, Object> hints = Maps.newHashMap();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hints.put(EncodeHintType.CHARACTER_SET, "UTF8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
        return stream;
    } catch (Exception e) {
        log.error("create QR code error!", e);
        return null;
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
 
Example 8
Source Project: wish-pay   Source File: AliPayUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取阿里支付链接的所有参数列表
 *
 * @param request
 * @return
 */
public static Map<String, String> getAlipayNotify(HttpServletRequest request) {
    Map<String, String> params = Maps.newHashMap();
    Map requestParams = request.getParameterMap();
    for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
        String name = iter.next();
        String[] values = (String[]) requestParams.get(name);
        String valueStr = "";
        for (int i = 0; i < values.length; i++) {
            valueStr = (i == values.length - 1) ? valueStr + values[i]
                    : valueStr + values[i] + ",";
        }
        //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
        //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
        params.put(name, valueStr);
    }
    return params;
}
 
Example 9
Source Project: muJava   Source File: FuzzyMap.java    License: Apache License 2.0 6 votes vote down vote up
private static <V> V findAbbreviatedValue(Map<? extends IKey, V> map, IKey name,
    boolean caseSensitive) {
  String string = name.getName();
  Map<String, V> results = Maps.newHashMap();
  for (IKey c : map.keySet()) {
    String n = c.getName();
    boolean match = (caseSensitive && n.startsWith(string))
        || ((! caseSensitive) && n.toLowerCase().startsWith(string.toLowerCase()));
    if (match) {
      results.put(n, map.get(c));
    }
  }

  V result;
  if (results.size() > 1) {
    throw new ParameterException("Ambiguous option: " + name
        + " matches " + results.keySet());
  } else if (results.size() == 1) {
    result = results.values().iterator().next();
  } else {
    result = null;
  }

  return result;
}
 
Example 10
Source Project: monasca-thresh   Source File: AlarmSqlImplTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(groups = "orm")
public void checkComplexMetrics() {
  final Alarm newAlarm = new Alarm(alarmDef, AlarmState.ALARM);

  for (final String hostname : Arrays.asList("vivi", "eleanore")) {
    for (final String metricName : Arrays.asList("cpu", "load")) {
      final Map<String, String> dimensions = Maps.newHashMap();
      dimensions.put("first", "first_value");
      dimensions.put("second", "second_value");
      dimensions.put("hostname", hostname);
      final MetricDefinition md = new MetricDefinition(metricName, dimensions);
      newAlarm.addAlarmedMetric(new MetricDefinitionAndTenantId(md, TENANT_ID));
    }
  }
  dao.createAlarm(newAlarm);

  final Alarm found = dao.findById(newAlarm.getId());
  // Have to check both ways because there was a bug in AlarmDAOImpl and it showed up if both
  // ways were tested
  assertTrue(newAlarm.equals(found));
  assertTrue(found.equals(newAlarm));
}
 
Example 11
@Test
public void asDataPointsShouldReturnCorrectMissingSensedDataPoints() {

    List<DataPoint<PhysicalActivity>> dataPoints = mapper.asDataPoints(singletonList(responseNode));

    PhysicalActivity expectedPhysicalActivity = new PhysicalActivity.Builder("Bike")
            .setDistance(new LengthUnitValue(METER, 6318.2688961))
            .setEffectiveTimeFrame(
                    TimeInterval.ofEndDateTimeAndDuration(OffsetDateTime.parse("2015-04-29T16:07:07-04:00"),
                            new DurationUnitValue(SECOND, 343)))
            .setCaloriesBurned(new KcalUnitValue(KILOCALORIE, 27.16863765916))
            .build();

    assertThat(dataPoints.get(1).getBody(), equalTo(expectedPhysicalActivity));

    DataPointHeader testDataPointHeader = dataPoints.get(1).getHeader();
    Map<String, Object> testProperties = Maps.newHashMap();
    testProperties.put(HEADER_EXTERNAL_ID_KEY, "SbiOBJjJJk8n2xLpNTMFng12pGRjX-qe");
    testProperties.put(HEADER_SOURCE_UPDATE_KEY, "2015-04-29T20:07:56Z");
    testProperties.put(HEADER_SCHEMA_ID_KEY, PhysicalActivity.SCHEMA_ID);
    testDataPointHeader(testDataPointHeader, testProperties);
}
 
Example 12
Source Project: monasca-common   Source File: AlarmExpressionTest.java    License: Apache License 2.0 6 votes vote down vote up
public void shouldParseDeterministicExpression() {
  final Map<String, String> dimensions = Maps.newHashMap();
  final ArrayList<AlarmExpression> expressions = Lists.newArrayList(
      new AlarmExpression("count(log.error{},deterministic,20) > 5")
  );
  final MetricDefinition metricDefinition = new MetricDefinition("log.error", dimensions);

  final AlarmSubExpression logErrorExpr = new AlarmSubExpression(
      AggregateFunction.COUNT,
      metricDefinition,
      AlarmOperator.GT,
      5,
      20,
      1,
      true // each expression is deterministic
  );

  for (final AlarmExpression expr : expressions) {
    final List<AlarmSubExpression> subExpressions = expr.getSubExpressions();

    assertTrue(expr.isDeterministic());  // each expression is deterministic
    assertEquals(1, subExpressions.size());
    assertEquals(subExpressions.get(0), logErrorExpr);
  }
}
 
Example 13
/**
 * The String key/value pairs to be passed to the Sonar Runner.
 *
 * {@code null} values are not permitted.
 */
@Input
public Map<String, Object> getSonarProperties() {
    if (sonarProperties == null) {
        sonarProperties = Maps.newLinkedHashMap();
    }

    return sonarProperties;
}
 
Example 14
Source Project: seezoon-framework-all   Source File: WechatServiceAPI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * h5 auth code  换取auth token
 * @param code
 * @return
 */
public AuthAccessToken getUserInfoByCode(String code) {
	Assert.hasLength(code,"code 为空");
	Map<String,String> params = Maps.newHashMap();
	params.put("appid",appId);
	params.put("secret",appsecret);
	params.put("code",code);
	params.put("grant_type","authorization_code");
	AuthAccessToken accessToken = HttpRequestUtils.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", params, AuthAccessToken.class);
	if (accessToken.isSuccess()) {
		return accessToken;
	} else {
		throw new ServiceException(accessToken.getErrmsg());
	}
}
 
Example 15
Source Project: seezoon-framework-all   Source File: WechatServiceAPI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * h5 需要js 的签名参数
 * @param url
 * @return
 */
public Map<String,Object> getJsConfig(String url){
	Assert.hasLength(url,"url 为null");
	String noncestr = WxUtils.createNoncestr();
	long timestamp = WxUtils.createTimestamp();
	String jsapiTicket = getJsApiTicket();
	String signature = WxUtils.jsSignature(noncestr, timestamp, jsapiTicket, url);
	Map<String,Object> config = Maps.newHashMap();
	config.put("noncestr", noncestr);
	config.put("timestamp", timestamp);
	config.put("signature", signature);
	config.put("appId", appId);
	return config;
}
 
Example 16
Source Project: seezoon-framework-all   Source File: WechatServiceAPI.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 小程序登录获取
 * @param code
 * @return
 */
public JsCode2session jscode2session(String code) {
	Assert.hasLength(code,"code为空");
	Map<String,String> params = Maps.newHashMap();
	params.put("appid",mappId);
	params.put("secret",mappsecret);
	params.put("js_code",code);
	params.put("grant_type","authorization_code");
	JsCode2session code2session = HttpRequestUtils.doGet("https://api.weixin.qq.com/sns/jscode2session", params, JsCode2session.class);
	if (code2session.isSuccess())  {
		return code2session;
	} else {
		throw new ServiceException(code2session.getErrmsg());
	}
}
 
Example 17
Source Project: yql-plus   Source File: CompilingTestBase.java    License: Apache License 2.0 5 votes vote down vote up
public void init(Module... modules) {
    if(modules == null) {
        modules = new Module[0];
    }
    this.metricModule = new JavaTestModule.MetricModule();
    injector = Guice.createInjector(Iterables.concat(ImmutableList.<Module>of(new CompilingTestModule()), Arrays.asList(modules)));
    source = injector.getInstance(ASMClassSource.class);
    scope = new GambitSource(source);
    this.modules = Maps.newLinkedHashMap();
    this.views = Maps.newHashMap();
    this.sources = Maps.newLinkedHashMap();
}
 
Example 18
Source Project: muJava   Source File: JCommander.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create the ParameterDescriptions for all the \@Parameter found.
 */
private void createDescriptions() {
  m_descriptions = Maps.newHashMap();

  for (Object object : m_objects) {
    addDescription(object);
  }
}
 
Example 19
Source Project: muJava   Source File: JCommander.java    License: Apache License 2.0 5 votes vote down vote up
public Map<String, JCommander> getCommands() {
  Map<String, JCommander> res = Maps.newLinkedHashMap();
  for (Map.Entry<ProgramName, JCommander> entry : m_commands.entrySet()) {
    res.put(entry.getKey().m_name, entry.getValue());
  }
  return res;
}
 
Example 20
/**
 * The String key/value pairs to be passed to the Sonar Runner.
 *
 * {@code null} values are not permitted.
 */
@Input
public Map<String, Object> getSonarProperties() {
    if (sonarProperties == null) {
        sonarProperties = Maps.newLinkedHashMap();
    }

    return sonarProperties;
}
 
Example 21
Source Project: sputnik   Source File: Notification.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<Integer> getSputnikIssue() {
    Optional<Integer> sputnikIssue = Optional.absent();
    for (com.jcabi.github.Issue issue : issues.iterate(Maps.<String, String>newHashMap())) {
        com.jcabi.github.Issue.Smart smartIssue = new com.jcabi.github.Issue.Smart(issue);
        try {
            if (smartIssue.title().startsWith(SPUTNIK_PREFIX)) {
                sputnikIssue = Optional.of(smartIssue.number());
            }
        } catch (IOException e) {
            log.error("Error getting issue title for issue #" + issue.number(), e);
        }
    }
    return sputnikIssue;
}
 
Example 22
public Iterator<Index> getIndices(
    final Map<StatisticsId, InternalDataStatistics<SimpleFeature, ?, ?>> stats,
    final BasicQueryByClass query,
    final ChooseBestMatchIndexQueryStrategy strategy) {
  return strategy.getIndices(
      stats,
      query,
      new Index[] {
          IMAGE_CHIP_INDEX1,
          new SpatialTemporalIndexBuilder().createIndex(),
          new SpatialIndexBuilder().createIndex(),
          IMAGE_CHIP_INDEX2},
      null,
      Maps.newHashMap());
}
 
Example 23
public Iterator<Index> getIndices(
    final Map<StatisticsId, InternalDataStatistics<SimpleFeature, ?, ?>> stats,
    final BasicQueryByClass query,
    final ChooseLocalityPreservingQueryStrategy strategy) {
  return strategy.getIndices(
      stats,
      query,
      indices.toArray(new Index[indices.size()]),
      null,
      Maps.newHashMap());
}
 
Example 24
public Iterator<Index> getIndices(
    final Map<StatisticsId, InternalDataStatistics<SimpleFeature, ?, ?>> stats,
    final BasicQueryByClass query,
    final ChooseHeuristicMatchIndexQueryStrategy strategy) {
  return strategy.getIndices(
      stats,
      query,
      indices.toArray(new Index[indices.size()]),
      null,
      Maps.newHashMap());
}
 
Example 25
Source Project: frpMgr   Source File: OnlineController.java    License: MIT License 4 votes vote down vote up
/**
 * 在线用户列表数据
 * @param request
 * @param response
 * @author ThinkGem
 */
@RequiresPermissions("sys:online:view")
@RequestMapping(value = "listData")
@ResponseBody
public List<Map<String, Object>> listData(String isAllOnline, String isVisitor, String sessionId, 
		String userCode, String userName, String userType, String orderBy) {
	List<Map<String, Object>> list = Lists.newArrayList();
	boolean excludeLeave = isAllOnline==null || !Global.YES.equals(isAllOnline);
	boolean excludeVisitor = isVisitor==null || !Global.YES.equals(isVisitor);
		Collection<Session> sessions = sessionDAO.getActiveSessions(excludeLeave, 
			excludeVisitor, null, sessionId, userCode);
	long currentTime = System.currentTimeMillis();
	for (Session session : sessions){
		if (StringUtils.isNotBlank(userName) && ((String)session.getAttribute("userName")).contains(userName)){
			continue;
		}
		if (StringUtils.isNotBlank(userType) && ((String)session.getAttribute("userType")).equals(userType)){
			continue;
		}
		Map<String, Object> map = Maps.newLinkedHashMap();
		// 为了安全性,需要有权限的人才能看
		if (UserUtils.getSubject().isPermitted("sys:online:edit")){
			map.put("id", session.getId().toString()); 
		}
		map.put("startTimestamp", DateUtils.formatDateTime(session.getStartTimestamp()));
		map.put("lastAccessTime", DateUtils.formatDateTime(session.getLastAccessTime()));
		map.put("timeout", TimeUtils.formatDateAgo(session.getTimeout()-(currentTime-session.getLastAccessTime().getTime())));
		PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
		LoginInfo principal = (pc != null ? (LoginInfo)pc.getPrimaryPrincipal() : null);
		if (principal != null){
			map.put("userCode", session.getAttribute("userCode"));// principal.getId());
			map.put("userName", session.getAttribute("userName"));// principal.getName());
			map.put("userType", session.getAttribute("userType"));// ObjectUtils.toString(principal.getParam("userType")));
			map.put("deviceType", ObjectUtils.toString(principal.getParam("deviceType")));
		}
		map.put("host", session.getHost());
		list.add(map);
	}
	// 本地排序
	if (StringUtils.isNotBlank(orderBy)){
		final String[] ss = orderBy.trim().split(" ");
		if (ss != null && ss.length == 2){
			Collections.sort(list, new Comparator<Map<String, Object>>() {
				@Override
				public int compare(Map<String, Object> o1, Map<String, Object> o2) {
					String s1 = (String)o1.get(ss[0]);
					String s2 = (String)o2.get(ss[0]);
					if ("asc".equals(ss[1])){
						return s1.compareTo(s2);
					}else{
						return s2.compareTo(s1);
					}
				}});
		}
	}
	return list;
}
 
Example 26
Source Project: seezoon-framework-all   Source File: T.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void t8() {
	String ipInfo = HttpRequestUtils.doGet("http://ip.taobao.com/service/getIpInfo.php", Maps.newHashMap("ip","223.73.212.106"));
}
 
Example 27
@Test(groups = {"unit", "server"})
public void testInsertMaps() {
    String cql = "insert into test_drive.map_data_type(id,id_uuid,binary_data,date_date,date_time," +
            "date_timestamp,id_timeuuid,net_inet,num_big_integer,num_decimal,num_double,num_float,num_int," +
            "num_small_int,num_tiny_int,num_varint,str_ascii,str_text,str_varchar,true_or_false)\n" +
            "values(5d19b3b2-a889-4913-81ec-164e5845cf36,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

    try {
        java.sql.PreparedStatement s = conn.prepareStatement(cql);
        assertTrue(s instanceof CassandraPreparedStatement);

        CassandraDataTypeConverters c = ((CassandraPreparedStatement) s).getDataTypeConverters();
        int index = 1;
        s.setObject(index++, Maps.newHashMap(UUID.randomUUID(), UUID.randomUUID()));
        //s.setObject(index++, Lists.newArrayList(ByteBuffer.wrap(new byte[]{1, 2, 3})));
        s.setObject(index++, Maps.newHashMap(new byte[]{1, 2, 3}, new byte[]{1, 2, 3}));
        //s.setObject(index++, Lists.newArrayList("2017-01-01"));
        s.setObject(index++, Maps.newHashMap(
                CassandraTestHelper.getInstance().replaceParameter(
                        LocalDate.fromMillisSinceEpoch(System.currentTimeMillis()), Date.class),
                CassandraTestHelper.getInstance().replaceParameter(
                        LocalDate.fromMillisSinceEpoch(System.currentTimeMillis()), Date.class)));
        //s.setObject(index++, Lists.newArrayList("11:50:30"));
        //s.setObject(index++, Lists.newArrayList(LocalTime.now().getMillisOfDay() * 1000000L));
        s.setObject(index++, Maps.newHashMap(
                CassandraTestHelper.getInstance().replaceParameter(
                        new Time(LocalTime.now().toDateTimeToday().getMillis()), Time.class),
                CassandraTestHelper.getInstance().replaceParameter(
                        new Time(LocalTime.now().toDateTimeToday().getMillis()), Time.class)));
        //s.setObject(index++, Lists.newArrayList("2017-02-02 11:50:30.123"));
        s.setObject(index++, Maps.newHashMap(LocalDateTime.now().toDate(),
                LocalDateTime.now().toDate()));
        // or you'll likely end up with error like the following:
        // com.datastax.driver.core.exceptions.InvalidTypeException: xxx is not a Type 1 (time-based) UUID
        s.setObject(index++, Maps.newHashMap(((CassandraPreparedStatement) s)
                        .getDataTypeConverters().defaultValueOf(UUID.class),
                ((CassandraPreparedStatement) s).getDataTypeConverters().defaultValueOf(UUID.class)));
        s.setObject(index++, Maps.newHashMap(InetAddress.getByName("192.168.10.11"),
                InetAddress.getByName("192.168.10.11")));
        s.setObject(index++, Maps.newHashMap(Long.MAX_VALUE, Long.MAX_VALUE));
        s.setObject(index++, Maps.newHashMap(new BigDecimal("33333333333333333333333333333333333"),
                new BigDecimal("33333333333333333333333333333333333")));
        s.setObject(index++, Maps.newHashMap(Double.MAX_VALUE, Double.MAX_VALUE));
        s.setObject(index++, Maps.newHashMap(Float.MAX_VALUE, Float.MAX_VALUE));
        s.setObject(index++, Maps.newHashMap(Integer.MAX_VALUE, Integer.MAX_VALUE));
        s.setObject(index++, Maps.newHashMap(
                CassandraTestHelper.getInstance().replaceParameter(Short.MAX_VALUE, Short.class),
                CassandraTestHelper.getInstance().replaceParameter(Short.MAX_VALUE, Short.class)));
        s.setObject(index++, Maps.newHashMap(
                CassandraTestHelper.getInstance().replaceParameter(Byte.MAX_VALUE, Byte.class),
                CassandraTestHelper.getInstance().replaceParameter(Byte.MAX_VALUE, Byte.class)));
        s.setObject(index++, Maps.newHashMap(new BigInteger("2222222222222222222222222222222222"),
                new BigInteger("2222222222222222222222222222222222")));
        s.setObject(index++, Maps.newHashMap("ascii", "ascii"));
        s.setObject(index++, Maps.newHashMap("text", "text"));
        s.setObject(index++, Maps.newHashMap("varchar", "varchar"));
        s.setObject(index++, Maps.newHashMap(true, true));

        assertFalse(s.execute());
        assertNull(s.getResultSet());
        assertEquals(s.getUpdateCount(), 1);

        s.close();
    } catch (Exception e) {
        e.printStackTrace();
        fail("Error occurred during testing: " + e.getMessage());
    }
}
 
Example 28
Source Project: geowave   Source File: ShapefileQueryOutputFormat.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void output(final ResultSet results) {
  int geometryColumn = -1;
  for (int i = 0; i < results.columnCount(); i++) {
    if (Geometry.class.isAssignableFrom(results.columnType(i))) {
      geometryColumn = i;
      break;
    }
  }
  if (geometryColumn < 0) {
    throw new RuntimeException(
        "Unable to output results to a shapefile without a geometry column.");
  }

  final SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
  ftb.setCRS(results.getCRS());
  ftb.setName(typeName);
  for (int i = 0; i < results.columnCount(); i++) {
    final AttributeTypeBuilder atb = new AttributeTypeBuilder();
    atb.setBinding(results.columnType(i));
    atb.nillable(true);
    if (i == geometryColumn) {
      ftb.add(atb.buildDescriptor("the_geom"));
    } else {
      ftb.add(atb.buildDescriptor(results.columnName(i)));
    }
  }
  final SimpleFeatureType sft = ftb.buildFeatureType();

  final SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(sft);
  final AtomicLong nextId = new AtomicLong(0L);
  final Iterator<SimpleFeature> features = Iterators.transform(results, r -> {
    sfb.reset();
    for (int i = 0; i < results.columnCount(); i++) {
      sfb.add(r.columnValue(i));
    }
    final SimpleFeature feature = sfb.buildFeature(Long.toString(nextId.incrementAndGet()));
    return feature;
  });

  final FileDataStoreFactorySpi factory = FileDataStoreFinder.getDataStoreFactory("shp");
  final File file = new File(outputFile);
  final Map<String, Serializable> params = Maps.newHashMap();
  final Transaction transaction = new DefaultTransaction("Write Results");
  try {
    params.put("url", file.toURI().toURL());
    final DataStore dataStore = factory.createNewDataStore(params);
    dataStore.createSchema(sft);
    final SimpleFeatureStore store =
        (SimpleFeatureStore) dataStore.getFeatureSource(dataStore.getTypeNames()[0]);
    store.setTransaction(transaction);
    final SimpleFeatureCollection featureCollection =
        DataUtilities.collection(new SimpleFeatureIterator() {
          @Override
          public boolean hasNext() {
            return features.hasNext();
          }

          @Override
          public SimpleFeature next() throws NoSuchElementException {
            return features.next();
          }

          @Override
          public void close() {}
        });
    store.addFeatures(featureCollection);
    transaction.commit();
  } catch (final Exception e) {
    try {
      transaction.rollback();
    } catch (final IOException ioe) {
      throw new RuntimeException("Encountered an error when rolling back transaction", ioe);
    }
    throw new RuntimeException(
        "Encountered an error when writing the features to the file: " + e.getMessage(),
        e);
  }
}