How to get table metadata from camel-sql component - metadata

I'm looking for a way to get all the column meta data for the given table name using camel-sql component.
Though it uses spring-jdbc behind the scenes i do not see a way to get the ResultSetMetaData.

I couldn't find a direct way to get the column details from camel-sql component, For now managed to get the information using spring jdbc template and data source.
public List<String> getColumnNamesFromTable(final TableData tableData) throws MetaDataAccessException {
final List<String> columnNames = new ArrayList<String>();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
StringBuilder query = new StringBuilder();
query.append("SELECT * FROM ").append(SINGLE_BLANK_SPACE);
query.append(tableData.getSchemaName());
query.append(tableData.getTableName()).append(SINGLE_BLANK_SPACE);
query.append("WHERE rownum < 0");
jdbcTemplate.query(query.toString(), new ResultSetExtractor<Integer>() {
#Override
public Integer extractData(ResultSet rs) throws SQLException, DataAccessException {
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add(rsmd.getColumnName(i).toUpperCase());
}
return columnCount;
}
});
return columnNames;
}

Related

Liquibase update throwing error when running in parallel

I am trying to generate DDL scripts for my JPA entities and it works just fine.
I am adding a unit test for the same which is providing me with this error
Caused by: liquibase.exception.ServiceNotFoundException: Could not find unique implementation of liquibase.executor.Executor. Found 0 implementations
at liquibase.servicelocator.ServiceLocator.findClass(ServiceLocator.java:185)
at liquibase.servicelocator.ServiceLocator.newInstance(ServiceLocator.java:211)
... 21 more
My testng test looks like this
#DataProvider(parallel = true)
public Object[][] listToArrays() {
File f=new File(PropertyReader.getInstance().getProperty("path");
File[] files=f.listFiles();
List<MetaData> list =prepare(files);
Object[][] array = new Object[list.size()][1];
for (int i = 0; i < list.size(); i++) {
array[i][0] = list.get(i);
}
return array;
}
#Test(dataProvider = "listToArrays")
public void test(MetaData s) throws ScriptGenerationException,
UnsupportedEncodingException, LiquibaseException, IOException {
String[] rdbmsTypes=new String[]
{"MSSQL","POSTGRES","ORACLE","MYSQL"};
for (String rdbmsType : rdbmsTypes) {
FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor();
CommandLineResourceAccessor clOpener = new CommandLineResourceAccessor(this.getClass().getClassLoader());
CompositeResourceAccessor fileOpener = new CompositeResourceAccessor(new ResourceAccessor[] { fsOpener, clOpener });
Database database = CommandLineUtils.createDatabaseObject(fileOpener, this.url, this.username, this.password, this.driver,
this.defaultCatalogName, this.defaultSchemaName, Boolean.parseBoolean(this.outputDefaultCatalog),
Boolean.parseBoolean(this.outputDefaultSchema), this.databaseClass,
this.driverPropertiesFile, this.propertyProviderClass, this.liquibaseCatalogName,
this.liquibaseSchemaName, this.databaseChangeLogTableName, this.databaseChangeLogLockTableName);
Liquibase liquibase=new Liquibase(d, null, database);
Writer w=getOutputWriter();
liquibase.update(new Contexts(this.contexts), new LabelExpression(this.labels), w);
w.close();
}
}
What could be the cause of the problem ?
Note : I am only using Liquibase in offline mode.

How I can make dynamic header column and dynamic data to export to Excel/CSV/PDF using MongoDB, Spring Boot, and apache poi

I want to make export function using Spring Boot, I have data on MongoDB NoSQL, and then want to export my document on MongoDB Dynamically using Apache POI ( If any better dependency you can recommend to me).
I don't want to declare header column, entity model, etc., I want to export data dynamically as shown as in my Document database, any one can give me an example for it?
Please try these code may be help for you.
->add Gson Depandencies in porm.xml
Controller code
MasterController.java
#Autowired
MasterServiceImpl masterServiceImpl;
#GetMapping(value="/dynamicfile/{flag}/{fileType}/{fileName}")
public ResponseEntity<InputStreamResource> downloadsFiles(#PathVariable("flag") int flag,#PathVariable("fileType") String fileType,#PathVariable("fileName") String fileName) throws IOException{
List<?> objects=new ArrayList<>();
if(flag==1) {
objects=masterServiceImpl.getData();
}
ByteArrayInputStream in = masterServiceImpl.downloadsFiles(objects,fileType);
HttpHeaders headers = new HttpHeaders();
if(fileType.equals("Excel")) {
headers.add("Content-Disposition", "attachment; filename="+fileName+".xlsx");
}else if(fileType.equals("Pdf")){
headers.add("Content-Disposition", "attachment; filename="+fileName+".pdf");
}else if(fileType.equals("Csv")) {
headers.add("Content-Disposition", "attachment; filename="+fileName+".csv");
}
return ResponseEntity.ok().headers(headers).body(new InputStreamResource(in));
}
Service code :
MasterServiceImpl.java
public static List<HashMap<Object, Object>> getListOfObjectToListOfHashMap(List<?> objects) {
List<HashMap<Object,Object>> list=new ArrayList<>();
for(int i=0;i<objects.size();i++) {
HashMap<Object,Object> map=new HashMap<>();
String temp=new Gson().toJson(objects.get(i)).toString();
String temo1= temp.substring(1, temp.length()-1);
String[] temp2=temo1.split(",");
for(int j=-1;j<temp2.length;j++) {
if(j==-1) {
map.put("SrNo",i+1);
}else {
String tempKey=temp2[j].toString().split(":")[0].toString();
String tempValue=temp2[j].toString().split(":")[1].toString();
char ch=tempValue.charAt(0);
if(ch=='"') {
map.put(tempKey.substring(1, tempKey.length()-1), tempValue.substring(1, tempValue.length()-1));
}else {
map.put(tempKey.substring(1, tempKey.length()-1), tempValue);
}
}
}
list.add(map);
}
return list;
}
public static ByteArrayInputStream downloadsFiles(List<?> objects,String fileType) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
List<HashMap<Object, Object>> list = getListOfObjectToListOfHashMap(objects);
String[] COLUMNs = getColumnsNameFromListOfObject(objects);
try{
if(fileType.equals("Excel")) {
generateExcel(list, COLUMNs,out);
}else if(fileType.equals("Pdf")) {
generatePdf(list, COLUMNs,out);
}else if(fileType.equals("Csv")) {
generatePdf(list, COLUMNs,out);
}
}catch(Exception ex) {
System.out.println("Error occurred:"+ ex);
}
return new ByteArrayInputStream(out.toByteArray());
}
public static final String[] getColumnsNameFromListOfObject(List<?> objects) {
String strObjects=new Gson().toJson(objects.get(0)).toString();
String[] setHeader= strObjects.substring(1, strObjects.length()-1).split(",");
String header="SrNo";
for(int i=0;i<setHeader.length;i++) {
String str=setHeader[i].toString().split(":")[0].toString();
header=header+","+str.substring(1, str.length()-1);
}
return header.split(",");
}
public static final void generateExcel(List<HashMap<Object, Object>> list, String[] COLUMNs,ByteArrayOutputStream out) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Excelshit");
Font headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(IndexedColors.BLUE.getIndex());
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setFont(headerFont);
Row headerRow = sheet.createRow(0);
for (int col = 0; col < COLUMNs.length; col++) {
Cell cell = headerRow.createCell(col);
cell.setCellValue(COLUMNs[col]);
cell.setCellStyle(headerCellStyle);
}
int rowIdx = 1;
for(int k = 0; k < list.size(); k++){
Row row =sheet.createRow(rowIdx++);
for (Map.Entry<Object, Object> entry : list.get(k).entrySet()){
Object key = entry.getKey();
Object value = entry.getValue();
for (int col = 0; col < COLUMNs.length; col++) {
if(key.toString().equals(COLUMNs[col].toString())) {
row.createCell(col).setCellValue(value.toString());
}
}
}
}
workbook.write(out);
System.out.println(workbook);
}
private static final void generatePdf(List<HashMap<Object, Object>> list, String[] COLUMNs,ByteArrayOutputStream out) throws DocumentException {
Document document = new Document();
com.itextpdf.text.Font headerFont =FontFactory.getFont(FontFactory.HELVETICA_BOLD,8);
com.itextpdf.text.Font dataFont =FontFactory.getFont(FontFactory.TIMES_ROMAN,8);
PdfPCell hcell=null;
PdfPTable table = new PdfPTable(COLUMNs.length);
for (int col = 0; col < COLUMNs.length; col++) {
hcell = new PdfPCell(new Phrase(COLUMNs[col], headerFont));
hcell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(hcell);
}
for(int index = 0; index < list.size(); index++){
PdfPCell cell = null;
for (Map.Entry<Object, Object> entry : list.get(index).entrySet()){
Object key = entry.getKey();
Object value = entry.getValue();
for (int col = 0; col < COLUMNs.length; col++) {
if(key.toString().equals(COLUMNs[col].toString())) {
cell = new PdfPCell(new Phrase(value.toString(),dataFont));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
}
table.addCell(cell);
}
}
PdfWriter.getInstance(document, out);
document.open();
document.add(table);
document.close();
}
public List<TblDepartment> getData() {
List<TblDepartment> list = new ArrayList<>();
departmentRepository.findAll().forEach(list::add);
return list;
}

QuickfixJ create message from xml string

QuickFixJ Message class has method toXML() which converts message into xml string.
Is there any way I can create message object from the XML string?
I need the reverse of toXML() i.e. I want to create Message from xml.
There's nothing like that built in. There doesn't really need to be, as there normally wouldn't be a use-case for it.
I've written a class which does it. The order of the tags might be different from the input message (but the FIX spec makes no guarantees about tag order, except within groups) because the XML exporter sorts by tag number, and so the original tag order is lost.
It only works on a single message in an XML file, but could easily be adapted to work on multiple messages.
You can use the standard MessageUtils.parse to create a Message from the resultant string.
Let me know if you have any problems.
class XmlMessage
{
private final String xml;
private final String delimiter;
XmlMessage(final String xml, final String delimiter)
{
this.xml = xml;
this.delimiter = delimiter;
}
public String toFixMessage() throws IOException, SAXException, ParserConfigurationException
{
final Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(xml.getBytes()));
final StringBuilder messageBuilder = new StringBuilder();
build(messageBuilder, doc, "header");
build(messageBuilder, doc, "body");
build(messageBuilder, doc, "trailer");
return messageBuilder.toString();
}
private void build(final StringBuilder messageBuilder, final Document doc, final String section)
{
final NodeList sectionRoot = doc.getElementsByTagName(section);
final NodeList sectionChildren = sectionRoot.item(0).getChildNodes();
build(messageBuilder, sectionChildren);
}
private void build(final StringBuilder messageBuilder, final NodeList nodeList)
{
final Set<String> numInGroupTags = getNumInGroupTags(nodeList);
for (int i = 0; i < nodeList.getLength(); i++)
{
final Node node = nodeList.item(i);
if (node.getNodeName().equals("field") && !numInGroupTags.contains(getTagNumber(node)))
{
messageBuilder.append(getTagNumber(node))
.append('=')
.append(node.getTextContent())
.append(delimiter);
}
else if (node.getNodeName().equals("groups"))
{
final NodeList groupElems = node.getChildNodes();
messageBuilder.append(getTagNumber(node))
.append('=')
.append(getGroupCount(groupElems))
.append(delimiter);
for (int j = 0; j < groupElems.getLength(); j++)
{
build(messageBuilder, groupElems.item(j).getChildNodes());
}
}
}
}
private Set<String> getNumInGroupTags(final NodeList nodeList)
{
final Set<String> numInGroupTags = new HashSet<>();
for (int i = 0; i < nodeList.getLength(); i++)
{
if (nodeList.item(i).getNodeName().equals("groups"))
{
numInGroupTags.add(getTagNumber(nodeList.item(i)));
}
}
return numInGroupTags;
}
private String getTagNumber(final Node node)
{
return node.getAttributes().getNamedItem("tag").getTextContent();
}
private int getGroupCount(final NodeList groupRoot)
{
int count = 0;
for (int j = 0; j < groupRoot.getLength(); j++)
{
if (groupRoot.item(j).getNodeName().equals("group")) count++;
}
return count;
}
}

android - trying to create listview

i'm trying to write data from sqlite to a listview. the compiler doesn't show error, but when I run the app on my phone, it crashes. please help me
Cursor resultSet = db.rawQuery("Select * from weight_listview ORDER BY `id` DESC",null);
resultSet.moveToFirst();
String[] list = new String[] {};
String[] weighttolist={};
String[] datetolist={};
ArrayList<String> List=new ArrayList<String>();
ArrayList<String> List2=new ArrayList<String>();
resultSet.moveToFirst();
int x = 0;
while(resultSet.moveToNext()){
String data = resultSet.getString(resultSet.getColumnIndex("weight"));
String data2 = resultSet.getString(resultSet.getColumnIndex("date"));
String id = resultSet.getString(resultSet.getColumnIndex("ID"));
List.add(data + " " + data2);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
String[] from = { "weight", "date" };
int[] to = { R.id.weight, R.id.date };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.row, resultSet, from, to);
listView.setAdapter(cursorAdapter);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, android.R.id.text1, weighttolist);
// ListView.setAdapter(adapter);
}
edit:
I successed to fix the problem but now I have another problem. I want that the listview will show 2 columns , not only 1 . I created fill row.xml , as you can see in the first code.
Cursor resultSet = db.rawQuery("Select * from weight_listview ORDER BY `id` DESC",null);
resultSet.moveToFirst();
String[] list = new String[] {};
String[] weighttolist={};
String[] datetolist={};
ArrayList<String> List=new ArrayList<String>();
ArrayList<String> List2=new ArrayList<String>();
resultSet.moveToFirst();
int x = 0;
while(resultSet.moveToNext()){
String data = resultSet.getString(resultSet.getColumnIndex("weight"));
String data2 = resultSet.getString(resultSet.getColumnIndex("date"));
List.add(data + " " + data2);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, weighttolist);
listView.setAdapter(adapter);
}
Well without the exact error it is hard to see what is going wrong. Here is my guess you are using a SimpleAdapter who's constructor looks like this
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
For your second parameter you are using a Cursor not a list, your from variable are keys so you need to use a hash map I believe
Comment out your code and try this
List<HashMap<String, String>> List = new ArrayList<HashMap<String, String>>();
int x = 0;
while(resultSet.moveToNext()){
HashMap<String, String> map = new HashMap<String, String>();
String weight = resultSet.getString(resultSet.getColumnIndex("weight"));
String date = resultSet.getString(resultSet.getColumnIndex("date"));
String id = resultSet.getString(resultSet.getColumnIndex("ID"));
map.put("weight", weight);
map.put("date", date);
List.add(map);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
String[] from = { "weight", "date" };
int[] to = { R.id.weight, R.id.date };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.row, List, from, to);
listView.setAdapter(cursorAdapter);

Passing database data to another activity

how can I pass an array of strings and integers which contains the database data into another activity...I don't know how to put the database data on the string array
You can use this method to retrieve data from the table
public List<String[]> getData(String query) throws SQLException{
Cursor c = mdb.rawQuery(query, null);
c.moveToFirst();
List<String[]> data = new ArrayList<String[]>();
if (c != null) {
for (int i = 0; i < c.getCount(); i++) { // iterate rows
String[] row = new String[c.getColumnCount()];
for(int j = 0; j < c.getColumnCount(); j++){//iterate columns
row[j] = c.getString(j);
}
data.add(row);
c.moveToNext();
}
}
c.close();
Log.i("getData", data.size() + " rows returned");
return data;
}
Each row of the result will be contained in each String[] of the list.
Say, intentData is a String[] and you want to pass the data to the next activity.For this, you have to add the data to the Intent like this
Intent intent = new Intent(CurrentAct.this, NextAct.class);
intent.putExtra("dbData", intentData);
startActivity(intent);
You can retrieve the data from NextAct's onCreate() method like this :
String[] passedData = getIntent().getExtras().getStringArray("dbData");