Can I return BufferedImage as html response? - java

I have the following implementation to create QR Code and try to return generated code as html response (ask user to open or save the generated image) instead of saving to file in a directory. However, I could not manage to perform that. I use the following example on Baeldung: https://www.baeldung.com/java-generating-barcodes-qr-codes
public static BufferedImage generateQRCodeImage(String barcodeText) throws Exception {
QRCodeWriter barcodeWriter = new QRCodeWriter();
BitMatrix bitMatrix =
barcodeWriter.encode(barcodeText, BarcodeFormat.QR_CODE, 200, 200);
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
I use the following REST Controller method:
#RestController
#RequestMapping("/barcodes")
public class BarcodesController {
#GetMapping(value = "/barbecue/ean13/{barcode}", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> barbecueEAN13Barcode(#PathVariable("barcode") String barcode)
throws Exception {
return okResponse(BarbecueBarcodeGenerator.generateEAN13BarcodeImage(barcode));
}
//...
}
However, I cannot get the image as HTTP response. So, how can I fix it?
Update: Here is my Application.java:
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args)
}
#Bean
public HttpMessageConverter<BufferedImage> createImageHttpMessageConverter() {
return new BufferedImageHttpMessageConverter();
}
}
Is that enough? Or should I call it from anywhere?

Related

How to Validate ui data with rest api responses

I need to validate my ui data and api responses are same,
here is my code I tried,
private ValidateContentPage cp = new ValidateContentPage();
public void getTitle() {
String UITitle = driver.findElement(titlepage).getText();
System.out.println(UITitle);
Assert.assertEquals(UITitle, cp.getAPICall(),"Passed");
}
here im getting my api responses,
public class ValidateContentPage {
public common cm = new common();
public Properties prop;
public void baseURI() {
prop = cm.getProperties("./src/test/API/IndiaOne/propertyfile/EndpointURL.properties");
RestAssured.baseURI = prop.getProperty("baseURI");
}
public String getAPICall() {
objectpojo ps = given().expect().defaultParser(Parser.JSON).when().get(prop.getProperty("resources")).as(objectpojo.class, cm.getMapper());
int number = ps.getPosts().size();
System.out.println(number);
System.out.println(ps.getPosts().get(0).getTitle());
return ps.getPosts().get(0).getTitle();
}
If i validate both using testng assertion it throwing null pointer exception, anyone help me on how to validate my ui data and api responses.
You need to call your ValidateContentPage from #Test itself or from #BeforeTest
#Test
public void getTitle() {
String UITitle = driver.findElement(titlepage).getText();
System.out.println(UITitle);
ValidateContentPage cp = new ValidateContentPage();
Assert.assertEquals(UITitle, cp.getAPICall(),"Passed");
}

Can i send information to testrail for selenium when my test runs its course

I am trying to send my tests to testrail from selenium but im not using an assert to end the test, i just want it to pass if it runs to completion? Is this possible? Also is there any examples of how this working in the code? I currently have:
public class login_errors extends ConditionsWebDriverFactory {
public static String TEST_RUN_ID = "R1713";
public static String TESTRAIL_USERNAME = "f2009#hotmail.com";
public static String TESTRAIL_PASSWORD = "Password100";
public static String RAILS_ENGINE_URL = "https://testdec.testrail.com/";
public static final int TEST_CASE_PASSED_STATUS = 1;
public static final int TEST_CASE_FAILED_STATUS = 5;
#Test
public void login_errors() throws IOException, APIException {
Header header = new Header();
header.guest_select_login();
Pages.Login login = new Pages.Login();
login.login_with_empty_fields();
login.login_with_invalid_email();
login.email_or_password_incorrect();
login.login_open_and_close();
login_errors.addResultForTestCase("T65013",TEST_CASE_PASSED_STATUS," ");
}
public static void addResultForTestCase(String testCaseId, int status,
String error) throws IOException, APIException {
String testRunId = TEST_RUN_ID;
APIClient client = new APIClient(RAILS_ENGINE_URL);
client.setUser(TESTRAIL_USERNAME);
client.setPassword(TESTRAIL_PASSWORD);
Map data = new HashMap();
data.put("status_id", status);
data.put("comment", "Test Executed - Status updated automatically from Selenium test automation.");
client.sendPost("add_result_for_case/"+testRunId+"/"+testCaseId+"",data );
}
}
I am getting a 401 status from this code.
Simply place the addResultForTestCase method at the end of the run. Ensure the Test CASE is used rather than the run id. You are currently using the incorrect ID

Wanted but not invoke: Mockito PrintWriter

Hi I am working on a project and using PrintWriter class for opening and writing in the file. But when I am writing the test case for same it gives following error at Line 153
Wanted but not invoked:
mockPrintWriter.println("ID url1
");
-> at x.y.z.verify(ProcessImageDataTest.java:153)
Actually, there were zero interactions with this mock.
Code: (Uses Lombok Library)
ProcessImageData.java
#Setter
#RequiredArgsConstructor
public class ProcessImageData implements T {
private final File newImageDataTextFile;
#Override
public void execute() {
LineIterator inputFileIterator = null;
try {
File filteredImageDataTextFile = new File(filteredImageDataTextFilepath);
PrintWriter writer = new PrintWriter(newImageDataTextFile);
inputFileIterator = FileUtils.lineIterator(filteredImageDataTextFile, StandardCharsets.UTF_8.displayName());
while (inputFileIterator.hasNext()) {
if(someCondition)
**Line51** writer.println(imageDataFileLine);
//FileUtils.writeStringToFile(newImageDataTextFile, imageDataFileLine + NEWLINE, true);
}
}
} catch (Exception e) {
} finally {
LineIterator.closeQuietly(inputFileIterator);
**LINE63** writer.close();
}
}
ProcessImageDataTest.java
#RunWith(PowerMockRunner.class)
#PrepareForTest({ ProcessImageData.class, FileUtils.class, Printwriter.class })
public class ProcessImageDataTest {
private ProcessImageData processImageData;
private static final String FILTERED_IMAGE_DATA_TEXT_FILE_PATH = "filteredFilepath";
private File FILTEREDFILE = new File(FILTERED_PATH);
private static final File IMAGE__FILE = new File("imageFilePath");
private LineIterator lineIterator;
#Mock
private PrintWriter mockPrintWriter;
#Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
processImageData = new ProcessImageData(Palettes_file, FILTERED_PATH, IMAGE_FILE);
PowerMockito.mockStatic(FileUtils.class);
PowerMockito.whenNew(PrintWriter.class).withArguments(IMAGE_FILE).thenReturn(mockPrintWriter);
PowerMockito.when(FileUtils.lineIterator(FILTERED_FILE, StandardCharsets.UTF_8.displayName())).thenReturn(lineIterator);
PowerMockito.when(lineIterator.hasNext()).thenReturn(true, true, false);
}
#Test
public void testTaskWhenIDInDBAndStale() throws IOException {
PowerMockito.when(lineIterator.nextLine()).thenReturn(ID2 + SPACE + URL1, ID1 + SPACE + URL2);
processImageData.execute();
List<String> exepctedFileContentOutput = Arrays.asList(ID2 + SPACE + URL1 + NEWLINE);
verify(exepctedFileContentOutput, 1, 1);
}
#Test
public void testTaskWhenIDNotInDB() throws IOException {
PowerMockito.when(lineIterator.nextLine()).thenReturn(ID2 + SPACE + URL1, ID3 + SPACE + URL2);
processImageData.execute();
List<String> exepctedFileContentOutput = Arrays.asList(ID3 + SPACE + URL2 + NEWLINE);
verify(exepctedFileContentOutput, 1, 1);
}
private void verify(List<String> exepctedFileContentOutput, int fileWriteTimes, int fileReadTimes) throws IOException {
for (String line : exepctedFileContentOutput){
**Line153** Mockito.verify(mockPrintWriter, Mockito.times(fileWriteTimes)).print(line);
}
PowerMockito.verifyStatic(Mockito.times(fileReadTimes));
FileUtils.lineIterator(FILTERED_IMAGE_DATA_TEXT_FILE, StandardCharsets.UTF_8.displayName());
}
}
I am mocking a new operator for PrintWriter also, injecting using beans. What is the mistake I am doing?? I am stuck on it from long time and not getting the error?
Any help is appreciated.
Updated :
I did changes suggested below and updated the code, but now I get the error:
Wanted but not invoked: mockPrintWriter.print("ASIN2 url1 "); ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageDataTest.verify‌​(ProcessImageDataTes‌​t.java:153)
However, there were other interactions with this mock: -> at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(Pr‌​ocessImageData.java:‌​51) ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(Pr‌​ocessImageData.java:‌​51) ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(Pr‌​ocessImageData.java:‌​58) –
I see 3 issues in your test:
You don't try to mock the correct constructor, indeed in the method execute, you create your PrintWriter with only one argument of type File while you try to mock the constructor with 2 arguments one of type File and the other one of type String.
So the code should rather be:
PowerMockito.whenNew(PrintWriter.class)
.withArguments(IMAGE_FILE)
.thenReturn(mockPrintWriter);
To be able to mock a constructor you need to prepare the class creating the instance which is ProcessImageData in this case, so you need to add ProcessImageData.class in the annotation #PrepareForTest. (I'm not sure ProcessImageDataTest.class is needed there)
The field lineIterator should be annotated with #Mock.
Instead of verifying print with a new line, you should verify directly println without new line it is much less error prone.
I simplified your code to show the idea.
Assuming that ProcessImageData is:
public class ProcessImageData {
private final File newImageDataTextFile;
public ProcessImageData(final File newImageDataTextFile) {
this.newImageDataTextFile = newImageDataTextFile;
}
public void execute() throws Exception{
try (PrintWriter writer = new PrintWriter(newImageDataTextFile)) {
LineIterator inputFileIterator = FileUtils.lineIterator(
newImageDataTextFile, StandardCharsets.UTF_8.displayName()
);
while (inputFileIterator.hasNext()) {
writer.println(inputFileIterator.nextLine());
}
}
}
}
My unit test would then be:
#RunWith(PowerMockRunner.class)
#PrepareForTest({ProcessImageData.class, FileUtils.class})
public class ProcessImageDataTest {
private File file = new File("imageFilePath");
private ProcessImageData processImageData;
#Mock
private PrintWriter mockPrintWriter;
#Mock
private LineIterator lineIterator;
#Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);
processImageData = new ProcessImageData(file);
PowerMockito.whenNew(PrintWriter.class)
.withArguments(file)
.thenReturn(mockPrintWriter);
PowerMockito.mockStatic(FileUtils.class);
PowerMockito.when(
FileUtils.lineIterator(file, StandardCharsets.UTF_8.displayName())
).thenReturn(lineIterator);
PowerMockito.when(lineIterator.hasNext()).thenReturn(true, true, false);
}
#Test
public void testExecute() throws Exception {
PowerMockito.when(lineIterator.nextLine()).thenReturn("Foo", "Bar");
processImageData.execute();
Mockito.verify(mockPrintWriter, Mockito.times(1)).println("Foo");
Mockito.verify(mockPrintWriter, Mockito.times(1)).println("Bar");
}
}
For more details please refer to How to mock construction of new objects.
how can I add verification in unit test for writer.close?
One way could be to simply check that close() at be called once by adding the next line to your unit test:
Mockito.verify(mockPrintWriter, Mockito.times(1)).close();
Your construction of the PrintWriter doesn't match the mock. You told PowerMockito to return your mock like this:
PowerMockito.whenNew(PrintWriter.class).withArguments(IMAGE_FILE , StandardCharsets.UTF_8.name()).thenReturn(mockPrintWriter);
So you would have to say:
new PrintWriter(IMAGE_FILE, "UTF-8"); // 2 arguments
But instead in your execute method in the code that is being tested, you do:
PrintWriter writer = new PrintWriter(newImageDataTextFile); // only 1 argument
So you either need to change the PowerMockito withArguments clause, or you need to add "UTF-8" to the constructor invocation in the execute method.

Unit testing Mongo-Hadoop jobs with MrUnit

How do you unit test mongo-hadoop jobs?
My attempt so far:
public class MapperTest {
MapDriver<Object, BSONObject, Text, IntWritable> d;
#Before
public void setUp() throws IOException {
WordMapper mapper = new WordMapper();
d = MapDriver.newMapDriver(mapper);
}
#Test
public void testMapper() throws IOException {
BSONObject doc = new BasicBSONObject("sentence", "Two words");
d.withInput(new Text("anykey"), doc );
d.withOutput(new Text("Two"), new IntWritable(1));
d.withOutput(new Text("words"), new IntWritable(1));
d.runTest();
}
}
Which produces this output:
No applicable class implementing Serialization in conf at io.serializations for class org.bson.BasicBSONObject
java.lang.IllegalStateException
at org.apache.hadoop.mrunit.internal.io.Serialization.copy(Serialization.java:67)
at org.apache.hadoop.mrunit.internal.io.Serialization.copy(Serialization.java:91)
at org.apache.hadoop.mrunit.internal.io.Serialization.copyWithConf(Serialization.java:104)
at org.apache.hadoop.mrunit.TestDriver.copy(TestDriver.java:608)
at org.apache.hadoop.mrunit.TestDriver.copyPair(TestDriver.java:612)
at org.apache.hadoop.mrunit.MapDriverBase.addInput(MapDriverBase.java:118)
at org.apache.hadoop.mrunit.MapDriverBase.withInput(MapDriverBase.java:207)
...
You need to set the serializer.
Example : mapDriver.getConfiguration().setStrings("io.serializations",
"org.apache.hadoop.io.serializer.WritableSerialization", MongoSerDe.class.getName());
MongoSerDe src: https://gist.github.com/lfrancke/01d1819a94f14da171e3
But I face error "org.bson.io.BasicOutputBuffer.pipe(Ljava/io/DataOutput;)I" while using this(MongoSerDe).

Using soapUI API to create a soapUI Mock object

I try to create a soap UI WSDL Mock Service using the soapUI API. But there seems to be no documentation of the source code.
Has anyone done this before or something in that direction?
Ok, I can now answer myself ... :)
I created a unit test for this task:
private static WsdlProjectFactory wsdlProjectFactory;
private static WsdlInterfaceFactory wsdlInterfaceFactory;
#BeforeClass
public static void createFactories(){
wsdlProjectFactory = new WsdlProjectFactory();
wsdlInterfaceFactory = new WsdlInterfaceFactory();
}
#Before
public void deleteCreatedFiles() {
new File("global-groovy.log").delete();
new File("soapui-errors.log").delete();
new File("soapui.log").delete();
new File("test.xml").delete();
}
private WsdlProject project;
#Before
public void createProject() throws XmlException, IOException, SoapUIException {
project = wsdlProjectFactory.createNew();
}
#Test #Ignore
public void testWSDLInterfaceImporting() throws SoapUIException {
int interfaceCount = project.getInterfaceCount();
assertThat("newly created project has no interfaces", interfaceCount, is(equalTo(0)));
WsdlInterface[] importWsdl = wsdlInterfaceFactory.importWsdl(project, "wsdls/SimpleUseCasesellerbtainitialbtexampleMasterClient.wsdl", false);
interfaceCount = project.getInterfaceCount();
assertThat("newly created project has 1 interface", interfaceCount, is(equalTo(1)));
}
#Test
public void testMockCreation() throws XmlException, IOException, SoapUIException {
int mockCount = project.getMockServiceCount();
assertThat("newly created project has no mocks", mockCount, is(equalTo(0)));
WsdlInterface[] importWsdl = wsdlInterfaceFactory.importWsdl(project, "wsdls/SimpleUseCasesellerbtainitialbtexampleMasterClient.wsdl", false);
WsdlMockService service = project.addNewMockService("newMockService");
service.addNewMockOperation(importWsdl[0].getOperationAt(0));
project.saveAs("test.xml");
mockCount = project.getMockServiceCount();
assertThat("project has exactly one mock", mockCount, is(1));
}

Categories