8 Replies Latest reply on Jun 6, 2017 2:10 AM by Nidheesh Ep

    Example Java code to call Jive REST V3 API using OAuth2

    ravishankar_d

      Hi,

       

      Please share Java code example to call a Jive v3 REST API using OAuth2 authentication(instead of basic authentication)

       

      Regards,

      Ravi

        • Re: Example Java code to call Jive REST V3 API using OAuth2
           public String getRequestAbsolute(String path) throws NotFoundException, IOException  {
            CloseableHttpClient client = HttpClientBuilder.create().build();
            CloseableHttpResponse response = null;
            try {
             // String jiveUrl = store.getString("JiveConnector.jiveserver");
              String access_token = store.getString("access_token");
              String clientid = COMMUNITY_CLIENT_ID;
              String proxyUrl = store.getString("JiveConnector.proxyserver");
              int proxyPort = store.getInt("JiveConnector.proxyport");
              Boolean proxyEnabled = store.getBoolean("JiveConnector.proxyenabled");
              
             
             
             HttpGet httpget = new HttpGet( path);
             
             
             //Set up proxy if required
             if (proxyEnabled==true){
              
              HttpHost proxyServer = new HttpHost(proxyUrl, proxyPort);
                RequestConfig config = RequestConfig.custom()
                                .setProxy(proxyServer)
                                .build();
                httpget.setConfig(config);
              
             }
             
             
             httpget.setHeader("Authorization", "Bearer " + access_token);
             
             
              response = client.execute(httpget);
            
             System.out.println("Response Code : " 
                            + response.getStatusLine().getStatusCode());
             
             
             if (response.getStatusLine().getStatusCode()==404){
              
             
              throw new NotFoundException();
              
             }
             
             if (response.getStatusLine().getStatusCode()==401){
              
              System.out.println("we need to refresh");
              boolean tokenUpdated = this.refreshToken();
              if (tokenUpdated==true){
                
                 access_token = store.getString("access_token");
               
                client = HttpClientBuilder.create().build();
               
                httpget = new HttpGet(path);
                //Set up proxy if required
                if (proxyEnabled==true){
                 
                 HttpHost proxyServer = new HttpHost(proxyUrl, proxyPort);
                   RequestConfig config = RequestConfig.custom()
                                   .setProxy(proxyServer)
                                   .build();
                   httpget.setConfig(config);
                 
                }
                
               httpget.setHeader("Authorization", "Bearer " + access_token);
               
               
                response = client.execute(httpget);
              
               System.out.println("Response Code : " 
                              + response.getStatusLine().getStatusCode());
                  HttpEntity entity = response.getEntity();
                  if (entity != null) {
                      
                       String tokenResponse = EntityUtils.toString(entity);
                       tokenResponse = tokenResponse.replace("throw 'allowIllegalResourceCall is false.';", "");
                     return tokenResponse;
                  }
              }
              else {
               System.out.println("Error getting refresh token");
              }
              
              
             }
             else {
              
              
            
                 HttpEntity entity = response.getEntity();
                 if (entity != null) {
                     
                      String tokenResponse = EntityUtils.toString(entity);
                      tokenResponse = tokenResponse.replace("throw 'allowIllegalResourceCall is false.';", "");
                    return tokenResponse;
                 }       
                 }  
                
              } catch (ClientProtocolException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
              } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
              }
            catch (NotFoundException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
             System.out.println("Object not in Jive");
            return null;
           }
            catch (Exception e){
             e.printStackTrace();
            }
            finally {
             response.close();
            }
            return null;
            
            
           }
            public boolean refreshToken () {
              
              try {
              String jiveUrl = store.getString("JiveConnector.jiveserver");
              String proxyUrl = store.getString("JiveConnector.proxyserver");
              int proxyPort = store.getInt("JiveConnector.proxyport");
              Boolean proxyEnabled = store.getBoolean("JiveConnector.proxyenabled");
              String refresh_token = store.getString("refresh_token");
              String clientid =  COMMUNITY_CLIENT_ID;
              String clientsecret =  COMMUNITY_CLIENT_SECRET;
               URI jiveUri = new URI(jiveUrl);
                  
               
                  
                String url = jiveUrl +"/oauth2/token";
                
                CloseableHttpClient  client = HttpClientBuilder.create().build();
                HttpPost post = new HttpPost(url);
               
                //Set up proxy if required
                if (proxyEnabled==true){
                  
                  HttpHost proxyServer = new HttpHost(proxyUrl, proxyPort);
                    RequestConfig config = RequestConfig.custom()
                                  .setProxy(proxyServer)
                                  .build();
                    post.setConfig(config);
                  
                }
                // add header
                post.setHeader("User-Agent", "AgentOfAwesome");
               
                UsernamePasswordCredentials creds = new UsernamePasswordCredentials(clientid, clientsecret);
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(
                    new AuthScope(jiveUri.getHost() , AuthScope.ANY_PORT), 
                    creds);
                
                HttpHost targetHost = new HttpHost(jiveUri.getHost(), jiveUri.getPort(), jiveUri.getScheme());
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                // Generate BASIC scheme object and add it to the local auth cache
                BasicScheme basicAuth = new BasicScheme();
                authCache.put(targetHost, basicAuth);
          
          
                // Add AuthCache to the execution context
                HttpClientContext context = HttpClientContext.create();
                context.setCredentialsProvider(credsProvider);
                context.setAuthCache(authCache);
                
                
                
                List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
                urlParameters.add(new BasicNameValuePair("refresh_token", refresh_token));
                urlParameters.add(new BasicNameValuePair("grant_type", "refresh_token"));
               
                
                  post.setEntity(new UrlEncodedFormEntity(urlParameters));
                
               
                  CloseableHttpResponse response = client.execute(post,context);
                System.out.println("Response Code : " 
                              + response.getStatusLine().getStatusCode());
                
                
                try {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        
                          String tokenResponse = EntityUtils.toString(entity);
                            
                            ObjectMapper mapper = new ObjectMapper();
                            OAuthBearerToken myToken = mapper.readValue(tokenResponse, OAuthBearerToken.class);
                            store.setValue("access_token", myToken.access_token);
                            store.setValue("refresh_token",myToken.refresh_token);
                            return true;
                            
                    }
                    else {
                      return false;
                    }
                } finally {
                  
                  response.close();
                  
                  
                }
              } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              } catch (URISyntaxException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
              }
              return false;
            }
          

           

          Using Apache HttpClient and Jackson