Quarkus Multiple File Upload - resteasy

Hi i'm trying to upload multiple files using multipart form
I use this but i get Bad Request Status, how can i upload multiple files?
public class AttachmentBody {
#FormParam("files")
#PartType(MediaType.APPLICATION_OCTET_STREAM)
public InputStream[] files;
}

I was working in a part, I thought it would be helpful for multiple files upload. I am using RestEasy and Quarkus framework. Find below the code.
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.annotations.providers.multipart.MultipartForm;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
#Path("/multiupload")
public class MultiFileUploadController {
private static String UPLOAD_DIR = "E:/sure-delete";
#POST
#Path("/files")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public Response handleFileUploadForm(#MultipartForm MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<String> fileNames = new ArrayList<>();
List<InputPart> inputParts = uploadForm.get("file");
System.out.println("inputParts size: " + inputParts.size());
String fileName = null;
for (InputPart inputPart : inputParts) {
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
fileName = getFileName(header);
fileNames.add(fileName);
System.out.println("File Name: " + fileName);
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] bytes = IOUtils.toByteArray(inputStream);
File customDir = new File(UPLOAD_DIR);
fileName = customDir.getAbsolutePath() + File.separator + fileName;
Files.write(Paths.get(fileName), bytes, StandardOpenOption.CREATE_NEW);
} catch (Exception e) {
e.printStackTrace();
}
}
String uploadedFileNames = String.join(", ", fileNames);
return Response.ok().entity("All files " + uploadedFileNames + " successfully.").build();
}
private String getFileName(MultivaluedMap<String, String> header) {
String[] contentDisposition = header.getFirst("Content-Disposition").split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
return finalFileName;
}
}
return "unknown";
}
}
To test from the postman client, find below the image.
You can take it as an example also handle the exception.

Related

Why getting resource list null for webpage when automating desktop application i.e. hybrid (Desktop and Web)?

I am automating hybrid application i.e. Desktop and WebApplication. We have desktop application in which some of pages are integrated using WebPages and some one pages are in desktop application. Below is the code which I have used to open Desktop Application. And its opening the application successfully. But When I am going to print resource list size, it comes 'null' where locator for resourcelist is showing correct count in chrome browser. I can login successfully using winium driver instance. After logged in, list of resources are present which I integrated in webpage.
Let me know if I am doing wrong in given code?
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.winium.DesktopOptions;
import org.openqa.selenium.winium.WiniumDriver;
import org.openqa.selenium.winium.WiniumDriverService;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
public class VMSWiniumBaseDriver {
public WiniumDriver driver;
String applicationPath = "C:\\Users\\prashantn\\Downloads\\Publish\\ABC.exe";
#Parameters({ "windowsPlatform" })
#BeforeClass(alwaysRun = true)
public void initialize(String browser) throws IOException, InterruptedException {
if (browser.equalsIgnoreCase("desktop")) {
try {
WiniumDriverService service;
DesktopOptions option;
option = new DesktopOptions();
option.setApplicationPath(applicationPath);
File driverPath = new File(System.getProperty("user.dir") + File.separator + "driver" + File.separator
+ "Winium.Desktop.Driver.exe");
service = new WiniumDriverService.Builder().usingDriverExecutable(driverPath).usingPort(9999)
.withVerbose(true).withSilent(false).buildDesktopService();
try {
service.start();
} catch (IOException e) {
System.out.println("Exception while starting WINIUM service");
e.printStackTrace();
}
driver = new WiniumDriver(service, option);
} catch (Exception e) {
System.out.println(e);
}
}
}
#AfterClass(alwaysRun = true)
public void TeardownTest() {
if (null == driver) {
driver.close();
driver.quit();
}
}
public WiniumDriver getDriver() {
return driver;
}
}
Here is
CommonUtilities.Java
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.ThreadLocalRandom;
import org.openqa.selenium.WebDriver;
import org.sikuli.hotkey.Keys;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import org.sikuli.script.ScreenImage;
import dataproviders.VMSConfigFileReader;
import managers.VMSWiniumBaseDriver;
public class CommonUtilities extends VMSWiniumBaseDriver {
public WebDriver getWebDriverInstance() {
WebDriver webDriver = (WebDriver) driver;
return webDriver;
}
}
LoginPage.java
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.winium.WiniumDriver;
import utilities.CommonUtilities;
public class LoginPage{
#FindBy(id = "PART_EditableTextBox")
WebElement userName;
#FindBy(id = "TextBlock_Password")
WebElement passwordInput;
#FindBy(id = "LoginButton")
WebElement loginButton;
#FindBy(xpath = "//dd[contains(#class,'vms-tree-enabled')]/span[#class='vms-treeview-label'][#title!='Removed channels'][#title!='Unassociated']")
List<WebElement> resourcesList;
public void getResourcesList() {
CommonUtilities commonUtilities = new CommonUtilities();
// System.out.println("Page Source :: "+commonUtilities.getWebDriverInstance());
List<WebElement> list = commonUtilities.getWebDriverInstance().findElements(By.xpath(
"//dd[contains(#class,'vms-tree-enabled')]/span[#class='vms-treeview-label'][#title!='Removed channels'][#title!='Unassociated']"));
System.out.println("Resources Size :: " + list.size());
for (int i = 0; i < resourcesList.size(); i++) {
System.out.println("Resource Name :: " + resourcesList.get(i).getText());
}
}
}
Exception Log:
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.WebDriver.findElements(org.openqa.selenium.By)" because the return value of "utilities.CommonUtilities.getWebDriverInstance()" is null
at pageobjects.LoginPage.getResourcesList(LoginPage.java:57)
at testcases.AppLaunchTest.selectLayOutBasic1(AppLaunchTest.java:62)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:132)
at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:599)
at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:174)
at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46)
at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:822)
at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:147)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
at org.testng.TestRunner.privateRun(TestRunner.java:764)
at org.testng.TestRunner.run(TestRunner.java:585)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:384)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337)
at org.testng.SuiteRunner.run(SuiteRunner.java:286)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1218)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
at org.testng.TestNG.runSuites(TestNG.java:1069)
at org.testng.TestNG.run(TestNG.java:1037)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)

allure report +selenide, Attached console print log is empty

I am using selenide, testng and allure reports.My goal is just print console logs into the allure report
I am using below code (demo)to add text printed on console to attach to my allure reports :
import com.codeborne.selenide.testng.TextReport;
import com.codeborne.selenide.testng.annotations.Report;
import io.qameta.allure.Attachment;
import org.openqa.selenium.By;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import static com.codeborne.selenide.CollectionCondition.size;
import static com.codeborne.selenide.Condition.enabled;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.*;
import java.io.IOException;
import java.util.List;
#Report
#Listeners(TextReport.class)
public class GoogleTestNGTest {
#Attachment
public String logOutput(List<String> outputList) {
String output = "";
for (String o : outputList)
output += o + " ";
return output;
}
#AfterMethod
protected void printLog(ITestResult testResult) throws IOException {
logOutput(Reporter.getOutput(testResult));
}
#BeforeMethod
public void setUp() {
TextReport.onSucceededTest = true;
TextReport.onFailedTest = true;
open("http://google.com/ncr");
}
#Test(enabled = true)
public void failingMethod() {
$(By.name("q")).shouldBe(visible, enabled);
$("#missing-button").click();
}
#Test
public void successfulMethod() {
$(By.name("q")).setValue("selenide").pressEnter();
$$("#ires .g").shouldHave(size(10));
}
}
The problem is that the printLog is empty
screenshot
how i can fix it ?
I got this working by adding this to my browser setup method:
LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(BROWSER, Level.ALL);
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
And added this to my code which handles the allure report generation:
List<String> logs = Selenide.getWebDriverLogs(LogType.BROWSER);
Allure.addAttachment("Console logs: ", logs.toString());
i am using for logs..
protected static void log(String stringToLog) {
final String uuid = UUID.randomUUID().toString();
final StepResult result = new StepResult()
.withName(stringToLog);
getLifecycle().startStep(uuid, result);
try {
getLifecycle().updateStep(uuid, s -> s.withStatus(Status.PASSED));
} finally {
getLifecycle().stopStep(uuid);
}
}

MULE HTTP listener attachment with rest web service

I am New to MULE ESB I am tryting to handle file attachment with http listener using rest web service.
I am created a simple flow but dont know how to handle attachment in mule to pass rest ful web service .
Any help greatly appreciated!!
:(
Given is simple flow waht i am assuming to be work !!
rest web service code ::
package com.one.file;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
#Path("/upload")
public class RESTMultipleFileUpload {
private static final String FILE_UPLOAD_PATH = "C:\\Users\\charan\\Documents\\webservice\\";
//private static final String CANDIDATE_NAME = "candidateName";
private static final String SUCCESS_RESPONSE = "Successful";
private static final String FAILED_RESPONSE = "Failed";
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("text/plain")
#Path("/multipleFiles")
public String registerWebService(#Context HttpServletRequest request)
{
String responseStatus = SUCCESS_RESPONSE;
String candidateName = null;
System.out.println("first ");
System.out.println("Two::"+request);
//checks whether there is a file upload request or not
if (ServletFileUpload.isMultipartContent(request))
{
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
try
{
System.out.println("t ");
/*
* parseRequest returns a list of FileItem
* but in old (pre-java5) style
*/
final List items = fileUpload.parseRequest(request);
if (items != null)
{
final Iterator iter = items.iterator();
while (iter.hasNext())
{
final FileItem item = (FileItem) iter.next();
final String itemName = item.getName();
final String fieldName = item.getFieldName();
final String fieldValue = item.getString();
if (item.isFormField())
{
candidateName = fieldValue;
System.out.println("Field Name: " + fieldName + ", Field Value: " + fieldValue);
System.out.println("Candidate Name: " + candidateName);
}
else
{
final File savedFile = new File(FILE_UPLOAD_PATH + File.separator
+ itemName);
System.out.println("Saving the file: " + savedFile.getName());
item.write(savedFile);
}
}
}
}
catch (FileUploadException fue)
{
responseStatus = FAILED_RESPONSE;
fue.printStackTrace();
}
catch (Exception e)
{
responseStatus = FAILED_RESPONSE;
e.printStackTrace();
}
}
System.out.println("Returned Response Status: " + responseStatus);
return responseStatus;
}
}

Execute lucene booleanquery in file huge problems

I 've a problem with my huge nquad file (about 4000 lines) when i execute a boolenquery,
i try a query as:
Query query1 = new TermQuery(new Term(FIELD_CONTENTS, "Albania"));
Query query2 = new TermQuery(new Term(FIELD_CONTENTS, "Hitchcock"));
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.add(query1, BooleanClause.Occur.MUST);
booleanQuery.add(query2, BooleanClause.Occur.MUST);
This query performs correctly when the words that I try to search in the line number<780, then >780 failed.
This is a snippet of my nquad file:
<http://dbpedia.org/resource/A_Clockwork_Orange> <http://dbpedia.org/ontology/numberOfPages> "192"^^<http://www.w3.org/2001/XMLSchema#positiveInteger> <http://en.wikipedia.org/wiki/A_Clockwork_Orange?oldid=606117686#absolute-line=12> .
I make a custom analyzer for distinguer tokens:
import java.io.Reader;
import java.util.Set;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.StopFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
class TestAnalyzer1 extends Analyzer {
public static final String[] TEST_STOP_WORDS = { "http", "https",
"resource", "foaf/0.1", "dbpedia.org", "en.wikipedia.org",
"xmlns.com", "purl.org", "elements/1.1",
"www.w3.org/2001/XMLSchema", "www.w3.org/1999/02/22-rdf",
"www.w3.org/2003/01", "oldid", "wiki" };
#SuppressWarnings("rawtypes")
private Set stopWords = StopFilter.makeStopSet(TEST_STOP_WORDS);
public TokenStream tokenStream(String fieldName, Reader reader) {
TokenStream ts = new StandardTokenizer(reader);
ts = new StandardFilter(ts);
ts = new StopFilter(ts, stopWords);
return ts;
}
}
This is main class:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermFreqVector;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Hit;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.LockObtainFailedException;
#SuppressWarnings("deprecation")
public class TestPreFinal {
public static final String FILES_TO_INDEX_DIRECTORY = "filesToIndex_1";
public static final String INDEX_DIRECTORY = "indexDirectory";
public static final String FIELD_PATH = "path";
public static final String FIELD_CONTENTS = "contents";
public static void main(String[] args) throws CorruptIndexException,
LockObtainFailedException, IOException, ParseException {
long startTime = System.currentTimeMillis();
Analyzer analyzer = new TestAnalyzer1();
IndexWriter indexWriter = new IndexWriter(INDEX_DIRECTORY, analyzer,
true);
File dir = new File(FILES_TO_INDEX_DIRECTORY);
File[] files = dir.listFiles();
for (File file : files) {
Reader reader = new FileReader(file);
Document document = new Document();
String path = file.getCanonicalPath();
Field fieldPath = new Field(FIELD_PATH, path, Field.Store.YES,
Field.Index.UN_TOKENIZED);
Field fieldContents = new Field(FIELD_CONTENTS, reader,
Field.TermVector.WITH_POSITIONS_OFFSETS);
document.add(fieldPath);
document.add(fieldContents);
indexWriter.addDocument(document);
}
indexWriter.commit();
indexWriter.close();
Directory directory = FSDirectory.getDirectory(INDEX_DIRECTORY);
IndexSearcher indexSearcher = new IndexSearcher(directory);
IndexReader indexReader = IndexReader.open(directory);
Query query1 = new TermQuery(new Term(FIELD_CONTENTS, "Albania"));
Query query2 = new TermQuery(new Term(FIELD_CONTENTS, "Hitchcock"));
BooleanQuery booleanQuery = new BooleanQuery();
booleanQuery.add(query1, BooleanClause.Occur.MUST);
booleanQuery.add(query2, BooleanClause.Occur.MUST);
Hits hits = indexSearcher.search(booleanQuery);
#SuppressWarnings({ "unchecked" })
Iterator<Hit> it = hits.iterator();
TermFreqVector tfv = null;
while (it.hasNext()) {
Hit hit = it.next();
Document document = hit.getDocument();
String path = document.get(FIELD_PATH);
System.out.println("Hit: " + path);
}
for (int i = 0; i < hits.length(); i++) {
tfv = indexReader.getTermFreqVector(i, FIELD_CONTENTS);
System.out.println(tfv);
}
}
}
I do not know what else to do. You can help please. Thanks in advance.

how to create CXF API for jbilling integration?

Can anyone tell me how to create CXF API? For jbilling integration, I want to create CXF API. But I don't know how to create it.
you can create a class in jbilling which call other evn and send headers and body as Json or string.
like this.
package com.cycle30.plugin.payment;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.log4j.Logger;
public class HttpJMSClient {
private PostMethod postMethod;
private String webUrl;
private List<NameValuePair> nameValuePairs=new ArrayList<NameValuePair>();
private static final Logger logger = Logger.getLogger(HttpJMSClient.class);
public HttpJMSClient() {
// TODO Auto-generated constructor stub
}
public void getConnection()
{
webUrl="http://localhost:8081";
nameValuePairs.add(new NameValuePair("x-force-user-id","abc1233"));
nameValuePairs.add(new NameValuePair("x-trans-id","123"));
}
public String makeCall( String body)
{
Object output=null;
try{
WebClient client = WebClient.create(webUrl);
for (NameValuePair h : nameValuePairs) {
client.header(h.getName(), h.getValue());
}
Response response = client.type(MediaType.APPLICATION_JSON).post(body,
Response.class);
logger.debug("Output from Server .... \n");
output = response.getEntity();
logger.debug(output);
System.out.println("my res: "+output.toString());
int statusCode = response.getStatus();
System.out.println("status code: "+statusCode);
return output.toString();
}catch(Exception e){
logger.error(e.getMessage());
logger.error(e.getCause());
}
return output.toString();
}
}

Resources