Tuesday, March 14, 2023

Oracle Cloud Infrastructure- Object storage example

This post will explain, how we can create bucket and configure notification and rules and object storage like create/update object. Login into OCI using login credentials . if you don't have a account please create the same using this link https://www.oracle.com/cloud/sign-in.html Once you create account and successful login, Now we need to create a bucket. search for bucket and create a bucket
After creating bucket now we can create a topic
Now we can create notification, after uploading file , we should get email
Create a Rule to process this
Once we create all then , once we upload file in object storage , then we should get email like below
This shows we can send email, but we can configure with different ways like queues. Here we will get the details in mail . But if we want complete object details, then we can use java code to retrieve the object details by calling the API which required namespace details ,bucket name and object name.
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Paths;
import java.util.List;

import com.oracle.bmc.objectstorage.ObjectStorage;
import com.oracle.bmc.objectstorage.ObjectStorageClient;
import com.oracle.bmc.objectstorage.model.GetObjectRequest;
import com.oracle.bmc.objectstorage.model.ObjectStream;
import com.oracle.bmc.objectstorage.model.Range;
import com.oracle.bmc.objectstorage.requests.GetObjectRequest;
import com.oracle.bmc.objectstorage.responses.GetObjectResponse;

public class LogFileRetriever {
    public static void main(String[] args) {
        String namespaceName = "mynamespace";
        String bucketName = "mybucket";
        String objectName = "mylogfile.txt";

        // Create a new Object Storage client
        ObjectStorage objectStorageClient = ObjectStorageClient.builder()
                .build(objectStorageConfig);

        GetObjectRequest request = GetObjectRequest.builder()
                .namespaceName(namespaceName)
                .bucketName(bucketName)
                .objectName(objectName)
                .build();

        GetObjectResponse response = objectStorageClient.getObject(request);

        // Get the InputStream from the response
        InputStream logFileInputStream = response.getInputStream();

        // Write the InputStream to a local file
        OutputStream logFileOutputStream = 
            new FileOutputStream(Paths.get("logfile.txt").toFile());
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = logFileInputStream.read(buffer)) != -1) {
            logFileOutputStream.write(buffer, 0, bytesRead);
        }
        logFileOutputStream.close();
    }
}

Monday, March 14, 2022

How to call REST API Using Spring Webflux WebClient set proxy with authorization while calling the external site and Generate base 64 authentication header spring boot

This post will explain us, how can we call REST API using Webclient. How to set Proxy username and password to call the external site. Step 1: Add folllowing dependency in your pom.xml
   
	 org.springframework.boot
	 spring-boot-starter-webflux
	
Step 2:
import lombok.extern.slf4j.XSlf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.reactive.ClientHttpConnector;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.netty.http.client.HttpClient;
import reactor.netty.transport.ProxyProvider;

import java.net.URI;
import java.util.Base64;
import java.util.function.Consumer;
import java.util.function.Function;
 public static void main(String[] args) {
  try {
  //Generate HttP client to set proxy details
  HttpClient httpClient = HttpClient.create()
            .proxy(proxy-> proxy.type(ProxyProvider.Proxy.HTTP)
            .host("javaguruonline.com").port(1328)
            .username("siva")
            .password(new Function() {
                        @Override
                        public String apply(String s) {
                            return "test@12!";
                        }
                    }));
  ClientHttpConnector clientHttpConnector = 
           new ReactorClientHttpConnector(httpClient);
  WebClient webClient = WebClient.builder().build();
  String plainCredentials = "username" + ":" + "password";
  String base64Credentials = new String(Base64.getEncoder()
                           .encode(plainCredentials.getBytes()));
  String authorizationHeader = "Basic " + base64Credentials;
  //input json
  String json = "{\n" +
                    "  \"user\": \"siva\"\n" +
                    "}";
            //set http headers
  Consumer httpHeaders = new Consumer() {
     @Override
     public void accept(HttpHeaders httpHeaders) {
       httpHeaders.add("Authorization", authorizationHeader);
       httpHeaders.add("Content-Type", "application/json");
       httpHeaders.add("Proxy-Authorization", authorizationHeader);
     }};
   //post call to external URL and get ResponseEntity as response like body 
   //and http status code etc..
    ResponseEntity result = webClient.mutate()
                    .clientConnector(clientHttpConnector)
                    .build()
                    .post()
                    .uri(new URI("https://localhost:8080/test/details"))
                    .bodyValue(json)
                    .accept(MediaType.APPLICATION_JSON)
                    .retrieve()
                    .toEntity(String.class)
                    .block();
            System.out.println(result);
        }
        catch(Exception ex){
        }
Hope this post will help some one, while working on the REST API calls

Thursday, March 11, 2021

How to mock ResultSet , NamedParameterJdbcTemplate , RowMapper

package com.siva.springboot.javaguruonline.repository;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import com.siva.springboot.javaguruonline.model.EmployeeDetails;
@RunWith(SpringRunner.class)
/**
 * 
 * @author Siva
 *
 */
//@SpringBootTest(classes = SpringbootJpaSwaggerSonarqubeApplication.class)
public class EmployeeDaoImplTest {
	
	@InjectMocks
	public EmployeeDaoImpl employeeDao;
	
	@Mock
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
	
	@SuppressWarnings("unchecked")
	@Test
	public void testGetAllEmployeeDetails(){
		List list = new ArrayList();
		EmployeeDetails employeeDetails = new EmployeeDetails();
		employeeDetails.setEmpId(1);
		employeeDetails.setEmpName("siva");
		list.add(employeeDetails);
		Mockito.when(namedParameterJdbcTemplate.query(Mockito.anyString(),
        Mockito.any(RowMapper.class)))
	    .thenAnswer(new Answer>() {
		
	        @Override
	public List answer(InvocationOnMock invocation) 
                                          throws Throwable {
	            // Fetch the method arguments
	          Object[] args = invocation.getArguments();
	          

	            // Fetch the row mapper instance from the arguments
	          RowMapper rm = (RowMapper) args[1];

	          // Create a mock result set and setup an expectation on it
	          ResultSet rs = Mockito.mock(ResultSet.class);
	          Mockito.when(rs.getInt("emp_id")).thenReturn(employeeDetails.getEmpId());
	            
	          Mockito.when(rs.getString("emp_name")).thenReturn(employeeDetails.getEmpName());
               
	            // Invoke the row mapper
	          EmployeeDetails actual = rm.mapRow(rs, 0);
	            // Assert the result of the row mapper execution
	          Assert.assertEquals(employeeDetails.getEmpName(), actual.getEmpName());

	            // Return your created list for the template#query call
	            return list;
	        }
	    });
		
		
		
		
		 employeeDao.getEmployeeDetails();
		Assert.assertNotNull(list);
	}

}

Thursday, August 27, 2020

Getting started with Chatbot using java and response in text to speech -- Java simple chatbot and text to speech

This will explain you about , how we can write simple chatbot using java and read the bot response into speech 

 Step 1: Download sample program-ab from the below archive folder Program-ab 

 Step 2: Unzip the downloaded folder. 

 Step 3: Create java maven project using any IDE or console application

 Step 4: Copy Ab.jar (Which is there in the unzipped folder lib in step 2) add to the classpath 

 Step 5: Copy bots folder (which is available in the unzipped folder) it has all the aiml files, which bot act upon our request and give the response

 Step 6: Now we need to give bot response in speech

 Step 7: Download freetss from the given link FREETTS 

 Step 8: Unzip the downloaded folder and go to \freetts-1.2.2-bin\freetts-1.2\lib folder 

 Step 9: Run the jsapi.exe file- It will generate multiple jars

 Step 10: copy that jars and place it in the classpath of the java project 

 Step 11: Once above steps completed then, we can write simple java program as follows
package com.siva;

import java.io.File;
import java.util.Locale;
import java.util.Scanner;

import javax.speech.Central;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;

import org.alicebot.ab.AB;
import org.alicebot.ab.Bot;
import org.alicebot.ab.Chat;
import org.alicebot.ab.MagicBooleans;
import org.alicebot.ab.utils.IOUtils;

public class TestChatbot {

    private static final boolean TRACE_MODE = false;
    static String botName = "super";
 
    public static void main(String[] args) {
        try {
 
            String aimlResourcesPath = getResourcesPath();
            System.out.println(aimlResourcesPath);
            MagicBooleans.trace_mode = TRACE_MODE;
            Bot bot = new Bot("super", aimlResourcesPath);
            Chat chatSession = new Chat(bot);
	        AB.ab(bot);
	        Scanner sc=new Scanner(System.in);

	        String request = "Hai";
	        do{

	        request = IOUtils.readInputTextLine();
	        String response = chatSession.multisentenceRespond(request); 
	        
	        
	        
	            // Set property as Kevin Dictionary 
	            System.setProperty( 
	                "freetts.voices", 
	                "com.sun.speech.freetts.en.us"
	                    + ".cmu_us_kal.KevinVoiceDirectory"); 
	  
	            // Register Engine 
	            Central.registerEngineCentral( 
	                "com.sun.speech.freetts"
	                + ".jsapi.FreeTTSEngineCentral"); 
	  
	            // Create a Synthesizer 
	            Synthesizer synthesizer 
	                = Central.createSynthesizer( 
	                    new SynthesizerModeDesc(Locale.US)); 
	  
	            // Allocate synthesizer 
	            synthesizer.allocate(); 
	  
	            // Resume Synthesizer 
	            synthesizer.resume(); 
	  
	            // Speaks the given text 
	            // until the queue is empty. 
	            synthesizer.speakPlainText( 
	            		response, null); 
	            synthesizer.waitEngineState( 
	                Synthesizer.QUEUE_EMPTY); 
	  
	        System.out.println(response); 
	        }while(!request.equals("exit"));

 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    private static String getResourcesPath() {
        File currDir = new File(".");
        String path = currDir.getAbsolutePath();
        path = path.substring(0, path.length() - 2);
        System.out.println(path);
        String resourcesPath = path + File.separator + "src" 
        + File.separator + "main" + File.separator + "resources";
        return resourcesPath;
    }
}


Step 12: Once code completed , then run the java program , type the input like Hai, hello and date, there are so many QA mentioned in imal files. and we can also write our own aiml file, for reference, you can verify under boats/aiml folder 

Step 13: output will print in console and it will read the boat response.. 

 Step 14: Out put will be like below image. 


 Thanks for viewing this post.

AddToAny

Contact Form

Name

Email *

Message *