/** * Gets all user's present in the twitch chat of a channel. * * @param channelName Channel to fetch the information for. * @return All chatters in a channel, separated into groups like admins, moderators and viewers. */ public Chatter getChatters(String channelName) { // Endpoint String requestUrl = String.format("%s/group/user/%s/chatters", Endpoints.TMI.getURL(), channelName); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // REST Request try { if (!restObjectCache.containsKey(requestUrl)) { Logger.trace(this, "Rest Request to [%s]", requestUrl); ChatterResult responseObject = restTemplate.getForObject(requestUrl, ChatterResult.class); restObjectCache.put(requestUrl, responseObject, ExpirationPolicy.CREATED, 60, TimeUnit.SECONDS); } return ((ChatterResult) restObjectCache.get(requestUrl)).getChatters(); } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } // OnError: Return empty result return new Chatter(); }
@Override public BackgroundException map(final IOException failure) { final Throwable[] stack = ExceptionUtils.getThrowables(failure); for(Throwable t : stack) { if(t instanceof BackgroundException) { return (BackgroundException) t; } } if(failure instanceof SSLException) { return new SSLExceptionMappingService().map((SSLException) failure); } final StringBuilder buffer = new StringBuilder(); this.append(buffer, failure.getMessage()); for(Throwable cause : ExceptionUtils.getThrowableList(failure)) { if(!StringUtils.contains(failure.getMessage(), cause.getMessage())) { this.append(buffer, cause.getMessage()); } } return this.wrap(failure, buffer); }
public <T> T parse(String[] args, T inputArgs, Function<? super T, String> validationFunction) { try { List<String> extraArgs = Args.parse(inputArgs, args); if (extraArgs.size() > 0) { printUsageAndExit(inputArgs, "Passed in unnecessary args: " + StringUtils.join(extraArgs, "; ")); } String validationMessage = validationFunction.valueOf(inputArgs); if (validationMessage != null) { printUsageAndExit(inputArgs, validationMessage); } } catch (IllegalArgumentException exc) { printUsageAndExit(inputArgs, ExceptionUtils.getStackTrace(exc)); } LOG.info("Arguments parsed: " + inputArgs.toString()); return inputArgs; }
@Override void invokeMethod(AbstractTest instance, Method method, TestClassContext context, boolean isBeforeAfterGroup) { AbstractWebServiceTest abstractWebServiceTest = (AbstractWebServiceTest) instance; try { method.setAccessible(true); method.invoke(instance); } catch (Throwable e) { String errorMessage = format("Precondition method '%s' failed ", method.getName()) + "\n " + ExceptionUtils.getStackTrace(e); if (isBeforeAfterGroup) { abstractWebServiceTest.setPostponedBeforeAfterGroupFail(errorMessage, context.getTestContext()); } else { abstractWebServiceTest.setPostponedTestFail(errorMessage); } new Report(errorMessage).allure(); } }
/** * Get All Streams (ordered by current viewers, desc) * <p> * Gets the list of all live streams. * Requires Scope: none * * @param limit Maximum number of most-recent objects to return. Default: 25. Maximum: 100. * @param offset Object offset for pagination of results. Default: 0. * @param language Restricts the returned streams to the specified language. Permitted values are locale ID strings, e.g. en, fi, es-mx. * @param game Restricts the returned streams to the specified game. * @param channelIds Receives the streams from a comma-separated list of channel IDs. * @param stream_type Restricts the returned streams to a certain stream type. Valid values: live, playlist, all. Playlists are offline streams of VODs (Video on Demand) that appear live. Default: live. * @return Returns all streams that match with the provided filtering. */ public List<Stream> getAll(Optional<Long> limit, Optional<Long> offset, Optional<String> language, Optional<Game> game, Optional<String> channelIds, Optional<String> stream_type) { // Endpoint String requestUrl = String.format("%s/streams", Endpoints.API.getURL()); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // Parameters restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(25l).toString())); restTemplate.getInterceptors().add(new QueryRequestInterceptor("offset", offset.orElse(0l).toString())); restTemplate.getInterceptors().add(new QueryRequestInterceptor("language", language.orElse(null))); restTemplate.getInterceptors().add(new QueryRequestInterceptor("game", game.map(Game::getName).orElse(null))); restTemplate.getInterceptors().add(new QueryRequestInterceptor("channel", channelIds.isPresent() ? channelIds.get() : null)); restTemplate.getInterceptors().add(new QueryRequestInterceptor("stream_type", stream_type.orElse("all"))); // REST Request try { StreamList responseObject = restTemplate.getForObject(requestUrl, StreamList.class); return responseObject.getStreams(); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return null; }
/** * Endpoint: Get Top Games * Get games by number of current viewers on Twitch. * Requires Scope: none * * @return todo */ public List<TopGame> getTopGames() { // Endpoint String requestUrl = String.format("%s/games/top", Endpoints.API.getURL()); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // REST Request try { Logger.trace(this, "Rest Request to [%s]", requestUrl); TopGameList responseObject = restTemplate.getForObject(requestUrl, TopGameList.class); return responseObject.getTop(); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return null; }
/** * Endpoint: Check User Subscription by Channel * Checks if a specified user is subscribed to a specified channel. * Requires Scope: user_subscriptions * * @param userId UserId of the user. * @param channelId ChannelId of the channel you are checking against. * @return Optional of Type UserSubscriptionCheck. Is only present, when the user is subscribed. */ public Optional<UserSubscriptionCheck> getUserSubcriptionCheck(Long userId, Long channelId) { // Endpoint String requestUrl = String.format("%s/users/%s/subscriptions/%s", Endpoints.API.getURL(), userId, channelId); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // REST Request try { Logger.trace(this, "Rest Request to [%s]", requestUrl); UserSubscriptionCheck responseObject = restTemplate.getForObject(requestUrl, UserSubscriptionCheck.class); return Optional.ofNullable(responseObject); } catch (RestException restException) { if (restException.getRestError().getStatus().equals(422)) { // Channel has no subscription program. Logger.info(this, "Channel %s has no subscription programm.", channelId); } else { Logger.error(this, "RestException: " + restException.getRestError().toString()); } } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return Optional.empty(); }
/** * 缓存配置 */ public void storeConfig(Map<String, String> properties) { try { // 如果缓存文件不存在,则创建 FileUtils.createFileIfAbsent(cacheFile.getPath()); OutputStream out = null; try { out = new FileOutputStream(cacheFile); mapToProps(properties).store(out, "updated at " + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss")); } finally { if (out != null) { out.close(); } } } catch (IOException e) { ExceptionUtils.rethrow(e); } }
/** * Endpoint to get the UserId from the UserName * <p> * https://api.twitch.tv/kraken/users?login=USERNAME * * @param userName todo * @return todo */ public Optional<Long> getUserIdByUserName(String userName) { // Validate Arguments Assert.hasLength(userName, "Please provide a Username!"); // REST Request String requestUrl = String.format("%s/users?login=%s", Endpoints.API.getURL(), userName); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // REST Request if (!restObjectCache.containsKey(requestUrl)) { try { UserList responseObject = restTemplate.getForObject(requestUrl, UserList.class); restObjectCache.put(requestUrl, responseObject, 15, TimeUnit.MINUTES); } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); return Optional.empty(); } } List<User> userList = ((UserList) restObjectCache.get(requestUrl)).getUsers(); // User found? if (userList.size() == 1) { return Optional.ofNullable(userList.get(0).getId()); } else { return Optional.empty(); } }
@Transactional(rollbackFor={Exception.class}) public void selectList() throws Exception { try { //单表查找 ExprBuilder expr = new ExprBuilder(Brand.class); expr.In("code", brandCode).In("name", brandName).orderAsc("id").orderChDesc("name").limit(0, 2000); expr.propEqual("id", "id"); ResultEntity<Brand> brands =baseMapper.selectList(new Brand(),expr); //use Cache ExprBuilder expr2 = new ExprBuilder(Brand.class); expr2.In("code", brandCode).In("name", brandName).orderDesc("id").orderChAsc("name").limit(0, 2000); expr2.propEqual("id", "id"); ResultEntity<Brand> brands2 =baseMapper.selectList(new Brand(),expr); Assert.isTrue(brands.getTotal()>0,"can't find result"); Assert.isTrue(brands2.getTotal()>0,"can't find result"); } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); throw e; } }
@Override public boolean doCommand(MessageReceivedEvent message, BotContext context, String query) { if (!discordService.isSuperUser(message.getAuthor()) || StringUtils.isEmpty(query)) { return false; } message.getChannel().sendTyping(); String script = CommonUtils.unwrapCode(query); try { Object result = getShell(message).evaluate(script); if (result != null) { messageService.sendMessageSilent(message.getChannel()::sendMessage, "```groovy\n" + String.valueOf(result) + "```"); } } catch (Exception e) { String errorText = String.format("\n`%s`\n\nStack trace:```javascript\n%s", e.getMessage(), ExceptionUtils.getStackTrace(e)); EmbedBuilder builder = messageService.getBaseEmbed(); builder.setTitle(e.getClass().getName()); builder.setColor(Color.RED); builder.setDescription(CommonUtils.trimTo(errorText, 2045) + "```"); messageService.sendMessageSilent(message.getChannel()::sendMessage, builder.build()); return fail(message); } return ok(message); }
@Transactional(rollbackFor={Exception.class}) public void selectOne() throws Exception { try { //单表查找 logger.debug("查找单挑记录"); Brand param=new Brand(); param.setId(1); Brand brand =customizeSqlMapper.selectOne(param,new SqlBuilder(Brand.class)); Assert.isTrue(brand!=null,"can't find result"); Shop siteParam=new Shop(); siteParam.setId(1); SqlBuilder sb=new SqlBuilder(Shop.class) .include("brands") .include("pictures") .include("address"); Shop site =customizeSqlMapper.selectOne(siteParam,sb); Assert.isTrue(site!=null,"can't find result"); } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); throw e; } }
/** * Gets posts from a specified channel feed. * * @param channelId The channel id, which the posts should be retrieved from. * @param limit Maximum number of most-recent objects to return. Default: 10. Maximum: 100. * @param cursor Tells the server where to start fetching the next set of results in a multi-page response. * @param commentLimit Specifies the number of most-recent comments on posts that are included in the response. Default: 5. Maximum: 5. * @return posts from a specified channel feed. */ public List<ChannelFeedPost> getFeedPosts(Long channelId, Optional<Long> limit, Optional<String> cursor, Optional<Long> commentLimit) { // Endpoint String requestUrl = String.format("%s/feed/%s/posts", Endpoints.API.getURL(), channelId); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // Parameters restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(10l).toString())); restTemplate.getInterceptors().add(new QueryRequestInterceptor("cursor", cursor.orElse(""))); restTemplate.getInterceptors().add(new QueryRequestInterceptor("comments", commentLimit.orElse(5l).toString())); // REST Request try { Logger.trace(this, "Rest Request to [%s]", requestUrl); ChannelFeed responseObject = restTemplate.getForObject(requestUrl, ChannelFeed.class); return responseObject.getPosts(); } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return new ArrayList<ChannelFeedPost>(); }
/** * 使用sqlbuild查询 使用getDetail方法 暂时废弃 * @throws Exception */ //@SuppressWarnings("deprecation") @Transactional(rollbackFor={Exception.class}) public void selectUseGetDetail() throws Exception { try { Shop shop=new Shop(); shop.setId(1); ExprBuilder expr = new ExprBuilder(Shop.class); expr.In("id", 1,2,3,4,8); SqlBuilder sb=new SqlBuilder(); sb.getDetail(Shop.class, "brands").orderAsc("id"); ResultEntity<Shop> sites =customizeSqlMapper.select(shop,sb,expr); Assert.isTrue(sites.getTotal()>0,"can't find result"); } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); throw e; } }
@Override public Map<AvailabilityZone, List<Instance>> getInstancesMapForZone( AvailabilityZone zone, AmazonEC2Client client) throws Exception { OperationStats op = new OperationStats("ec2InstanceStore", "getInstancesMapForZone"); try { Map<AvailabilityZone, List<Instance>> ret = new HashMap<>(); ret.put(zone, getInstancesForZone(zone, client)); op.succeed(); return ret; } catch (Exception e) { op.failed(); logger.error(ExceptionUtils.getRootCauseMessage(e)); throw e; } }
@Override public void add(Product... products) { new Txn(dBase).call(session -> { for (Product product : products) { try { session.sql("INSERT INTO category_product (category_id, product_id) VALUES (?, ?)") .set(category.id()) .set(product.number()) .insert(Outcome.VOID); } catch (SQLException e) { ExceptionUtils.rethrow(e); } } return null; }); }
/** * Endpoint: Get User Block List * Gets a user’s block list. List sorted by recency, newest first. * Requires Scope: user_blocks_read * * @param credential Credential to use. * @param limit Maximum number of most-recent objects to return (users who started following the channel most recently). Default: 25. Maximum: 100. * @param offset Tells the server where to start fetching the next set of results, in a multi-page response. * @return todo */ public List<Block> getUserBlockList(OAuthCredential credential, Optional<Long> limit, Optional<Long> offset) { // Endpoint String requestUrl = String.format("%s/users/%s/blocks", Endpoints.API.getURL(), credential.getUserId()); RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential); // Parameters restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(25l).toString())); restTemplate.getInterceptors().add(new QueryRequestInterceptor("offset", offset.orElse(0l).toString())); // REST Request try { Logger.trace(this, "Rest Request to [%s]", requestUrl); BlockList responseObject = restTemplate.getForObject(requestUrl, BlockList.class); return responseObject.getBlocks(); } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return new ArrayList<Block>(); }
public void saveMonitorNiPingResult(MonitorNiPingResult monitorNiPingResult) throws NiPingException { Date currentDate = new Date(); monitorNiPingResult.setCreationTime(currentDate); monitorNiPingResult.setModifiedTime(currentDate); monitorNiPingResult.setCollectedTime(currentDate.getTime()); monitorNiPingResult.setStartTime(monitorNiPingResult.getStartTime() * 1000); monitorNiPingResult.setEndTime(monitorNiPingResult.getEndTime() * 1000); try { monitorNiPingResultDao.saveMonitorNiPingResult(monitorNiPingResult); log.debug("monitor NiPing result {} saved", monitorNiPingResult); } catch (DBIException e) { log.error("save monitor niping result {} error: {}", monitorNiPingResult, ExceptionUtils.getMessage(e)); throw new NiPingException(DBError); } }
/** * Callback when the command is invoked */ public void processCommand(ICommandSender sender, String[] args) throws CommandException { if (args.length < 2) { throw new WrongUsageException("commands.tellraw.usage", new Object[0]); } else { EntityPlayer entityplayer = getPlayer(sender, args[0]); String s = buildString(args, 1); try { IChatComponent ichatcomponent = IChatComponent.Serializer.jsonToComponent(s); entityplayer.addChatMessage(ChatComponentProcessor.processComponent(sender, ichatcomponent, entityplayer)); } catch (JsonParseException jsonparseexception) { Throwable throwable = ExceptionUtils.getRootCause(jsonparseexception); throw new SyntaxErrorException("commands.tellraw.jsonException", new Object[] {throwable == null ? "" : throwable.getMessage()}); } } }
/** * Endpoint: Block User * Blocks a user; that is, adds a specified target user to the blocks list of a specified source user. * Requires Scope: user_blocks_edit * * @param credential Credential * @param targetUserId UserID of the Target * @return todo */ public Boolean addBlock(OAuthCredential credential, Long targetUserId) { // Endpoint String requestUrl = String.format("%s/users/%s/blocks/%s", Endpoints.API.getURL(), credential.getUserId(), targetUserId); RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential); // REST Request try { Logger.trace(this, "Rest Request to [%s]", requestUrl); restTemplate.put(requestUrl, Follow.class, new HashMap<String, String>()); return true; } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return false; }
public Page<MonitorNiPingResult> list(String accountId, String taskId, String monitorId, long time, Integer type, Long pageNo, Long pageSize) throws NiPingException { Page<MonitorNiPingResult> page = new Page<>(pageNo, pageSize); try { if (pageNo != null || pageSize != null) { long totalCount = monitorNiPingResultDao.count(accountId, taskId, monitorId, time(time), condition(null, null, null, type), ">="); if (totalCount > 0) { page.setTotalCount(totalCount); page.setData(monitorNiPingResultDao.select(accountId, taskId, monitorId, time(time), condition(null, null, null, type), this.page(page.getOffset(), page.getPageSize()), ">=")); } } else { page.setData(monitorNiPingResultDao.selectAll(accountId, taskId, monitorId, time(time), condition(null, null, null, type), ">=")); } } catch (DBIException e) { log.error("list results accountId {} taskId {} monitorId {} time {} type {} pageNo {} pageSize" + " {} error: {}", accountId, taskId, monitorId, time, type, pageNo, pageSize, ExceptionUtils.getMessage(e)); throw new NiPingException(DBError); } return page; }
public void saveMonitor(Monitor monitor) throws NiPingException { String monitorId = monitor.getMonitorId(); Date currentDate = new Date(); String nipingT = monitor.getNipingT(); monitor.setModifiedTime(currentDate); try { if (monitorDao.countMonitor(monitorId) == 0) { monitor.setCreationTime(currentDate); monitor.setStatus(Monitor.Status.active.getStatus()); monitorDao.insertMonitor(monitor); log.debug("monitor {} saved", monitor); } else if (StringUtils.isNoneBlank(nipingT)) { monitorDao.updateMonitorNiping(monitor); log.debug("monitor {} modified", monitor); } } catch (DBIException e) { log.error("monitors: save monitor {} error: {}", monitor, ExceptionUtils.getMessage(e)); throw new NiPingException(DBError); } }
/** * Endpoint: Unfollow Channel * Deletes a specified user from the followers of a specified channel. * Requires Scope: user_follows_edit * * @param credential Credential * @param channelId Channel to follow * @return Optional Follow, if user is following. */ public Boolean unfollowChannel(OAuthCredential credential, Long channelId) { // Endpoint String requestUrl = String.format("%s/users/%s/follows/channels/%s", Endpoints.API.getURL(), credential.getUserId(), channelId); RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential); // REST Request try { Logger.trace(this, "Rest Request to [%s]", requestUrl); restTemplate.delete(requestUrl); return true; } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return false; }
private void getAutoCompleteValues(final String search) { final Future<?> f = _future.getAndSet(_executor.submit(() -> { try { final List<KeyValuePair<Integer>> values = _provider.getFromHistory(search); final Future<?> current = _future.getAndSet(null); if (current != null) { // if null, been cancelled asyncAutoComplete(values); } } catch (final Throwable e) { LOGGER.error("Fail to get autocomplete", e); JOptionPane.showMessageDialog(null, "failed " + Arrays.toString(ExceptionUtils.getStackFrames(e))); } })); if (f != null) { f.cancel(true); } }
/** * Get Stream by Channel * <p> * Gets stream information (the stream object) for a specified channel. * Requires Scope: none * * @param channel Get stream object of Channel Entity * @return Optional of type Stream is only Present if Stream is Online, returns Optional.empty for Offline streams */ public Optional<Stream> getByChannel(Channel channel) { // Endpoint String requestUrl = String.format("%s/streams/%s", Endpoints.API.getURL(), channel.getId()); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // REST Request try { StreamSingle responseObject = restTemplate.getForObject(requestUrl, StreamSingle.class); // Stream Offline if (responseObject.getStream() == null) { // Stream Offline return Optional.empty(); } else { // Stream Online return Optional.ofNullable(responseObject.getStream()); } } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return null; }
@Override public void onCommand(final MessageReceivedEvent e, final String[] args) { EEWBot.instance.getExecutor().execute(() -> { String remote = null; if (args.length<=0) remote = QuakeInfoDispather.REMOTE; else if (args[0].startsWith("http://")||args[0].startsWith("https://")) remote = args[0]; else reply(e, "URLが不正です"); try { final QuakeInfo info = QuakeInfoDispather.get(remote); e.getChannel().sendMessage(info.buildEmbed()); info.getDetails().forEach(detail -> reply(e, detail.buildEmbed())); } catch (final Exception ex) { Log.logger.info(ExceptionUtils.getStackTrace(ex)); reply(e, "```"+ex.getClass().getSimpleName()+"```"); } }); }
@Override public Response toResponse(final DataIntegrityViolationException exception) { log.error("DataIntegrityViolationException exception", exception); final Throwable root = ExceptionUtils.getRootCause(exception); Matcher matcher = PATTERN_FOREIGN_KEY.matcher(StringUtils.trimToEmpty(root.getMessage())); final String code; if (matcher.find()) { // Foreign key code = "foreign"; } else { matcher = PATTERN_UNICITY.matcher(root.getMessage()); if (matcher.find()) { // Duplicate entry code = "unicity"; } else { // Another SQL error code = "unknown"; matcher = null; } } return toResponse(Status.PRECONDITION_FAILED, newServerError(exception, matcher, code)); }
/** * Gets the steam profile id, if the streamer has linked his steam account. * * @param userName Twitch username * @return todo */ public String getConnectedSteamProfile(String userName) { // Endpoint String requestUrl = String.format("https://api.twitch.tv/api/channels/%s", userName); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // REST Request try { Logger.trace(this, "Rest Request to [%s]", requestUrl); AdvancedChannelInformation responseObject = restTemplate.getForObject(requestUrl, AdvancedChannelInformation.class); return responseObject.getSteamId(); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return null; }
/** * Create Feed Post * <p> * Requires the Twitch *channel_feed_edit* Scope. * * @param credential OAuth token for a Twitch user (that as 2fa enabled) * @param channelId Channel ID * @param message message to feed * @param share Share to Twitter if is connected */ public void createFeedPost(OAuthCredential credential, Long channelId, String message, Optional<Boolean> share) { // Endpoint String requestUrl = String.format("%s//feed/%s/posts", Endpoints.API.getURL(), channelId); RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential); // Parameters restTemplate.getInterceptors().add(new QueryRequestInterceptor("share", share.orElse(false).toString())); // Post Data MultiValueMap<String, Object> postBody = new LinkedMultiValueMap<String, Object>(); postBody.add("content", message); // REST Request try { restTemplate.postForObject(requestUrl, postBody, Void.class); } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } }
/** * Endpoint: Get Community by ID * Gets a specified community. * Requires Scope: none * * @param id The guid of the community. (e9f17055-810f-4736-ba40-fba4ac541caa) * @return The community. */ public Community getCommunityById(String id) { // Endpoint String requestUrl = String.format("%s/communities/%s", Endpoints.API.getURL(), id); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // REST Request try { Community responseObject = restTemplate.getForObject(requestUrl, Community.class); return responseObject; } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return null; }
/** * 查询配置 */ public Map<String, String> queryConfig() { try { String resultStr = HTTP_CLIENT.execute(request, new BasicResponseHandler()); FindPropertiesResult result = JSON.parseObject(resultStr, FindPropertiesResult.class); if (result == null) { throw new RuntimeException("请求配置中心失败"); } if (!result.isSuccess()) { throw new RuntimeException("从配置中心读取配置失败:" + result.getMessage()); } return result.getProperties(); } catch (IOException e) { return ExceptionUtils.rethrow(e); } }
@Override public void execute(ItemAmountUpdateCommandBuffer commandBuffer) { List<ItemAmountUpdateCommand> commands = commandBuffer.get(); if (CollectionUtils.isEmpty(commands)) { return; } List<Object[]> args = commands.stream().map(cmd -> new Object[] { cmd.getAmount(), cmd.getItemId() }) .collect(toList()); try { jdbcTemplate.batchUpdate(SQL, args); commands.forEach(command -> LOGGER.info("Executed", command)); } catch (Exception e) { commands.forEach(command -> LOGGER.error("Failed", command)); LOGGER.error(ExceptionUtils.getStackTrace(e)); } }
/** * Endpoint: Get Community by Name * Gets a specified community. * Requires Scope: none * * @param name The name of the community is specified in a required query-string parameter. It must be 3-25 characters. * @return todo */ public Community getCommunityByName(String name) { // Endpoint String requestUrl = String.format("%s/communities", Endpoints.API.getURL()); RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate(); // Parameter restTemplate.getInterceptors().add(new QueryRequestInterceptor("name", name)); // REST Request try { Community responseObject = restTemplate.getForObject(requestUrl, Community.class); return responseObject; } catch (RestException restException) { Logger.error(this, "RestException: " + restException.getRestError().toString()); } catch (Exception ex) { Logger.error(this, "Request failed: " + ex.getMessage()); Logger.trace(this, ExceptionUtils.getStackTrace(ex)); } return null; }
/** * Convert a JsonParseException into a user-friendly exception */ protected static SyntaxErrorException toSyntaxException(JsonParseException e) { Throwable throwable = ExceptionUtils.getRootCause(e); String s = ""; if (throwable != null) { s = throwable.getMessage(); if (s.contains("setLenient")) { s = s.substring(s.indexOf("to accept ") + 10); } } return new SyntaxErrorException("commands.tellraw.jsonException", new Object[] {s}); }
private void endTrace(Throwable throwable) { if (isTraceEnabled()) { Ending ending = new Ending(); if (throwable != null) { ending.addAnnotation("error", ExceptionUtils.getStackTrace(throwable)); } endTrace(ending); } }
public void endTrace(final int warningCount, final Throwable throwable) { if (isTraceEnabled()) { Ending ending = new Ending(); if (warningCount > 0) { ending.addAnnotation("warning.count", String.valueOf(warningCount)); } if (throwable != null) { ending.addAnnotation("error.message", ExceptionUtils.getStackTrace(throwable)); } endTrace(ending); } }
@Override public void onCommand(final MessageReceivedEvent e, final String[] args) { EEWBot.instance.getExecutor().execute(() -> { try { e.getChannel().sendFile("", new ByteArrayInputStream(MonitorDispatcher.get()), "kyoshinmonitor.png"); } catch (final Exception ex) { Log.logger.error(ExceptionUtils.getStackTrace(ex)); reply(e, ":warning: エラーが発生しました"); } }); }
public static String generateMultipleExceptionText(List<? extends Exception> exceptions) { String text = "\n"; for (Exception exception : exceptions) { String lines = ExceptionUtils.getStackTrace(exception); text += lines.replace("\n", "\n\t"); text += "\n\n"; } return text; }
public AbortDetails(Exception ex, String abortMessage, String utilityName) { if (ex == null) { throw new IllegalArgumentException("Exception object cannot be null"); } if (utilityName == null || utilityName.trim().equals("")) { throw new IllegalArgumentException("Utility name cannot be null"); } this.utilityName = utilityName; this.abortMessage = abortMessage; this.exceptionClass = ex.getClass().getSimpleName(); this.exceptionMessage = ex.getMessage(); this.exceptionStackTrace = ExceptionUtils.getStackTrace(ex); }
@Override public final boolean canRetry(RetryContext context) { Throwable rootException = ExceptionUtils.getRootCause(context.getThrowable()); if (rootException instanceof InterruptedException) { return false; } if ((rootException instanceof NullPointerException) || (rootException instanceof IllegalArgumentException)) { return context.getRetryCount() < 2; } return doCanRetry(context); }