I'm a beginner in Java coding.
Below is the code
public class AddJIRATicketWatcherCommandHandler {
private final JiraFactory jiraFactory;
public void handle(String jiraIssueKey, String watcher) {
log.debug("Adding {} watcher to JIRA issue: {}", watcher, jiraIssueKey);
final Issue issue = jiraFactory.createClient().getIssueClient().getIssue(jiraIssueKey).claim();
log.debug("Found JIRA issue: {}", issue.getKey());
Promise<Void> addWatcherPromise = jiraFactory.createClient().getIssueClient().addWatcher(issue.getWatchers().getSelf() , watcher);
addWatcherPromise.claim();
}}
public JiraRestClient createClient() {
log.debug("Creating JIRA rest client for remote environment");
URI jiraServerUri = URI.create("");
jiraServerUri = new URI(StringUtils.removeEnd(jiraConfig.getJiraURI(), "/rest"));
JiraRestClient restClient = new AsynchronousJiraRestClientFactory().createWithBasicHttpAuthentication(jiraServerUri,
jiraConfig.getJiraUsername(),
jiraConfig.getJiraPassword());
JIRA_LOGGER.info("url=[{}], username=[{}], password=[{}]", jiraServerUri.toString(), jiraConfig.getJiraUsername(), jiraConfig.getJiraPassword());
log.debug("JIRA rest client created successfully for remote environment");
return restClient;
}
However, when I ran the sonarqube. I received this error.
Use try-with-resources or close this "JiraRestClient" in a "finally" clause.
My understanding is to close the connection once done. But, I'm unsure on how to do that.
I tried to implement finally with close(). But the results is still showing the same error.
Try with resources:
public void handle(String jiraIssueKey, String watcher) {
try (JiraRestClient restClient = jiraFactory.createClient()) {
log.debug("Adding {} watcher to JIRA issue: {}", watcher, jiraIssueKey);
final Issue issue = restClient.getIssue(jiraIssueKey).claim();
log.debug("Found JIRA issue: {}", issue.getKey());
Promise<Void> addWatcherPromise = restClient.getIssueClient().addWatcher(issue.getWatchers().getSelf() , watcher);
addWatcherPromise.claim();
}
}
try finally:
public void handle(String jiraIssueKey, String watcher) {
JiraRestClient restClient = jiraFactory.createClient();
try {
log.debug("Adding {} watcher to JIRA issue: {}", watcher, jiraIssueKey);
final Issue issue = restClient.getIssue(jiraIssueKey).claim();
log.debug("Found JIRA issue: {}", issue.getKey());
Promise<Void> addWatcherPromise = restClient.getIssueClient().addWatcher(issue.getWatchers().getSelf() , watcher);
addWatcherPromise.claim();
} finally {
restClient.close();
}
}
Related
I'm trying to send push message using the emulator of pubsub, I'm using spring boot too, this is my configuration:
Dependency:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gcp-starter-pubsub</artifactId>
</dependency>
My bean:
#Configuration
#AutoConfigureBefore(value= GcpPubSubAutoConfiguration.class)
#EnableConfigurationProperties(value= GcpPubSubProperties.class)
public class EmulatorPubSubConfiguration {
#Value("${spring.gcp.pubsub.projectid}")
private String projectId;
#Value("${spring.gcp.pubsub.subscriptorid}")
private String subscriptorId;
#Value("${spring.gcp.pubsub.topicid}")
private String topicId;
#Bean
public Publisher pubsubEmulator() throws IOException {
String hostport = System.getenv("PUBSUB_EMULATOR_HOST");
ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext().build();
try {
TransportChannelProvider channelProvider =
FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
CredentialsProvider credentialsProvider = NoCredentialsProvider.create();
// Set the channel and credentials provider when creating a `TopicAdminClient`.
// Similarly for SubscriptionAdminClient
TopicAdminClient topicClient =
TopicAdminClient.create(
TopicAdminSettings.newBuilder()
.setTransportChannelProvider(channelProvider)
.setCredentialsProvider(credentialsProvider)
.build());
ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);
// Set the channel and credentials provider when creating a `Publisher`.
// Similarly for Subscriber
return Publisher.newBuilder(topicName)
.setChannelProvider(channelProvider)
.setCredentialsProvider(credentialsProvider)
.build();
} finally {
channel.shutdown();
}
}
}
Of course, I have set PUBSUB_EMULATOR_HOST system variable to localhost:8085, where is the emulator running
I created a rest controller for testing:
for send push message
#Autowired
private Publisher pubsubPublisher;
#PostMapping("/send1")
public String publishMessage(#RequestParam("message") String message) throws InterruptedException, IOException {
Publisher pubsubPublisher = this.getPublisher();
ByteString data = ByteString.copyFromUtf8(message);
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
ApiFuture<String> future = pubsubPublisher.publish(pubsubMessage);
//pubsubPublisher.publishAllOutstanding();
try {
// Add an asynchronous callback to handle success / failure
ApiFutures.addCallback(future,
new ApiFutureCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
if (throwable instanceof ApiException) {
ApiException apiException = ((ApiException) throwable);
// details on the API exception
System.out.println(apiException.getStatusCode().getCode());
System.out.println(apiException.isRetryable());
}
System.out.println("Error publishing message : " + message);
System.out.println("Error publishing error : " + throwable.getMessage());
System.out.println("Error publishing cause : " + throwable.getCause());
}
#Override
public void onSuccess(String messageId) {
// Once published, returns server-assigned message ids (unique within the topic)
System.out.println(messageId);
}
},
MoreExecutors.directExecutor());
}
finally {
if (pubsubPublisher != null) {
// When finished with the publisher, shutdown to free up resources.
pubsubPublisher.shutdown();
pubsubPublisher.awaitTermination(1, TimeUnit.MINUTES);
}
}
return "ok";
for get message:
#PostMapping("/pushtest")
public String pushTest(#RequestBody CloudPubSubPushMessage request) {
System.out.println( "------> message received: " + decode(request.getMessage().getData()) );
return request.toString();
}
I have created my topic and subscription in the emulator, I followed this tutorial:
https://cloud.google.com/pubsub/docs/emulator
I'm set the endpoint "pushtest" for get push message in the emulator, with this command:
python subscriber.py PUBSUB_PROJECT_ID create-push TOPIC_ID SUBSCRIPTION_ID PUSH_ENDPOINT
But when I run the test, doesn't reach "/pushtest" endpoint and I'm getting this error:
Task java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask#265d5d05
[Not completed, task = java.util.concurrent.Executors$RunnableAdapter#a8c8be3
[Wrapped task = com.google.common.util.concurrent.TrustedListenableFutureTask#1a53c57c
[status=PENDING, info=[task=[running=[NOT STARTED YET], com.google.api.gax.rpc.AttemptCallable#3866e1d0]]]]]
rejected from java.util.concurrent.ScheduledThreadPoolExecutor#3f34809a
[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1]
for assurance that the emulator is running ok, I'm run the test in python with the following command:
python publisher.py PUBSUB_PROJECT_ID publish TOPIC_ID
And I'm getting messages correctly in "pushtest" endpoint.
I don't know why sorry for my hazing.
Thanks for your help.
I found the problem.
Only comment this line in the bean
channel.shutdown();
HAHA very simple.
My Unit Test project is running into an error when configured with Jenkins. The Tests run fine when I run the maven test locally from Command prompt.
Error I get :
feature ("Verify GET User Details API")
cucumber.runtime.CucumberException: java.lang.IllegalStateException: Failed to create cache dir
at cucumber.api.testng.TestNGCucumberRunner.runCucumber(TestNGCucumberRunner.java:78)
at com.ibm.wce.scbn.cc.runner.BaseRunner.feature(BaseRunner.java:32)
Caused by: java.lang.IllegalStateException: Failed to create cache dir
at io.vertx.core.file.impl.FileResolver.setupCacheDir(FileResolver.java:332)
at io.vertx.core.file.impl.FileResolver.<init>(FileResolver.java:87)
at io.vertx.core.impl.VertxImpl.<init>(VertxImpl.java:165)
at io.vertx.core.impl.VertxImpl.vertx(VertxImpl.java:92)
at io.vertx.core.impl.VertxFactoryImpl.vertx(VertxFactoryImpl.java:40)
at io.vertx.core.impl.VertxFactoryImpl.vertx(VertxFactoryImpl.java:32)
at io.vertx.core.impl.VertxFactoryImpl.vertx(VertxFactoryImpl.java:27)
at io.vertx.core.Vertx.vertx(Vertx.java:75)
at com.ibm.wce.scbn.cc.util.TokenUtil.<init>(TokenUtil.java:32)
at com.ibm.wce.scbn.cc.util.TokenUtil.getInstance(TokenUtil.java:46)
at com.ibm.wce.scbn.cc.stepdefinitions.AccountsByID.we_send_Get_request_to_service_for_Account_with_source_and_iui(AccountsByID.java:369)
at ✽.We send Get request to service for Account "1" with source "1" and iui "1"(./features/AccountsByID/AccountsByID.feature:7)
TokenUtil.java
public class TokenUtil {
private static final Logger LOGGER = Logger.getLogger(TokenUtil.class.getName());
private static TokenUtil TOKEN_INSTANCE = null;
private static Vertx VERTX = null;
private static JWTAuthOptions JWTAUTHOPS = new JWTAuthOptions();
private TokenUtil() throws Exception {
try {
VERTX = Vertx.vertx();
JsonObject objJason = new JsonObject(VERTX.fileSystem().readFileBlocking(System.getProperty("privatejwtpath")));
JWTAUTHOPS.addJwk(objJason);
} catch (Exception e) {
LOGGER.error("Unable to load private JWK json file", e);
throw e;
}
}
public static TokenUtil getInstance() throws Exception {
if (TOKEN_INSTANCE == null) {
synchronized (TokenUtil.class) {
TOKEN_INSTANCE = new TokenUtil();
}
}
return TOKEN_INSTANCE;
}
public String getJWT(String iui) {
JWTOptions jwtOptions = new JWTOptions();
JsonObject payLoad = new JsonObject();
jwtOptions.setAlgorithm("RS256");
jwtOptions.setExpiresInSeconds(300);
JWTAuth jwt = JWTAuth.create(VERTX, JWTAUTHOPS);
payLoad.put("ibm", new JsonObject().put("iui", iui));
return jwt.generateToken(payLoad, jwtOptions);
}
}
Any suggestions on how to fix this is highly appreciated. Thank you
Issue fixed by disabling Cache
Does anyone have an idea why is being thrown listed exception after invoking /user URL? It quite strange because all works as is expected (upstream service handles a response from downstream and sends to a response to a client). Using Ratpack 1.4.1. Full code is available: https://github.com/peterjurkovic/ratpack-demo
Edit:
I've just tried downgrade to version 1.3.3 and with this version of Ratpack it is not happening. Github issue created.
Edit 2:
The issue should be resolved in the next version 1.4.2.
public class DownstreamUserService {
Logger log = LoggerFactory.getLogger(DownstreamUserService.class);
private HttpClient httpClient;
private ObjectMapper mapper;
private URI downstreamServerUri;
#Inject
public DownstreamUserService(HttpClient httpClient, Config config, ObjectMapper mapper) {
this.httpClient = httpClient;
this.mapper = mapper;
try {
downstreamServerUri = new URI("http://" + config.getHost() + ":" + config.getPort() + "/endpoint");
} catch (URISyntaxException e) {
log.error("",e);
throw new RuntimeException(e);
}
}
public Promise<User> load(){
return httpClient.get( downstreamServerUri )
.onError(e -> log.info("Error",e))
.map( res -> mapper.readValue(res.getBody().getBytes(), User.class));
}
}
Server
public class App {
static Logger log = LoggerFactory.getLogger(App.class);
public static void main(String[] args) throws Exception {
RatpackServer.start(s -> s
// bindings..
.handlers( chain -> chain
.get("user", c -> {
DownstreamUserService service = c.get(DownstreamUserService.class);
service.load().then( user -> c.render( json(user) ));
})
}
}
Stacktrace:
[2016-08-28 22:58:24,979] WARN [ratpack-compute-1-2] i.n.c.DefaultChannelPipeline - An exceptionCaught() event was fired, and it reached at the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception.
io.netty.handler.codec.PrematureChannelClosureException: channel gone inactive with 1 missing response(s)
at io.netty.handler.codec.http.HttpClientCodec$Decoder.channelInactive(HttpClientCodec.java:261)
at io.netty.channel.CombinedChannelDuplexHandler.channelInactive(CombinedChannelDuplexHandler.java:220)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:255)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:241)
at io.netty.channel.AbstractChannelHandlerContext.fireChannelInactive(AbstractChannelHandlerContext.java:234)
at io.netty.channel.DefaultChannelPipeline$HeadContext.channelInactive(DefaultChannelPipeline.java:1329)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:255)
at io.netty.channel.AbstractChannelHandlerContext.invokeChannelInactive(AbstractChannelHandlerContext.java:241)
at io.netty.channel.DefaultChannelPipeline.fireChannelInactive(DefaultChannelPipeline.java:908)
at io.netty.channel.AbstractChannel$AbstractUnsafe$7.run(AbstractChannel.java:744)
at io.netty.util.concurrent.SingleThreadEventExecutor.safeExecute(SingleThreadEventExecutor.java:451)
at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:418)
at io.netty.channel.epoll.EpollEventLoop.run(EpollEventLoop.java:306)
at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:877)
at ratpack.exec.internal.DefaultExecController$ExecControllerBindingThreadFactory.lambda$newThread$0(DefaultExecController.java:136)
at ratpack.exec.internal.DefaultExecController$ExecControllerBindingThreadFactory$$Lambda$129/1240843015.run(Unknown Source)
at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
at java.lang.Thread.run(Thread.java:745)
hi im creating a simple tool using java to create,update and delete issues(tickets) in jira. i am using rest api following code is im using to authenticate jira and issue tickets.
public class JiraConnection {
public static URI jiraServerUri = URI.create("http://localhost:8090/jira/rest/api/2/issue/HSP-1/");
public static void main(String args[]) throws IOException {
final AsynchronousJiraRestClientFactory factory = new AsynchronousJiraRestClientFactory();
final JiraRestClient restClient = factory.createWithBasicHttpAuthentication(jiraServerUri,"vinuvish92#gmail.com","vinu1994");
System.out.println("Sending issue creation requests...");
try {
final List<Promise<BasicIssue>> promises = Lists.newArrayList();
final IssueRestClient issueClient = restClient.getIssueClient();
System.out.println("Sending issue creation requests...");
for (int i = 0; i < 100; i++) {
final String summary = "NewIssue#" + i;
final IssueInput newIssue = new IssueInputBuilder("TST", 1L, summary).build();
System.out.println("\tCreating: " + summary);
promises.add(issueClient.createIssue(newIssue));
}
System.out.println("Collecting responses...");
final Iterable<BasicIssue> createdIssues = transform(promises, new Function<Promise<BasicIssue>, BasicIssue>() {
#Override
public BasicIssue apply(Promise<BasicIssue> promise) {
return promise.claim();
}
});
System.out.println("Created issues:\n" + Joiner.on("\n").join(createdIssues));
} finally {
restClient.close();
}
}
}
according this code i couldn't connect to the jira
**following exception i am getting **
please suggest me best solution to do my task
It seems to me that your error is clearly related to url parameter. The incriminated line and the fact that the error message is about not finding the resource are good indications of it.
You don't need to input the whole endpoint since you are using the JiraRestClient. Depending on the method that you call it will resolve the endpoint. Here is an example that works: as you can see I only input the base url
I'm attempting to perform a synchronous write/read in a demux-based client application with MINA 2.0 RC1, but it seems to get stuck. Here is my code:
public boolean login(final String username, final String password) {
// block inbound messages
session.getConfig().setUseReadOperation(true);
// send the login request
final LoginRequest loginRequest = new LoginRequest(username, password);
final WriteFuture writeFuture = session.write(loginRequest);
writeFuture.awaitUninterruptibly();
if (writeFuture.getException() != null) {
session.getConfig().setUseReadOperation(false);
return false;
}
// retrieve the login response
final ReadFuture readFuture = session.read();
readFuture.awaitUninterruptibly();
if (readFuture.getException() != null) {
session.getConfig().setUseReadOperation(false);
return false;
}
// stop blocking inbound messages
session.getConfig().setUseReadOperation(false);
// determine if the login info provided was valid
final LoginResponse loginResponse = (LoginResponse)readFuture.getMessage();
return loginResponse.getSuccess();
}
I can see on the server side that the LoginRequest object is retrieved, and a LoginResponse message is sent. On the client side, the DemuxingProtocolCodecFactory receives the response, but after throwing in some logging, I can see that the client gets stuck on the call to readFuture.awaitUninterruptibly().
I can't for the life of me figure out why it is stuck here based upon my own code. I properly set the read operation to true on the session config, meaning that messages should be blocked. However, it seems as if the message no longer exists by time I try to read response messages synchronously.
Any clues as to why this won't work for me?
The reason this wasn't working for me was because of an issue elsewhere in my code where I stupidly neglected to implement the message response encoder/decoder. Ugh. Anyway, the code in my question worked as soon as I fixed that.
I prefer this one (Christian Mueller : http://apache-mina.10907.n7.nabble.com/Mina-Client-which-sends-receives-messages-synchronous-td35672.html)
public class UCPClient {
private Map<Integer, BlockingQueue<UCPMessageResponse>> concurrentMap = new ConcurrentHashMap<Integer, BlockingQueue<UCPMessageResponse>>();
// some other code
public UCPMessageResponse send(UCPMessageRequest request) throws Throwable {
BlockingQueue<UCPMessageResponse> queue = new LinkedBlockingQueue<UCPMessageResponse>(1);
UCPMessageResponse res = null;
try {
if (sendSync) {
concurrentMap.put(Integer.valueOf(request.getTransactionReference()), queue);
}
WriteFuture writeFuture = session.write(request);
if (sendSync) {
boolean isSent = writeFuture.await(transactionTimeout, TimeUnit.MILLISECONDS);
if (!isSent) {
throw new TimeoutException("Could not sent the request in " + transactionTimeout + " milliseconds.");
}
if (writeFuture.getException() != null) {
throw writeFuture.getException();
}
res = queue.poll(transactionTimeout, TimeUnit.MILLISECONDS);
if (res == null) {
throw new TimeoutException("Could not receive the response in " + transactionTimeout + " milliseconds.");
}
}
} finally {
if (sendSync) {
concurrentMap.remove(Integer.valueOf(request.getTransactionReference()));
}
}
return res;
}
}
and the IoHandler:
public class InnerHandler implements IoHandler {
// some other code
public void messageReceived(IoSession session, Object message) throws Exception {
if (sendSync) {
UCPMessageResponse res = (UCPMessageResponse) message;
BlockingQueue<UCPMessageResponse> queue = concurrentMap.get(res.getTransactionReference());
queue.offer(res);
}
}
}
I had this exact problem. It turns out that it's because I was doing reads/writes in my IoHandler.sessionCreated() implementation. I moved the processing onto the thread that established the connection, instead of just waiting for the close future.
You must not use your login() function in IoHandler Thread :
If you call IoFuture.awaitUninterruptibly() in the override event function of IoHandler,
IoHandler don't work and get stuck.
You can call login() in other Thread and it will be work properly.