It is necessary to attach a 0313 XEP (0.2)
http://xmpp.org/extensions/attic/xep-0313-0.2.html#sect-idp616432
in to SMACK/ASMACK.
I create PacketExtension for this.
public class Archive313 implements PacketExtension {
static final public String NAMESPACE = "urn:xmpp:mam:tmp";
static final public String ELEMENT = "result";
private String Id;
private String Queryid;
private String Stamp;
private String To;
private String From;
private String Type;
private String Body;
public Archive313(String id, String queryid, String stamp, String to, String from, String type, String body) {
Id = id;
Queryid = queryid;
Stamp = stamp;
To = to;
From = from;
Type = type;
Body = body;
}
#Override
public String getElementName() {
return ELEMENT;
}
#Override
public String getNamespace() {
return NAMESPACE;
}
#Override
public String toXML() {
return "<" + ELEMENT + " xmlns='" + NAMESPACE + "' queryid='" + Queryid + "' id='" + Id + "'>" +
"<forwarded xmlns='urn:xmpp:forward:0'>" +
"<delay xmlns='urn:xmpp:delay' stamp='" + Stamp + "'/><message to='"
+ To + "' from='" + From + "' type='" + Type + "'><body>" + Body + "</body></message></forwarded></result>";
}
public static class Archive313Provider implements PacketExtensionProvider {
#Override
public PacketExtension parseExtension(XmlPullParser xmlPullParser) throws Exception {
String tag_name = "";
String id = "";
String queryid = "";
String stamp = "";
String to = "";
String from = "";
String type = "";
String body = "";
while (xmlPullParser.getEventType() != XmlPullParser.END_DOCUMENT) {
switch (xmlPullParser.getEventType()) {
case XmlPullParser.START_TAG:
tag_name = xmlPullParser.getName();
for (int i = 0; i < xmlPullParser.getAttributeCount(); i++) {
if (tag_name != null && tag_name.equals("result")) {
if (xmlPullParser.getAttributeName(i).equals("queryid")) {
queryid = xmlPullParser.getAttributeValue(i);
}
if (xmlPullParser.getAttributeName(i).equals("id")) {
id = xmlPullParser.getAttributeValue(i);
}
}
if (tag_name != null && tag_name.equals("delay")) {
if (xmlPullParser.getAttributeName(i).equals("stamp")) {
stamp = xmlPullParser.getAttributeValue(i);
}
}
if (tag_name != null && tag_name.equals("message") && xmlPullParser.getAttributeCount() > 2) {
if (xmlPullParser.getAttributeName(i).equals("to")) {
to = xmlPullParser.getAttributeValue(i);
}
if (xmlPullParser.getAttributeName(i).equals("from")) {
from = xmlPullParser.getAttributeValue(i);
}
if (xmlPullParser.getAttributeName(i).equals("type")) {
type = xmlPullParser.getAttributeValue(i);
}
}
}
break;
case XmlPullParser.END_TAG:
tag_name = xmlPullParser.getName();
break;
case XmlPullParser.TEXT:
if ("body".equals(tag_name)) {
body = xmlPullParser.getText();
}
break;
default:
break;
}
xmlPullParser.next();
}
return new Archive313(id,queryid,stamp,to,from,type,body);
}
}
}
ProviderManager pm = ProviderManager.getInstance();
pm.addExtensionProvider("result", "urn:xmpp:mam:tmp", new Archive313.Archive313Provider());
mXMPPConnection.addPacketListener(archiveListener, new PacketExtensionFilter("result", "urn:xmpp:mam:tmp"));
private PacketListener archiveListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {
Log.d("archiveListener", packet.toXML());
}
};
In this implementation I do not give any Packet to archiveListener.
If i set filter:
PacketFilter filter = new PacketFilter() {
#Override
public boolean accept(Packet packet) {
if (packet.toXML().contains("urn:xmpp:mam:tmp")) {
return true;
}
return false;
}
};
I got packages but they are not full.
Need to be:
<message id='aeb213' to='juliet#capulet.lit/chamber'>
<result xmlns='urn:xmpp:mam:tmp' queryid='f27' id='28482-98726-73623'>
<forwarded xmlns='urn:xmpp:forward:0'>
<delay xmlns='urn:xmpp:delay' stamp='2010-07-10T23:08:25Z'/>
<message to='juliet#capulet.lit/balcony'
from='romeo#montague.lit/orchard'
type='chat'>
<body>Call me but love, and I'll be new baptized; Henceforth I never will be Romeo.</body>
</message>
</forwarded>
</result>
</message>
I got:
<message id='aeb213' to='juliet#capulet.lit/chamber'>
<result xmlns='urn:xmpp:mam:tmp' queryid='f27' id='28482-98726-73623'>
</result>
</message>
In SMACK Logs I got full message.
It looks like your code
ProviderManager pm = ProviderManager.getInstance();
pm.addExtensionProvider("result", "urn:xmpp:mam:tmp", new Archive313.Archive313Provider());
never calls. Check this. Commonly, this code must be placed in static block of main class which working with xmpp lib.
To add any extension you have to do three things.
Create a custom extension class extending Extension/ExtensionElement.
Create an extension provider extending ExtensionProvider.
Add custom extension provider to provider manager.
Note : Extension provider will parse your extension from packet (XML) as per your requirement (onParse() method of provider). Every custom extension have to parsed manually and need to add custom provider to provider manager.
Related
this is my first question here. do not judge strictly:) I'm parsing a file with the dim extension of the xml format, in fact, so I chose SAXparser. the problem is probably architectural or I don’t know how to call it correctly. in general, if you describe: there is a list of tags that I need to pull out and, in accordance with them, create objects, assign values to their fields, which the parser will pull out as strings from certain tags. in accordance with the tags I need, I have implemented classes with which I need to create objects in the startElement method, after that in endElement I need to assign the appropriate strings to this object. The crux of the problem is that I can't figure out how I can avoid a lot of code in the SaxParserHandler class, including a lot of if/else in the startElement and endElement methods. tried to use enum and factory pattern, but all in vain. example of my current code in SaxParserHandler:
public class SaxParserHandler extends DefaultHandler {
private Dataset_Id dataset_id = null;
private StringBuilder data = null;
private Dataset_Frame dataset_frame = null;
private String MetadataId = "Metadata_Id";
private String dataset_name_tag = "DATASET_NAME";
private String dataset_frame_tag = "Dataset_Frame";
private Vertex vertex = null;
private List<Vertex> vertices = null;
private String vertex_tag = "Vertex";
private String FRAME_LON = "FRAME_LON";
private String FRAME_LAT = "FRAME_LAT";
private String FRAME_X = "FRAME_X";
private String FRAME_Y = "FRAME_Y";
private String FRAME_ROW = "FRAME_ROW";
private String FRAME_COL = "FRAME_COL";
private Source_Information source_information = null;
private Scene_Source scene_source = null;
private String source_info_tag = "Source_Information";
private String source_id_tag = "SOURCE_ID";
private String scene_source_tag = "Scene_Source";
private String imaging_date_tag = "IMAGING_DATE";
private String imaging_time_tag = "IMAGING_TIME";
private String mission_tag = "MISSION";
private String mission_index_tag = "MISSION_INDEX";
private String instrument_tag = "INSTRUMENT";
private String satellite_incidence_angle_tag = "SATELLITE_INCIDENCE_ANGLE";
private String viewing_angle_tag = "VIEWING_ANGLE";
private String sun_azimuth_tag = "SUN_AZIMUTH";
private String sun_elevation_tag = "SUN_ELEVATION";
private String theoretical_resolution_tag = "THEORETICAL_RESOLUTION";
private Coordinate_Reference_System coordinate_reference_system = null;
private Horizontal_CS horizontal_cs = null;
private String Coordinate_Reference_System_Tag = "Coordinate_Reference_System";
private String Horizontal_CS_Tag = "Horizontal_CS";
private String HORIZONTAL_CS_CODE_TAG = "HORIZONTAL_CS_CODE";
private String HORIZONTAL_CS_TYPE_TAG = "HORIZONTAL_CS_TYPE";
private String HORIZONTAL_CS_NAME_TAG = "HORIZONTAL_CS_NAME";
private Production production = null;
private Production_Facility production_facility = null;
private String Production_Tag = "Production";
private String DATASET_PRODUCTION_DATE_TAG = "DATASET_PRODUCTION_DATE";
private String PRODUCT_TYPE_TAG = "PRODUCT_TYPE";
private String PRODUCT_INFO_TAG = "PRODUCT_INFO";
private String JOB_ID_TAG = "JOB_ID";
private String Production_Facility_Tag = "Production_Facility";
private String SOFTWARE_NAME_TAG = "SOFTWARE_NAME";
private String SOFTWARE_VERSION_TAG = "SOFTWARE_VERSION";
private String PROCESSING_CENTER_TAG = "PROCESSING_CENTER";
private Raster_Encoding raster_encoding = null;
private String Raster_Encoding_Tag = "Raster_Encoding";
private String DATA_TYPE_TAG = "DATA_TYPE";
private String NBITS_TAG = "NBITS";
private String BYTEORDER_TAG = "BYTEORDER";
private String BANDS_LAYOUT_TAG = "BANDS_LAYOUT";
private Data_Processing data_processing = null;
private String Data_Processing_Tag = "Data_Processing";
private String PROCESSING_LEVEL_TAG = "PROCESSING_LEVEL";
private String GEOMETRIC_PROCESSING_TAG = "GEOMETRIC_PROCESSING";
private String RADIOMETRIC_PROCESSING_TAG = "RADIOMETRIC_PROCESSING";
private Data_Access data_access = null;
private Data_File_List data_file_list = null;
private String Data_Access_Tag = "Data_Access";
private String DATA_FILE_FORMAT_TAG = "DATA_FILE_FORMAT";
private String DATA_FILE_ORGANISATION_TAG = "DATA_FILE_ORGANISATION";
private String Data_File_List_Tag = "Data_File_List";
private String DATA_FILE_PATH_TAG = "DATA_FILE_PATH";
private Image_Display image_display = null;
private Band_Display_Order band_display_order = null;
private String Image_Display_Tag = "Image_Display";
private String Band_Display_Order_Tag = "Band_Display_Order";
private String RED_CHANNEL_TAG = "RED_CHANNEL";
private String GREEN_CHANNEL_TAG = "GREEN_CHANNEL";
private String BLUE_CHANNEL_TAG = "BLUE_CHANNEL";
private Data_Strip data_strip = null;
private Data_Strip_Identification data_strip_identification = null;
private Time_Stamp time_stamp = null;
private Ephemeris ephemeris = null;
private String Data_Strip_Tag = "Data_Strip";
private String Data_Strip_Identification_Tag = "Data_Strip_Identification";
private String DATA_STRIP_ID_TAG = "DATA_STRIP_ID";
private String SEGMENT_ID_TAG = "SEGMENT_ID";
private String Time_Stamp_Tag = "Time_Stamp";
private String REFERENCE_BAND_TAG = "REFERENCE_BAND";
private String REFERENCE_TIME_TAG = "REFERENCE_TIME";
private String REFERENCE_LINE_TAG = "REFERENCE_LINE";
private String LINE_PERIOD_TAG = "LINE_PERIOD";
private String Ephemeris_Tag = "Ephemeris";
private String SATELLITE_ALTITUDE_TAG = "SATELLITE_ALTITUDE";
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase(dataset_name_tag))
dataset_id = new Dataset_Id();
else if (qName.equalsIgnoreCase(dataset_frame_tag)) {
dataset_frame = new Dataset_Frame();
} else if (qName.equals(vertex_tag)) {
vertex = new Vertex();
if (vertices == null)
vertices = new ArrayList<>();
} else if (qName.equalsIgnoreCase(source_info_tag)) {
source_information = new Source_Information();
} else if (qName.equals(scene_source_tag)) {
scene_source = new Scene_Source();
} else if (qName.equals(Coordinate_Reference_System_Tag)) {
coordinate_reference_system = new Coordinate_Reference_System();
} else if (qName.equals(Horizontal_CS_Tag)) {
horizontal_cs = new Horizontal_CS();
} else if (qName.equals(Production_Tag)) {
production = new Production();
} else if (qName.equals(Production_Facility_Tag)) {
production_facility = new Production_Facility();
} else if (qName.equals(Raster_Encoding_Tag)) {
raster_encoding = new Raster_Encoding();
} else if (qName.equals(Data_Processing_Tag)) {
data_processing = new Data_Processing();
} else if (qName.equals(Data_Access_Tag)) {
data_access = new Data_Access();
} else if (qName.equals(Data_File_List_Tag)) {
data_file_list = new Data_File_List();
}else if (qName.equals(Image_Display_Tag)) {
image_display = new Image_Display();
}else if (qName.equals(Band_Display_Order_Tag)) {
band_display_order = new Band_Display_Order();
}else if (qName.equals(Data_Strip_Tag)){
data_strip = new Data_Strip();
}else if (qName.equals(Data_Strip_Identification_Tag)) {
data_strip_identification = new Data_Strip_Identification();
}else if (qName.equals(Time_Stamp_Tag)) {
time_stamp = new Time_Stamp();
}else if (qName.equals(Ephemeris_Tag)) {
ephemeris = new Ephemeris();
}
data = new StringBuilder();
}
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals(dataset_name_tag)) {
dataset_id.setDataset_name(data.toString());
} else if (qName.equals(FRAME_LON)) {
vertex.setFRAME_LON(data.toString());
} else if (qName.equals(FRAME_LAT)) {
vertex.setFRAME_LAT(data.toString());
} else if (qName.equals(FRAME_X)) {
vertex.setFRAME_X(data.toString());
} else if (qName.equals(FRAME_Y)) {
vertex.setFRAME_Y(data.toString());
} else if (qName.equals(FRAME_ROW)) {
vertex.setFRAME_ROW(data.toString());
} else if (qName.equals(FRAME_COL)) {
vertex.setFRAME_COL(data.toString());
} else if (qName.equals(vertex_tag)) {
vertices.add(vertex);
} else if (qName.equals(dataset_frame_tag)) {
dataset_frame.setDataset_Frame(vertices);
} else if (qName.equals(source_id_tag)) {
source_information.setSource_id(data.toString());
} else if (qName.equals(imaging_date_tag)) {
scene_source.setIMAGING_DATE(data.toString());
} else if (qName.equals(imaging_time_tag)) {
scene_source.setIMAGING_TIME(data.toString());
} else if (qName.equals(mission_tag)) {
scene_source.setMISSION(data.toString());
} else if (qName.equals(mission_index_tag)) {
scene_source.setMISSION_INDEX(data.toString());
} else if (qName.equals(instrument_tag)) {
scene_source.setINSTRUMENT(data.toString());
} else if (qName.equals(satellite_incidence_angle_tag)) {
scene_source.setSATELLITE_INCIDENCE_ANGLE(data.toString());
} else if (qName.equals(viewing_angle_tag)) {
scene_source.setVIEWING_ANGLE(data.toString());
} else if (qName.equals(sun_azimuth_tag)) {
scene_source.setSUN_AZIMUTH(data.toString());
} else if (qName.equals(sun_elevation_tag)) {
scene_source.setSUN_ELEVATION(data.toString());
} else if (qName.equals(theoretical_resolution_tag)) {
scene_source.setTHEORETICAL_RESOLUTION(data.toString());
} else if (qName.equals(source_info_tag)) {
source_information.setScene_source(scene_source);
} else if (qName.equals(HORIZONTAL_CS_TYPE_TAG)) {
horizontal_cs.setHORIZONTAL_CS_TYPE(data.toString());
} else if (qName.equals(HORIZONTAL_CS_NAME_TAG)) {
horizontal_cs.setHORIZONTAL_CS_NAME(data.toString());
} else if (qName.equals(HORIZONTAL_CS_CODE_TAG)) {
horizontal_cs.setHORIZONTAL_CS_CODE(data.toString());
} else if (qName.equals(Horizontal_CS_Tag)) {
coordinate_reference_system.setHorizontal_cs(horizontal_cs);
} else if (qName.equals(DATASET_PRODUCTION_DATE_TAG)) {
production.setDATASET_PRODUCTION_DATE(data.toString());
} else if (qName.equals(PRODUCT_TYPE_TAG)) {
production.setPRODUCT_TYPE(data.toString());
} else if (qName.equals(PRODUCT_INFO_TAG)) {
production.setPRODUCT_INFO(data.toString());
} else if (qName.equals(JOB_ID_TAG)) {
production.setJOB_ID(data.toString());
} else if (qName.equals(SOFTWARE_NAME_TAG)) {
production_facility.setSOFTWARE_NAME(data.toString());
} else if (qName.equals(SOFTWARE_VERSION_TAG)) {
production_facility.setSOFTWARE_VERSION(data.toString());
} else if (qName.equals(PROCESSING_CENTER_TAG)) {
production_facility.setPROCESSING_CENTER(data.toString());
} else if (qName.equals(Production_Tag)) {
production.setProduction_facility(production_facility);
} else if (qName.equals(DATA_TYPE_TAG)) {
raster_encoding.setDATA_TYPE(data.toString());
} else if (qName.equals(NBITS_TAG)) {
raster_encoding.setNBITS(data.toString());
} else if (qName.equals(BYTEORDER_TAG)) {
raster_encoding.setBYTEORDER(data.toString());
} else if (qName.equals(BANDS_LAYOUT_TAG)) {
raster_encoding.setBANDS_LAYOUT(data.toString());
} else if (qName.equals(PROCESSING_LEVEL_TAG)) {
data_processing.setPROCESSING_LEVEL(data.toString());
} else if (qName.equals(GEOMETRIC_PROCESSING_TAG)) {
data_processing.setGEOMETRIC_PROCESSING(data.toString());
} else if (qName.equals(RADIOMETRIC_PROCESSING_TAG)) {
data_processing.setRADIOMETRIC_PROCESSING(data.toString());
} else if (qName.equals(DATA_FILE_FORMAT_TAG)) {
data_access.setDATA_FILE_FORMAT(data.toString());
} else if (qName.equals(DATA_FILE_ORGANISATION_TAG)) {
data_access.setDATA_FILE_ORGANISATION(data.toString());
} else if (qName.equals(DATA_FILE_PATH_TAG)) {
data_file_list.setDATA_FILE_PATH(data.toString());
} else if (qName.equals(Data_File_List_Tag)) {
data_access.setData_file_lists(data_file_list);
}else if (qName.equals(RED_CHANNEL_TAG)) {
band_display_order.setRED_CHANNEL(data.toString());
}else if (qName.equals(GREEN_CHANNEL_TAG)) {
band_display_order.setGREEN_CHANNEL(data.toString());
}else if (qName.equals(BLUE_CHANNEL_TAG)) {
band_display_order.setBLUE_CHANNEL(data.toString());
}else if (qName.equals(Band_Display_Order_Tag)) {
image_display.setBand_display_orders(band_display_order);
}else if (qName.equals(DATA_STRIP_ID_TAG)){
data_strip_identification.setDATA_STRIP_ID(data.toString());
}else if (qName.equals(SEGMENT_ID_TAG)) {
data_strip_identification.setSEGMENT_ID(data.toString());
}else if (qName.equals(Data_Strip_Identification_Tag)) {
data_strip.setData_strip_identification(data_strip_identification);
}else if (qName.equals(REFERENCE_BAND_TAG)) {
time_stamp.setREFERENCE_BAND(data.toString());
}else if (qName.equals(REFERENCE_TIME_TAG)){
time_stamp.setREFERENCE_TIME(data.toString());
}else if (qName.equals(REFERENCE_LINE_TAG)) {
time_stamp.setREFERENCE_LINE(data.toString());
}else if (qName.equals(LINE_PERIOD_TAG)) {
time_stamp.setLINE_PERIOD(data.toString());
}else if (qName.equals(Time_Stamp_Tag)) {
data_strip.setTime_stamp(time_stamp);
}else if (qName.equals(SATELLITE_ALTITUDE_TAG)) {
ephemeris.setSATELLITE_ALTITUDE(data.toString());
}else if (qName.equals(Ephemeris_Tag)) {
data_strip.setEphemerises(ephemeris);
}
}
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
data.append(new String(ch, start, length));
}
Root root = new Root();
public Root getRoot() {
root.setDataset_id(dataset_id);
root.setDataset_frame(dataset_frame);
root.setSource_information(source_information);
root.setCoordinate_reference_systems(coordinate_reference_system);
root.setProductions(production);
root.setRaster_encodings(raster_encoding);
root.setData_processings(data_processing);
root.setData_accesses(data_access);
root.setImage_displays(image_display);
root.setData_strips(data_strip);
return root;
}
}
part of dim file sample
<?xml version="1.0" encoding="ISO-8859-1"?>
<Dimap_Document xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Metadata_Id>
<METADATA_FORMAT version="1.1">DIMAP</METADATA_FORMAT>
</Metadata_Id>
<Dataset_Id>
<DATASET_NAME>KM000604MI_017_MUL_L1G</DATASET_NAME>
<DATASET_TN_PATH href="KM000604MI_017_MUL_L1G_tn.jpg"/>
<DATASET_QL_PATH href="KM000604MI_017_MUL_L1G_ql.jpg"/>
</Dataset_Id>
<Production>
<DATASET_PRODUCER_NAME/>
<DATASET_PRODUCTION_DATE>2015-09-28</DATASET_PRODUCTION_DATE>
<PRODUCT_TYPE/>
</Production>
<Dataset_Use>
<DATASET_CONTENT/>
</Dataset_Use>
<Data_Processing>
<GEOMETRIC_PROCESSING/>
<Processing_Parameter>
<PROC_PARAMETER_DESC>SOFTWARE</PROC_PARAMETER_DESC>
<PROC_PARAMETER_VALUE>Keystone 3.8.9.FINAL.</PROC_PARAMETER_VALUE>
</Processing_Parameter>
</Data_Processing>
<Coordinate_Reference_System>
<GEO_TABLES>EPSG</GEO_TABLES>
<Horizontal_CS>
<HORIZONTAL_CS_CODE>EPSG:32642</HORIZONTAL_CS_CODE>
<HORIZONTAL_CS_TYPE>PROJECTED</HORIZONTAL_CS_TYPE>
<HORIZONTAL_CS_NAME>WGS 84 / UTM zone 42N</HORIZONTAL_CS_NAME>
<Coordinate_Axis>
<AXIS1_NAME>Easting</AXIS1_NAME>
<AXIS2_NAME>Northing</AXIS2_NAME>
<AXIS1_ORIENTATION>EAST</AXIS1_ORIENTATION>
<AXIS2_ORIENTATION>NORTH</AXIS2_ORIENTATION>
</Coordinate_Axis>
<Projection>
<PROJECTION_NAME>UTM zone 42N</PROJECTION_NAME>
<PROJECTION_CODE>EPSG:16042</PROJECTION_CODE>
<Projection_CT_Method>
<PROJECTION_CT_NAME>Transverse Mercator</PROJECTION_CT_NAME>
<PROJECTION_CT_CODE>EPSG:9807</PROJECTION_CT_CODE>
<Projection_Parameters>
<Projection_Parameter>
<PROJECTION_PARAMETER_NAME>Latitude_of_natural_origin</PROJECTION_PARAMETER_NAME>
<PROJECTION_PARAMETER_VALUE unit="DEG">0.0</PROJECTION_PARAMETER_VALUE>
</Projection_Parameter>
<Projection_Parameter>
<PROJECTION_PARAMETER_NAME>Longitude_of_natural_origin</PROJECTION_PARAMETER_NAME>
<PROJECTION_PARAMETER_VALUE unit="DEG">69.0</PROJECTION_PARAMETER_VALUE>
</Projection_Parameter>
<Projection_Parameter>
<PROJECTION_PARAMETER_NAME>Scale_factor_at_natural_origin</PROJECTION_PARAMETER_NAME>
<PROJECTION_PARAMETER_VALUE>0.9996</PROJECTION_PARAMETER_VALUE>
</Projection_Parameter>
<Projection_Parameter>
<PROJECTION_PARAMETER_NAME>False_easting</PROJECTION_PARAMETER_NAME>
<PROJECTION_PARAMETER_VALUE unit="M">500000.0</PROJECTION_PARAMETER_VALUE>
</Projection_Parameter>
<Projection_Parameter>
<PROJECTION_PARAMETER_NAME>False_northing</PROJECTION_PARAMETER_NAME>
<PROJECTION_PARAMETER_VALUE unit="M">0.0</PROJECTION_PARAMETER_VALUE>
</Projection_Parameter>
</Projection_Parameters>
</Projection_CT_Method>
</Projection>
<Geographic_CS>
<GEOGRAPHIC_CS_NAME>WGS 84</GEOGRAPHIC_CS_NAME>
<GEOGRAPHIC_CS_CODE>EPSG:4326</GEOGRAPHIC_CS_CODE>
<Horizontal_Datum>
<HORIZONTAL_DATUM_NAME>World Geodetic System 1984</HORIZONTAL_DATUM_NAME>
<HORIZONTAL_DATUM_CODE>EPSG:6326</HORIZONTAL_DATUM_CODE>
<Ellipsoid>
<ELLIPSOID_NAME>WGS 84</ELLIPSOID_NAME>
<ELLIPSOID_CODE>EPSG:7030</ELLIPSOID_CODE>
<Ellipsoid_Parameters>
<ELLIPSOID_MAJOR_AXIS unit="M">6378137.0</ELLIPSOID_MAJOR_AXIS>
<ELLIPSOID_MINOR_AXIS unit="M">6356752.314245</ELLIPSOID_MINOR_AXIS>
</Ellipsoid_Parameters>
</Ellipsoid>
<Prime_Meridian>
<PRIME_MERIDIAN_NAME>Greenwich</PRIME_MERIDIAN_NAME>
<PRIME_MERIDIAN_CODE>EPSG:8901</PRIME_MERIDIAN_CODE>
<PRIME_MERIDIAN_OFFSET unit="DEG">0.0</PRIME_MERIDIAN_OFFSET>
</Prime_Meridian>
</Horizontal_Datum>
</Geographic_CS>
</Horizontal_CS>
</Coordinate_Reference_System>
If you are open to use third party libraries, you might give Jsoup a try. Jsoup is actually a HTML-parser but is also able to parse XML. It provides IMHO an intuitive and simple selector syntax and API which you can use to get the elements you are interested in.
I am not realy sure what you are trying to achieve and didn't find all the tags from your code in the sample xml you provided. But to give you a simple starting point on how to use Jsoup, please see below snippet where I fetch the
Production DATASET_PRODUCTION_DATE and the Projection_Parameters from the sample xml:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
public class Example2 {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream(new File("path to your xml file"));
Document doc = Jsoup.parse(in, "UTF-8", "", Parser.xmlParser());
String productionDate = doc.selectFirst("Production DATASET_PRODUCTION_DATE").text();
System.out.println("PRODUCTION_DATE: " + productionDate);
Elements projection_Parameters = doc.select("Projection_Parameter");
projection_Parameters.forEach(param -> {
String name = param.selectFirst("PROJECTION_PARAMETER_NAME").text();
String value = param.selectFirst("PROJECTION_PARAMETER_VALUE").text();
System.out.printf("NAME: %s, VALUE: %s %n", name, value);
});
}
}
output:
PRODUCTION_DATE: 2015-09-28
NAME: Latitude_of_natural_origin, VALUE: 0.0
NAME: Longitude_of_natural_origin, VALUE: 69.0
NAME: Scale_factor_at_natural_origin, VALUE: 0.9996
NAME: False_easting, VALUE: 500000.0
NAME: False_northing, VALUE: 0.0
Instead of printing to console you could of course create directly your POJOs. If interested get Jsoup from Maven central
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.15.3</version>
</dependency>
Currently I'm doing a program which retrieve the Azure Client ID and Secret Value through key-vault.
Below is the logic that my friend and I make to get the value, my question is how can I take the value that I got in the static void main and pass to another class for use? I had no idea how to reuse the value I get in another class. Please teach me.
public class SecretReceiver {
private static SecretClient secretClient;
public static final String AZURE_CLIENT_ID="AZURE_CLIENT_ID";
public static final String AZURE_CLIENT_SECRET="AZURE_CLIENT_SECRET";
public static final String AZURE_TENANT_ID="AZURE_TENANT_ID";
public static final String AZURE_KEY_VAULT_NAME="AZURE_KEY_VAULT_NAME";
private static final String KEY_VAULT_URL = "https://%s.vault.azure.net";
private static void secretReceiverBuilder() {
if (secretClient == null) {
String keyVaultUrl = String.format(KEY_VAULT_URL, getProperty(AZURE_KEY_VAULT_NAME, ""));
secretClient = new SecretClientBuilder()
.vaultUrl(keyVaultUrl)
.credential(new ClientSecretCredentialBuilder()
.clientId(getProperty(AZURE_CLIENT_ID, ""))
.clientSecret(getProperty(AZURE_CLIENT_SECRET, ""))
.tenantId(getProperty(AZURE_TENANT_ID, ""))
.build())
.buildClient();
}
}
public static void loadConfigFileAndSetEnv(String filePath) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath))))) {
String line = null;
while ((line = reader.readLine()) != null) {
String[] split = line.split("=");
if (split.length > 1) {
String key = split[0].trim();
String value = split[1].trim();
if (key.contains(AZURE_CLIENT_ID)) {
System.setProperty(AZURE_CLIENT_ID, value);
continue;
}
if (key.contains(AZURE_CLIENT_SECRET)) {
System.setProperty(AZURE_CLIENT_SECRET, value);
continue;
}
if (key.contains(AZURE_TENANT_ID)) {
System.setProperty(AZURE_TENANT_ID, value);
continue;
}
if (key.contains(AZURE_KEY_VAULT_NAME)) {
System.setProperty(AZURE_KEY_VAULT_NAME, value);
}
}
}
} catch (Exception e) {
log.error("Load file : {} error.", filePath, e);
}
}
public static String getProperty(String key, String defaultValue) {
String value = System.getProperty(key);
if (StringUtils.isBlank(value)) {
value = System.getenv(key);
}
return StringUtils.isBlank(value) ? defaultValue : value;
}
public static void main() throws Exception {
//getUatAKV();
loadConfigFileAndSetEnv("C:script\\key_vault.conf");
String username = getSecretByKey("client-secret-name");
String secret = getSecretByKey("client-secret");
System.out.println("This is client id: " + username);
System.out.println("This is client secret: " + secret);
}
public static String getSecretByKey(String name) {
if (secretClient == null) {
secretReceiverBuilder();
}
return secretClient.getSecret(name).getValue();
}
Try the following code:
// Create static variable in a Class
public class Global {
public static String USER_NAME ="";
public static String SECRET ="";
}
// Set the value in your main function
String username = getSecretByKey("client-secret-name");
String secret = getSecretByKey("client-secret");
Global.USER_NAME = username;
Global.SECRET = secret;
// Get value in another class
System.out.println("This is client id: " + Global.USER_NAME);
System.out.println("This is client secret: " + Global.SECRET);
I am new to Jsoup parsing and I want to get the list of all the companies on this page: https://angel.co/companies?company_types[]=Startup
Now, a way to do this is actually to inspect the page with the div tags relevant to what I need.
However, when I call the method :
Document doc = Jsoup.connect("https://angel.co/companies?company_types[]=Startup").get();
System.out.println(doc.html());
Firstly I cannot even find those DIV tags in my consol html output, (the ones which are supposed to give a list of the companies)
Secondly, even if I did find it, how can I find a certain Div element with class name :
div class=" dc59 frw44 _a _jm"
Pardon the jargon, I have no idea how to go through this.
The data are not embedded in the page but they are retrieved using subsequent API calls :
a POST https://angel.co/company_filters/search_data to get an ids array & a token named hexdigest
a GET https://angel.co/companies/startups to retrieve company data using the output from the previous request
The above is repeated for each page (thus a new token & a list of ids are needed for each page). This process can be seen using Chrome dev console in Network tabs.
The first POST request gives JSON output but the second request (GET) gives HTML data in a property of a JSON object.
The following extracts the company filter :
private static CompanyFilter getCompanyFilter(final String filter, final int page) throws IOException {
String response = Jsoup.connect("https://angel.co/company_filters/search_data")
.header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
.header("X-Requested-With", "XMLHttpRequest")
.data("filter_data[company_types][]=", filter)
.data("sort", "signal")
.data("page", String.valueOf(page))
.userAgent("Mozilla")
.ignoreContentType(true)
.post().body().text();
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
return gson.fromJson(response, CompanyFilter.class);
}
Then the following extracts companies :
private static List<Company> getCompanies(final CompanyFilter companyFilter) throws IOException {
List<Company> companies = new ArrayList<>();
URLConnection urlConn = new URL("https://angel.co/companies/startups?" + companyFilter.buildRequest()).openConnection();
urlConn.setRequestProperty("User-Agent", "Mozilla");
urlConn.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
HtmlContainer htmlObj = new Gson().fromJson(reader, HtmlContainer.class);
Element doc = Jsoup.parse(htmlObj.getHtml());
Elements data = doc.select("div[data-_tn]");
if (data.size() > 0) {
for (int i = 2; i < data.size(); i++) {
companies.add(new Company(data.get(i).select("a").first().attr("title"),
data.get(i).select("a").first().attr("href"),
data.get(i).select("div.pitch").first().text()));
}
} else {
System.out.println("no data");
}
return companies;
}
The main function :
public static void main(String[] args) throws IOException {
int pageCount = 1;
List<Company> companies = new ArrayList<>();
for (int i = 0; i < 10; i++) {
System.out.println("get page n°" + pageCount);
CompanyFilter companyFilter = getCompanyFilter("Startup", pageCount);
pageCount++;
System.out.println("digest : " + companyFilter.getDigest());
System.out.println("count : " + companyFilter.getTotalCount());
System.out.println("array size : " + companyFilter.getIds().size());
System.out.println("page : " + companyFilter.getpage());
companies.addAll(getCompanies(companyFilter));
if (companies.size() == 0) {
break;
} else {
System.out.println("size : " + companies.size());
}
}
}
Company, CompanyFilter & HtmlContainer are model class :
class CompanyFilter {
#SerializedName("ids")
private List<Integer> mIds;
#SerializedName("hexdigest")
private String mDigest;
#SerializedName("total")
private String mTotalCount;
#SerializedName("page")
private int mPage;
#SerializedName("sort")
private String mSort;
#SerializedName("new")
private boolean mNew;
public List<Integer> getIds() {
return mIds;
}
public String getDigest() {
return mDigest;
}
public String getTotalCount() {
return mTotalCount;
}
public int getpage() {
return mPage;
}
private String buildRequest() {
String out = "total=" + mTotalCount + "&";
out += "sort=" + mSort + "&";
out += "page=" + mPage + "&";
out += "new=" + mNew + "&";
for (int i = 0; i < mIds.size(); i++) {
out += "ids[]=" + mIds.get(i) + "&";
}
out += "hexdigest=" + mDigest + "&";
return out;
}
}
private static class Company {
private String mLink;
private String mName;
private String mDescription;
public Company(String name, String link, String description) {
mLink = link;
mName = name;
mDescription = description;
}
public String getLink() {
return mLink;
}
public String getName() {
return mName;
}
public String getDescription() {
return mDescription;
}
}
private static class HtmlContainer {
#SerializedName("html")
private String mHtml;
public String getHtml() {
return mHtml;
}
}
The full code is also available here
This is the service class.I am creating a XML file by reading value from database. Code is using three more pojo classes. Mt700, Header and Swift details. MT700 is main class for Header and swift details. Problem is I am able to store everything one time. Doesn't matter how many rows of data I have when the file get generated with one record it has only one header and one swift details. How can I make this work in loop? I think I have to use list but I am not sure how to use it to make it work.
public void generateEliteExtracts(int trdCustomerKy, Date lastRunDate, Date currentDate) throws TradeException {
FileOutputStream fout = null;
try {
MT700 mt700 = getMT700(trdCustomerKy,lastRunDate,currentDate);
if (null != mt700){
StringBuffer fileName = new StringBuffer(1024);
fileName.append(mConfiguration.getOutDirectory()).append(MT700_MSGTYPE)
.append(DOT).append(mConfiguration.getOutputFileExtn());
smLog.debug("Generated Extract for BankRef" + fileName.toString());
mTracer.log("Generated Extract for BankRef" + fileName.toString());
File xmlFile = new File(fileName.toString());
fout = new FileOutputStream(xmlFile);
fout.write(MT700_XMLHEADER.getBytes());
JAXBContext jaxbContext = JAXBContext.newInstance(MT700.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, ENCODING_ASCII);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.FALSE);
marshaller.setProperty("com.sun.xml.internal.bind.xmlDeclaration", Boolean.FALSE);
marshaller.marshal(mt700, fout);
IOUtils.closeQuietly(fout);
}
}catch(
Exception ex)
{
smLog.error("Caught unexpected error while creating extracts. ", ex);
throw new TradeException("Caught unexpected error while creating extracts.", ex);
} finally
{
IOUtils.closeQuietly(fout);
}
}
private MT700 getMT700(int trdCustomerKy, Date lastRunDate, Date currentDate) throws TradeException {
MT700 mt700 = new MT700();
AbInBevEliteExtractDAO dao = new AbInBevEliteExtractDAO(mConnection);
CompanyCodesHelper ccHelper = new CompanyCodesHelper(mConnection);
String cifCodes = ccHelper.getDescription(trdCustomerKy, "CIF Codes", "CIF Codes");
if (false == TradeUtil.isStringNull(cifCodes)) {
mTracer.log("Fetching records for CIFs: " + StringUtils.replace(cifCodes, PIPE, COMMA));
String[] codes = StringUtils.split(cifCodes, PIPE);
List<ExportAdvicesData> exportList = dao.getExportAdvices(trdCustomerKy, lastRunDate, currentDate, codes);
for (int i = 0; i < exportList.size(); i++) {
ExportAdvicesData exportData = exportList.get(i);
if ("XXLC".equalsIgnoreCase(exportData.getDocAcronym())) {
Header header = new Header();
header.setMessageType("N");
header.setVersionNo("1.0");
header.setRevisionNo("00");
header.setDocumentDate(DateUtil.formatDate(new Date(), DATE_FORMAT_YYYY_MM_DD_HHMMSS));
header.setBankId("BOA" + StringUtils.substring(exportData.getCustRef(), 0, 4));
header.setCustId("XOM");
SwiftDetails swiftTest = new SwiftDetails();
header.setDocumentType(MT700_MSGTYPE);
SwiftParserBankDocs parser = new SwiftParserBankDocs(exportData.getDocumentContent());
String bankRef = parser.getTagValue("21");
String custRef = parser.getTagValue("20");
if (TradeUtil.isStringNull(bankRef)) {
header.setCustRefNo("NONREF");
header.setBankRefNo(custRef);
} else {
header.setCustRefNo(custRef);
header.setBankRefNo(bankRef);
}
swiftTest.setTAG_27("1/1");
swiftTest.setTAG_20(custRef);
swiftTest.setTAG_23(EMPTY_STRING);
String issueDate = parser.getTagValue("31C");
swiftTest.setTAG_31C(getDateInYYMMDD(issueDate));
swiftTest.setTAG_40E("UCP LATEST VERSION");
String datePlaceOfExpiry = parser.getTagValue("31D");
swiftTest.setTAG_31D(getFormattedDatePlaceOfExpiry(datePlaceOfExpiry));
swiftTest.setTAG_50(parser.getTagValue("50"));
swiftTest.setTAG_59(parser.getTagValue("59"));
swiftTest.setTAG_32B(getCurrencyCdAmount(parser.getTagValue("32B")));
if (false == TradeUtil.isStringNull(exportData.getPositiveTolerance())) {
swiftTest.setTAG_39A(
exportData.getPositiveTolerance() + "/" + exportData.getPositiveTolerance());
} else {
swiftTest.setTAG_39A(EMPTY_STRING);
}
swiftTest.setTAG_39B(EMPTY_STRING);
swiftTest.setTAG_39C(EMPTY_STRING);
swiftTest.setTAG_41A(parser.getTagValue("41D"));
String tag42A = parser.getTagValue("42A");
swiftTest.setTAG_42A(tag42A);
if (TradeUtil.isStringNull(tag42A)) {
swiftTest.setTAG_42A(parser.getTagValue("42D"));
}
swiftTest.setTAG_42C(parser.getTagValue("42C"));
swiftTest.setTAG_42M(parser.getTagValue("42M"));
swiftTest.setTAG_42P(parser.getTagValue("42P"));
swiftTest.setTAG_43P(parser.getTagValue("43P"));
swiftTest.setTAG_43T(parser.getTagValue("43T"));
if (!(TradeUtil.isStringNull(parser.getTagValue("44A")))) {
swiftTest.setTAG_44A(parser.getTagValue("44A"));
}
if (!(TradeUtil.isStringNull(parser.getTagValue("44B")))) {
swiftTest.setTAG_44B(parser.getTagValue("44B"));
}
if (!(TradeUtil.isStringNull(parser.getTagValue("44E")))) {
swiftTest.setTAG_44E(parser.getTagValue("44E"));
}
if (!(TradeUtil.isStringNull(parser.getTagValue("44F")))) {
swiftTest.setTAG_44F(parser.getTagValue("44F"));
}
Date latestShipDate = exportData.getLatestShipDate();
if (null != latestShipDate) {
swiftTest.setTAG_44C(DateUtil.formatDate(latestShipDate, DATE_FORMAT_YYMMDD));
} else {
swiftTest.setTAG_44C(EMPTY_STRING);
}
swiftTest.setTAG_44D(parser.getTagValue("44D"));
swiftTest.setTAG_45A(parser.getTagValue("45") + BLANK_STRING + parser.getTagValue("45A")
+ BLANK_STRING + parser.getTagValue("45B"));
swiftTest.setTAG_46A(parser.getTagValue("46") + BLANK_STRING + parser.getTagValue("46A")
+ BLANK_STRING + parser.getTagValue("46B"));
swiftTest.setTAG_47A(parser.getTagValue("47") + BLANK_STRING + parser.getTagValue("47A")
+ BLANK_STRING + parser.getTagValue("47B"));
swiftTest.setTAG_71B(parser.getTagValue("71B"));
swiftTest.setTAG_48(parser.getTagValue("48"));
swiftTest.setTAG_49(parser.getTagValue("49"));
swiftTest.setTAG_50B(EMPTY_STRING);
swiftTest.setTAG_51A(EMPTY_STRING);
String issuingBank = parser.getAddress(SwiftParserBankDocs.ISSUING_BANK);
if (TradeUtil.isStringNull(issuingBank)) {
String errorMsg = "Issuing Bank address not found in bankdoc text, SWIFT content is possibly invalid, skipped processed record: "
+ exportData.getCustRef();
smLog.error(errorMsg);
mTracer.log("ERROR: " + errorMsg);
}
issuingBank = StringUtils.replace(issuingBank, CRLF, BLANK_STRING + CRLF);
swiftTest.setTAG_52A(issuingBank);
swiftTest.setTAG_53A(parser.getTagValue("53A"));
swiftTest.setTAG_78(parser.getTagValue("78"));
swiftTest.setTAG_57A(parser.getAddress("TO:"));
swiftTest.setTAG_72(parser.getTagValue("72"));
swiftTest.setTAG_40A(parser.getTagValue("40B"));
if (parser.is710Advice()) {
swiftTest.setTAG_20(parser.getTagValue("21"));
}
mt700.setSwift700(swiftTest);
mt700.setHeader(header);
} else if ("XAMD".equalsIgnoreCase(exportData.getDocAcronym())) {
Header header = new Header();
header.setMessageType("N");
header.setVersionNo("1.0");
header.setRevisionNo("00");
header.setDocumentDate(DateUtil.formatDate(new Date(), DATE_FORMAT_YYYY_MM_DD_HHMMSS));
header.setBankId("BOA" + StringUtils.substring(exportData.getCustRef(), 0, 4));
header.setCustId("XOM");
SwiftDetails swift = new SwiftDetails();
header.setDocumentType(MT707_MSGTYPE);
SwiftParserBankDocs parser = new SwiftParserBankDocs(exportData.getDocumentContent());
String custRef = parser.getTagValue("20");
String bankRef = parser.getTagValue("23");
if (TradeUtil.isStringNull(bankRef)) {
header.setBankRefNo("NONREF");
} else {
header.setBankRefNo(bankRef);
}
header.setCustRefNo(custRef);
swift.setTAG_20(custRef);
swift.setTAG_21(parser.getTagValue("21"));
swift.setTAG_23(EMPTY_STRING);
String issuingBank = parser.getAddress(SwiftParserBankDocs.ISSUING_BANK);
if (TradeUtil.isStringNull(issuingBank)) {
String errorMsg = "Issuing Bank address not found in bankdoc text, SWIFT content is possibly invalid, skipped processed record: "
+ exportData.getCustRef();
smLog.error(errorMsg);
mTracer.log("ERROR: " + errorMsg);
swift.setTAG_52A(EMPTY_STRING);
} else {
issuingBank = StringUtils.replace(issuingBank, CRLF, BLANK_STRING + CRLF);
swift.setTAG_52A(issuingBank);
}
swift.setTAG_31C(getDateInYYMMDD(parser.getTagValue("31C")));
swift.setTAG_30(getDateInYYMMDD(parser.getTagValue("30")));
swift.setTAG_26E(parser.getTagValue("26E"));
swift.setTAG_59(parser.getTagValue("59"));
swift.setTAG_31E(getDateInYYMMDD(parser.getTagValue("31E")));
swift.setTAG_79(parser.getTagValue("79"));
swift.setTAG_72(parser.getTagValue("72"));
swift.setTAG_32B(getCurrencyCdAmount(parser.getTagValue("32B")));
swift.setTAG_33B(getCurrencyCdAmount(parser.getTagValue("33B")));
swift.setTAG_34B(getCurrencyCdAmount(parser.getTagValue("34B")));
swift.setTAG_39A(parser.getTagValue("39A"));
swift.setTAG_39B(parser.getTagValue("39B"));
swift.setTAG_39C(parser.getTagValue("39C"));
swift.setTAG_44A(parser.getTagValue("44A"));
swift.setTAG_44B(parser.getTagValue("44B"));
swift.setTAG_44C(parser.getTagValue("44C"));
swift.setTAG_44D(parser.getTagValue("44D"));
swift.setTAG_44E(parser.getTagValue("44E"));
swift.setTAG_44F(parser.getTagValue("44F"));
mt700.setHeader(header);
mt700.setSwift700(swift);
}
}
}
return mt700;
}
This is MT700 POJO class. In this class I am calling header and swift details pojo classes.
#XmlRootElement(name = "MT700")
public class MT700 implements Serializable
{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
private Header header;
private SwiftDetails swift700;
private String version = "1.0";
public Header getHeader()
{
return header;
}
#XmlElement(name = "Header")
public void setHeader(Header header)
{
this.header = header;
}
/**
* #return the swift700
*/
public SwiftDetails getSwift700()
{
return swift700;
}
#XmlElement(name = "Swift_Details_700")
public void setSwift700(SwiftDetails swift700)
{
this.swift700 = swift700;
}
public String getVersion()
{
return version;
}
#XmlAttribute(name = "Version")
public void setVersion(String version)
{
this.version = version;
}
}
This is Header class. I class similar to like this which has tags and that is swift details
#XmlRootElement(name = "Header")
#XmlType(propOrder = { "documentType", "messageType", "versionNo",
"revisionNo", "documentDate", "bankId", "custId", "custRefNo",
"bankRefNo" })
public class Header implements Serializable
{
private static final long serialVersionUID = 1L;
private String documentType;
private String messageType;
private String versionNo;
private String revisionNo;
private String documentDate;
private String bankId;
private String custId;
private String custRefNo;
private String bankRefNo;
I am not adding getter and setter for this class to make the post look simple
You are creating one MT700 instance and then in this loop, you are reassigning the header and swift fields each time through the loop:
MT700 mt700 = new MT700();
for (int i = 0; i < exportList.size(); i++) {
...
mt700.setHeader(header);
mt700.setSwift700(swift);
}
This means that the document you are outputting contains just the last header/swift returned from the database query.
You need to make one or more of these three into a list of some sort. Either your MT700 contains a list of headers and swifts, or more likely you want to have a list of MT700s each with one header and one swift.
In other words, you want to have a fourth type that will be the actual root of your XML document. That element will contain one MT700 element for each row found by the query. Each MT700 element will have a header element and a swift element.
So, more specifically, here is what you want to do:
#XmlRootElement
class MT700s {
#XmlElement(name = "MT700")
private List<MT700> mt700s = new ArrayList<>();
public List<MT700> getMT700s() { return mt700s; }
// Etc.
}
MT700s mt700s = new MT700s();
for (int i = 0; i < exportList.size(); i++) {
MT700 mt700 = new MT700();
...
mt700.setHeader(header);
mt700.setSwift700(swift);
mt700s.getMT700s().add(mt700);
}
client1 can send txt message to client2 using
connection.getChatManager().createChat(to, this).sendMessage(message);
How to send other kind of message: like INFO message ? (client1 to client2) ?
Because I want, INFO message should not be displayed in the chat window....is it possible ? using smack, smackx library.
Many Thanks.
What you want do do here is to add an extension to your text message. Here is a rough guide.
Chat chat = connection.getChatManager().createChat(to, this);
Message message = new Message(to, Message.Type.chat);
message.setBody("hello");
message.setProperty(prop0, val0);
message.setProperty(prop1, val1);
chat.sendMessage(message)
The properties are carried in a separate namespace (use toXML() to look at it) and will not appear in the chat window. On the 'other side', the applications uses getProperty() to retrieve the value.
If you do not want key/value pairs, but structured data, use addExtension() in the message body. This is a little more complicated because you basically have to extend PacketExtension, provide your own namespace. You might even have to write a PacketExtensionProvider.
Here is the example for message extension.
The basic XML structure of the XMPP protocol is:
<message
from='sender_jid'
to='receiver_jid'
type='message_type'>
<body> content </body>
</message>
The process of sending messages:
//build chat
Chat chat = chatManager.createChat("jid");
//build extension
UserInfo4XMPP userInfo4XMPP = new UserInfo4XMPP();
userInfo4XMPP.setNameText("userx");
userInfo4XMPP.setUrlText("http://www.liaoku.org/");
//build message
Message message = new Message();
message.setBody("hello");
message.addExtension(userInfo4XMPP);// add the extension
//send
chat.sendMessage(message);
The UserInfo4XMPP is defined as:
import org.jivesoftware.smack.packet.ExtensionElement;
public class UserInfo4XMPP implements ExtensionElement{
private String elementName = "userinfo";
private String nameElement = "name";
private String urlElement = "url";
private String nameText = "";
private String urlText = "";
#Override
public String getElementName() {
return elementName;
}
#Override
public CharSequence toXML() {
StringBuilder sb = new StringBuilder();
sb.append("<");
sb.append(elementName);
sb.append(">");
sb.append("<");
sb.append(nameElement);
sb.append(">");
sb.append(nameText);
sb.append("</");
sb.append(nameElement);
sb.append(">");
sb.append("<");
sb.append(urlElement);
sb.append(">");
sb.append(urlText);
sb.append("</");
sb.append(urlElement);
sb.append(">");
sb.append("</");
sb.append(elementName);
sb.append(">");
return sb.toString();
}
#Override
public String getNamespace() {
return "";
}
public String getNameText() {
return nameText;
}
public void setNameText(String nameText) {
this.nameText = nameText;
}
public String getUrlText() {
return urlText;
}
public void setUrlText(String urlText) {
this.urlText = urlText;
}
}
A more complicated example of message extention:
Message videoMsg = new Message();
VideoChatRTP videoXml = new VideoChatRTP();
videoXml.setVideoType(VideoMediaType.REQUEST);
videoXml.setAddress(address);
videoMsg.setTo(receive);
videoMsg.addExtension(videoXml);
XMPPConnection conn = BaseService.getInstance().getConnection();
conn.sendPacket(videoMsg);
The extension class VideoChatRIP must implement PacketExtension:
public class VideoChatRTP implements PacketExtension {
private VideoMediaType videoType;
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public VideoMediaType getVideoType() {
return videoType;
}
public void setVideoType(VideoMediaType videoType) {
this.videoType = videoType;
}
public static final String NAME = "jingle";
public static final String NAME_SPACE = "com:roger:video";
public VideoChatRTP() {
super();
}
#Override
public String getElementName() {
return NAME;
}
#Override
public String getNamespace() {
return NAME_SPACE;
}
#Override
public String toXML() {
StringBuffer sb = new StringBuffer();
sb.append("<jingle").append(" xmlns=\"").append(NAME_SPACE).append(
"\">");
sb.append("<type>").append(videoType).append("</type>");
sb.append("<ipAddress>").append(address).append("</ipAddress>");
sb.append("</jingle>");
return sb.toString();
}
}
The Listener:
ProviderManager.getInstance().addExtensionProvider(VideoChatRTP.NAME, VideoChatRTP.NAME_SPACE, new VideoChatReceive());
Processing:
public class VideoChatReceive implements PacketExtensionProvider {
#Override
public PacketExtension parseExtension(XmlPullParser parser)
throws Exception {
boolean done = false;
String requestType = "asdasd";
String ipAddress = "asdasd";
while (!done) {
int eventType = parser.next();
String name = parser.getName();
if (eventType == XmlPullParser.START_TAG) {
if (name.equals("type")) {
requestType = parser.nextText();
}
if (name.equals("ipAddress")) {
ipAddress = parser.nextText();
}
}
if (eventType == XmlPullParser.END_TAG) {
if (name.equals("jingle")) {
done = true;
}
}
}
VideoChatRTP videoRtp = new VideoChatRTP();
videoRtp.setVideoType(VideoMediaType.valueOf(requestType));
videoRtp.setAddress(ipAddress);
return videoRtp;
}
}