Fails to access the `Downloads` folder - java

I am trying to save a txt file into the Downloads folder in my first abndroid app.
public class DisplaySettingsActivity extends AppCompatActivity implements View.OnClickListener {
private H300sVoipSettings settings;
Button saveIntoFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_settings);
this.settings = (H300sVoipSettings) getIntent().getSerializableExtra("H300sVoipSettings");
this.saveIntoFile = (Button)findViewById(R.id.save);
this.saveIntoFile.setOnClickListener(this);
}
private String saveFile(){
Log.d("Η300s","Saving");
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e("H300s","Unable to detect external storage");
return null;
}
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyMMdd");
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File( file.getAbsolutePath(),"voip_h300s_"+pattern.format(LocalDate.now())+".txt");
Log.d("H300s",file.toString());
try {
Log.d("H300s","Saving");
this.settings.save(file);
Log.d("H300s","Saved");
Log.d("H300s",file.getAbsolutePath());
return file.getAbsolutePath();
} catch (Exception e) {
Log.e("H300s",e.toString());
Log.e("H300s",Log.getStackTraceString(e));
return null;
}
}
}
But this piece of code in my function:
this.settings.save(file);
Fails to be saved due to lack of permissions. As the following log shows:
2021-04-24 14:48:18.498 8208-8208/com.example.vodafone_fu_h300s E/H300s: java.io.IOException: Permission denied
2021-04-24 14:48:18.499 8208-8208/com.example.vodafone_fu_h300s E/H300s: java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively0(Native Method)
at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
at java.io.File.createNewFile(File.java:1008)
at pc_magas.vodafone_fu_h300s.screens.DisplaySettingsActivity.saveFile(DisplaySettingsActivity.java:97)
at pc_magas.vodafone_fu_h300s.screens.DisplaySettingsActivity.onClick(DisplaySettingsActivity.java:120)
at android.view.View.performClick(View.java:6597)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25906)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
What I want to do is to save a txt file into Downloads Folder and make it accessible to the user via file manager. The class H300sVoipSettings has the following:
public class H300sVoipSettings implements Serializable
{
private String username = null;
private String password = null;
private String primary_registar = null;
private String primary_registar_port = null;
private String secondary_registar = null;
private String secondary_registar_port = null;
private String primary_proxy = null;
private String primary_proxy_port = null;
private String secondary_proxy = null;
private String secondary_proxy_port = null;
private String sip_domain = null;
private String sip_number = null;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPrimary_registar() {
return primary_registar;
}
public void setPrimary_registar(String primary_registar) {
this.primary_registar = primary_registar;
}
public String getPrimary_registar_port() {
return primary_registar_port;
}
public void setPrimary_registar_port(String primary_registar_port) {
this.primary_registar_port = primary_registar_port;
}
public String getSecondary_registar() {
if(secondary_registar == null || secondary_registar.trim().equals("")){
return null;
}
return secondary_registar;
}
public void setSecondary_registar(String secondary_registar) {
this.secondary_registar = secondary_registar;
}
public String getSecondary_registar_port() {
return secondary_registar_port;
}
public void setSecondary_registar_port(String secondary_registar_port) {
this.secondary_registar_port = secondary_registar_port;
}
public String getPrimary_proxy() {
return primary_proxy;
}
public void setPrimary_proxy(String primary_proxy) {
this.primary_proxy = primary_proxy;
}
public String getPrimary_proxy_port() {
return primary_proxy_port;
}
public void setPrimary_proxy_port(String primary_proxy_port) {
this.primary_proxy_port = primary_proxy_port;
}
public String getSecondary_proxy() {
return secondary_proxy;
}
public void setSecondary_proxy(String secondary_proxy) {
this.secondary_proxy = secondary_proxy;
}
public String getSecondary_proxy_port() {
return secondary_proxy_port;
}
public void setSecondary_proxy_port(String secondary_proxy_port) {
this.secondary_proxy_port = secondary_proxy_port;
}
public String getSip_domain() {
return sip_domain;
}
public void setSip_domain(String sip_domain) {
this.sip_domain = sip_domain;
}
public String getSip_number() {
return sip_number;
}
public void setSip_number(String sip_number) {
this.sip_number = sip_number;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static H300sVoipSettings createFromJson(String jsonString) throws IllegalArgumentException, JSONException {
if(jsonString == null || jsonString.trim().equals("")){
throw new IllegalArgumentException("JsonString Should not be empty");
}
JSONArray settingsJson = new JSONArray(jsonString);
H300sVoipSettings settings = new H300sVoipSettings();
for (int i = 0; i < settingsJson.length(); i++) {
JSONObject item = settingsJson.getJSONObject(i);
if(item.getString("type").equals("provider")){
settings.setPrimary_registar(item.getString("primary_registrar"));
settings.setPrimary_registar_port(item.getString("primary_registrar_port"));
settings.setPrimary_proxy(item.getString("primary_proxy"));
settings.setPrimary_proxy_port(item.getString("primary_proxy_port"));
settings.setSip_domain(item.getString("sip_domain"));
String secondary_proxy = item.getString("secondary_proxy");
if(secondary_proxy != null && !secondary_proxy.trim().equals("")){
settings.setSecondary_proxy(secondary_proxy.trim());
}
settings.setSecondary_proxy_port(item.getString("secondary_proxy_port"));
settings.setSecondary_registar(item.getString("secondary_registrar"));
settings.setSecondary_registar_port(item.getString("secondary_registrar_port"));
} else if(item.getString("type").equals("number")){
settings.setSip_number(item.getString("sip_number"));
settings.setUsername(item.getString("username"));
settings.setPassword(item.getString("password"));
}
}
return settings;
}
public boolean equals(H300sVoipSettings other){
boolean truth = other.getPassword().equals(this.getPassword()) &&
other.getUsername().equals(this.getUsername()) &&
other.getSip_number().equals(this.getSip_number()) &&
other.getSip_domain().equals(this.getSip_domain()) &&
other.getPrimary_proxy().equals(this.getPrimary_proxy()) &&
other.getPrimary_proxy_port().equals(this.getPrimary_proxy_port()) &&
other.getPrimary_registar().equals(this.getPrimary_registar()) &&
other.getPrimary_registar_port().equals(this.getPrimary_registar_port()) &&
other.getSecondary_proxy_port().equals(this.getSecondary_proxy_port()) &&
other.getSecondary_registar_port().equals(this.getSecondary_registar_port());
truth = truth && ((other.getSecondary_proxy() == null && this.getSecondary_proxy() == null) || (other.getSecondary_proxy().equals(this.getSecondary_proxy())));
truth = truth &&
(
(other.getSecondary_registar() == null && this.getSecondary_registar() == null) ||
(
other.getSecondary_registar().equals(this.getSecondary_registar())
)
);
return truth;
}
public String toString()
{
StringBuilder txt = new StringBuilder();
txt.append("Phone Number: ");
txt.append(this.getSip_number());
txt.append("\n");
txt.append("Username: ");
txt.append(this.getUsername());
txt.append("\n");
txt.append("Password: ");
txt.append(this.getPassword());
txt.append("\n");
txt.append("Sip Domain: ");
txt.append(this.getSip_domain());
txt.append("\n");
txt.append("Primary proxy: ");
txt.append(this.getPrimary_proxy());
txt.append(" Port: ");
txt.append(this.getPrimary_proxy_port());
txt.append("\n");
txt.append("Secondary proxy: ");
String secondary_proxy = this.getSecondary_proxy();
secondary_proxy = (secondary_proxy == null || !secondary_proxy.trim().equals(""))?"N/A":secondary_proxy;
txt.append(secondary_proxy);
txt.append(" Port: ");
String secondaryProxyPort = this.getSecondary_proxy_port();
secondaryProxyPort=(secondaryProxyPort == null || !secondaryProxyPort.trim().equals(""))?"N/A":secondaryProxyPort;
txt.append(secondaryProxyPort);
txt.append("\n");
txt.append("Primary Registar: ");
String primaryRegistar = this.getPrimary_registar();
txt.append(primaryRegistar);
txt.append(" Port: ");
String primaryRegistarPort = this.getPrimary_registar_port();
txt.append(primaryRegistarPort);
txt.append("\n");
txt.append("Secondary Registar: ");
String secondary_registar = this.getSecondary_registar();
secondary_registar = (secondary_registar == null || !secondary_registar.trim().equals(""))?"N/A":secondary_registar;
txt.append(secondary_registar);
txt.append(" Port: ");
String secondaryRegistarPort = this.getSecondary_registar();
secondaryRegistarPort=(secondaryRegistarPort == null || !secondaryRegistarPort.trim().equals(""))?"N/A":secondaryRegistarPort;
txt.append(secondaryRegistarPort);
txt.append("\n");
return txt.toString();
}
public void save(File file) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(file));
out.println("********");
out.print("Exported Date: ");
out.println(new Date().toString());
out.println("********");
out.print(this.toString());
out.close();
}
}
And is used for data serialization. The application has the following in Android Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Furthermore I have looked upon these answers whith no result whatsoever:
https://stackoverflow.com/a/62748149/4706711
So do you have any idea how I can access the donwloads folder?

Despite having the permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should also prompt the user to accept these requests as well. In order to achieve this the onCLick function should be:
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d("H300s","Permission Accepted");
saveFile();
} else {
requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE );
}
}
Where the requestPermissionLauncher is initialized into the onCreate like this:
requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
Log.d("H300s","Permissions Callback");
if (isGranted) {
Log.d("H300s","Permission Accepted 2");
saveFile();
} else {
permissionSaveDenied();
}
});
Furthermore, ensure that at build.gradle you should place the following:
implementation 'androidx.activity:activity-ktx:1.2.0'
implementation 'androidx.fragment:fragment:1.3.0'
In order for the ActivityResultContracts to work.
Bonus Tip
You can skip declaring the need for this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Because application gonna request the user to provide it nevertheless.

Related

Java SaxParser XML

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>

The root deduction code has been Bypassed by frida and Object Bypassing how to save apps from those bypass method?

My application is Under VAPT report certification. in my application i wrote a code for detecting weather the device is root or not. the method is returning boolean values. but they Bypassed the code with Magisk or some other root application. How to disable the bypassing???? How????
public class DeviceUtils {
public static boolean isDeviceRooted() {
return checkRootMethod1() || checkRootMethod2() || checkRootMethod3() || checkRootMethod4() || checkRootMethod5();
}
private static boolean checkRootMethod1() {
String buildTags = android.os.Build.TAGS;
return buildTags != null && buildTags.contains("test-keys");
}
private static boolean checkRootMethod2() {
String[] paths = { "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
"/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};
for (String path : paths) {
if (new File(path).exists()) return true;
}
return false;
}
private static boolean checkRootMethod3() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[] { "/system/xbin/which", "su" });
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
if (in.readLine() != null) return true;
return false;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
private static boolean checkRootMethod4() {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
return false;
}
public static boolean findBinary(String binaryName)
{ boolean found = false;
if (!found) { String[] places = { "/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/", "/data/local/bin/", "/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/", "/system/app/Superuser.apk", "/sbin/su", "/sbin/su/", "/system/bin/su","/system/bin/su/", "/system/xbin/su", "/system/xbin/su/", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su", "/su/", "/data/local/xbin/", "/system/bin/.ext/", "/system/bin/failsafe/", "/system/sd/xbin/", "/su/xbin/", "/su/bin/", "/magisk/.core/bin/", "/system/usr/we-need-root/", "/system/xbin/", "/system/su","/system/bin/.ext/.su","/system/usr/we-need-root/su-backup", "/system/xbin/mu", "/system/su/","/system/bin/.ext/.su/","/system/usr/we-need-root/su-backup/", "/system/xbin/mu/"};
for (String where : places)
{
if (new File(where + binaryName).exists())
{
found = true;
break;
}
}
}
return found;
}
private static boolean checkRootMethod5()
{
return findBinary("su");
}
}

Xpages: send html email via java using backend document

I found this great Java Bean that allows you to send an html email including attachments via a managed java bean. It works as described when I use it directly form an Xpage.
However, I would like to use this in the backend in a scheduled agent. The problem I have run into is when I try to pass a document to the java bean. The bean is expecting (I think) an XSP document, which I don't have when in the back end, so it throws an error.
I thought I would just send the UNID of the document that I want and then change it so it would work with this bean, however, when I try to set the UNID I get an error:
Unknown member 'setUNID' in Java class 'com.scoular.utls.Email'
I am confused. Seems like this has something to do with a wrapped document, but don't understand.
Here is the faces-config:
<faces-config>
<managed-bean>
<managed-bean-name>Email</managed-bean-name>
<managed-bean-class>com.scoular.utls.Email</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>debugMode</property-name>
<value>true</value>
</managed-property>
</managed-bean>
</faces-config>
Here is a button I am using to test calling the method:
//Need to get email document
var emlView = database.getView("xpViewEmailsAll");
var emlDoc = emlView.getFirstDocument();
if (emlDoc != null) {
//try{
var subject = ""
var senderEmail = supEml
var senderName = supNme
Email.setSendTo("John");
Email.setSubject("subject");
Email.setSenderEmail("John#gmal.com");
Email.setUNID = emlDoc.getUniversalID();
Email.setSenderName("Sender");
//Email.setBackEndDocument(emlDoc);
Email.setFieldName("Body");
Email.send();
//}catch(e){
//print(e.getMessage());
//}
}
And here is the bean:
package com.scoular.utls;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.EmbeddedObject;
import lotus.domino.MIMEEntity;
import lotus.domino.MIMEHeader;
import lotus.domino.NotesException;
import lotus.domino.Session;
import lotus.domino.Stream;
import com.ibm.commons.util.NotImplementedException;
import com.ibm.domino.xsp.module.nsf.NotesContext;
import com.ibm.xsp.model.FileRowData;
import com.ibm.xsp.model.domino.wrapped.DominoDocument;
import com.ibm.xsp.model.domino.wrapped.DominoRichTextItem;
import com.ibm.xsp.model.domino.wrapped.DominoDocument.AttachmentValueHolder;
import com.ibm.xsp.persistence.PersistedContent;
public class Email {
private ArrayList<String> sendTo;
private ArrayList<String> ccList;
private ArrayList<String> bccList;
private String senderEmail;
private String senderName;
private String subject;
private DominoDocument document;
private String fieldName;
private String bannerHTML;
private String footerHTML;
private String unid;
private boolean debugMode = false;
private static final Pattern imgRegExp = Pattern.compile("<img[^>]+src\\s*=\\s*['\"]([^'\"]+)['\"][^>]*>");
// -------------------------------------------------------------------------
public Email() {
this.subject = "";
this.sendTo = new ArrayList<String>();
this.ccList = new ArrayList<String>();
this.bccList = new ArrayList<String>();
}
// -------------------------------------------------------------------------
public String getSendTo() {
if (this.isDebugMode()) {
System.out.println("getSendTo() : " + this.sendTo.toString());
}
return this.sendTo.toString().replace("[", "").replace("]", "");
}
public void setSendTo(final String sendTo) {
this.sendTo.add(sendTo);
}
// -------------------------------------------------------------------------
public String getCcList() {
if (this.isDebugMode()) {
System.out.println("getCcList() : " + this.ccList.toString());
}
return this.ccList.toString().replace("[", "").replace("]", "");
}
public void setCcList(final String ccList) {
this.ccList.add(ccList);
}
// -------------------------------------------------------------------------
public String getBccList() {
if (this.isDebugMode()) {
System.out.println("getBccList() : " + this.bccList.toString());
}
return this.bccList.toString().replace("[", "").replace("]", "");
}
public void setBccList(final String bccList) {
this.bccList.add(bccList);
}
// -------------------------------------------------------------------------
public String getSenderEmail() {
return this.senderEmail;
}
public void setSenderEmail(final String senderEmail) {
this.senderEmail = senderEmail;
}
// -------------------------------------------------------------------------
public String getSenderName() {
return this.senderName;
}
public void setSenderName(final String senderName) {
this.senderName = senderName;
}
// -------------------------------------------------------------------------
public String getSubject() {
return this.subject;
}
public void setSubject(final String subject) {
this.subject = subject;
}
// -------------------------------------------------------------------------
public boolean isDebugMode() {
return this.debugMode;
}
public void setDebugMode(final boolean debugMode) {
this.debugMode = debugMode;
}
// -------------------------------------------------------------------------
private Session getCurrentSession() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentSession() : null;
}
// -------------------------------------------------------------------------
private Database getCurrentDatabase() {
NotesContext nc = NotesContext.getCurrentUnchecked();
return (null != nc) ? nc.getCurrentDatabase() : null;
}
// -------------------------------------------------------------------------
public void send() throws NotesException, IOException, Exception {
Session session = getCurrentSession();
Database database = getCurrentDatabase();
if (null != session && null != database && null != this.sendTo && null != this.subject
&& null != this.senderEmail) {
try {
if (this.isDebugMode()) {
System.out.println("Started send()");
}
session.setConvertMime(false);
Document emailDocument = database.createDocument();
MIMEEntity emailRoot = emailDocument.createMIMEEntity("Body");
if (null != emailRoot) {
MIMEHeader emailHeader = emailRoot.createHeader("Reply-To");
emailHeader.setHeaderVal(this.getSenderEmail());
emailHeader = emailRoot.createHeader("Return-Path");
emailHeader.setHeaderVal(this.getSenderEmail());
final String fromSender = (null == this.getSenderName()) ? this.getSenderEmail() : "\""
+ this.getSenderName() + "\" <" + this.getSenderEmail() + ">";
emailHeader = emailRoot.createHeader("From");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("Sender");
emailHeader.setHeaderVal(fromSender);
emailHeader = emailRoot.createHeader("To");
emailHeader.setHeaderVal(this.getSendTo());
if (!this.ccList.isEmpty()) {
emailHeader = emailRoot.createHeader("CC");
emailHeader.setHeaderVal(this.getCcList());
}
if (!this.bccList.isEmpty()) {
emailHeader = emailRoot.createHeader("BCC");
emailHeader.setHeaderVal(this.getBccList());
}
emailHeader = emailRoot.createHeader("Subject");
emailHeader.setHeaderVal(this.getSubject());
MIMEEntity emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild) {
final String boundary = System.currentTimeMillis() + "-" + this.document.getDocumentId();
emailHeader = emailRootChild.createHeader("Content-Type");
emailHeader.setHeaderVal("multipart/alternative; boundary=\"" + boundary + "\"");
MIMEEntity emailChild = emailRootChild.createChildEntity();
if (null != emailChild) {
final String contentAsText = this.document.getRichTextItem(this.fieldName)
.getContentAsText();
Stream stream = session.createStream();
stream.writeText(contentAsText);
emailChild.setContentFromText(stream, "text/plain; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
emailChild = emailRootChild.createChildEntity();
stream = session.createStream();
stream.writeText(this.getHTML());
emailChild.setContentFromText(stream, "text/html; charset=\"UTF-8\"", MIMEEntity.ENC_NONE);
stream.close();
stream.recycle();
stream = null;
}
// add embedded images....
final List<FileRowData> embeddedImages = this.getEmbeddedImagesList();
if (null != embeddedImages && !embeddedImages.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Images...");
}
for (FileRowData embeddedImage : embeddedImages) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && embeddedImage instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) embeddedImage)
.getPersistentName();
String cid = ((AttachmentValueHolder) embeddedImage).getCID();
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("inline; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = this.getEmbeddedImageStream(persistentName);
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, embeddedImage.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Embedded Image : " + persistentName);
}
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Adding Embedded Image failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Embedded Images");
}
}
// add attachments....
final List<FileRowData> attachments = this.getDocument().getAttachmentList(this.getFieldName());
if (null != attachments && !attachments.isEmpty()) {
if (this.isDebugMode()) {
System.out.println("Adding Attachments...");
}
for (FileRowData attachment : attachments) {
emailRootChild = emailRoot.createChildEntity();
if (null != emailRootChild && attachment instanceof AttachmentValueHolder) {
InputStream is = null;
try {
String persistentName = ((AttachmentValueHolder) attachment)
.getPersistentName();
String cid = ((AttachmentValueHolder) attachment).getCID();
EmbeddedObject eo = this.getDocument().getDocument().getAttachment(
persistentName);
if (null != eo) {
emailHeader = emailRootChild.createHeader("Content-Disposition");
emailHeader.setHeaderVal("attachment; filename=\"" + persistentName + "\"");
emailHeader = emailRootChild.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
is = eo.getInputStream();
Stream stream = session.createStream();
stream.setContents(is);
emailRootChild.setContentFromBytes(stream, attachment.getType(),
MIMEEntity.ENC_IDENTITY_BINARY);
if (this.isDebugMode()) {
System.out.println("Added Attachment : " + persistentName);
}
}
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Adding Attachment failed : " + e.getMessage());
}
throw e;
} finally {
if (null != is) {
is.close();
is = null;
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed Adding Attachments");
}
}
}
}
emailDocument.send();
session.setConvertMime(true);
if (this.isDebugMode()) {
System.out.println("Completed send()");
}
} catch (NotesException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with NotesException" + e.getMessage());
}
throw e;
} catch (IOException e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with IOException" + e.getMessage());
}
throw e;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed send() with Exception" + e.getMessage());
}
throw e;
}
}
}
// -------------------------------------------------------------------------
public DominoDocument getDocument() {
return this.document;
}
public void setDocument(final DominoDocument document) {
this.document = document;
}
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
public String getFieldName() {
return this.fieldName;
}
public void setFieldName(final String fieldName) {
this.fieldName = fieldName;
}
// -------------------------------------------------------------------------
public List<FileRowData> getEmbeddedImagesList() throws NotesException {
if (null != document && null != fieldName) {
return document.getEmbeddedImagesList(fieldName);
}
return null;
}
// -------------------------------------------------------------------------
private InputStream getEmbeddedImageStream(final String fileName) throws NotesException, IOException {
if (null != document && null != fieldName && null != fileName) {
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
final PersistedContent pc = drti.getPersistedContent(FacesContext.getCurrentInstance(), fieldName,
fileName);
if (null != pc) {
return pc.getInputStream();
}
}
}
return null;
}
// -------------------------------------------------------------------------
public String getHTML() {
StringBuffer html = new StringBuffer();
html.append(getBannerHTML());
html.append(getBodyHTML());
html.append(getFooterHTML());
return html.toString();
}
// -------------------------------------------------------------------------
public String getBannerHTML() {
return this.bannerHTML;
}
public void setBannerHTML(final String bannerHTML) {
this.bannerHTML = bannerHTML;
}
// -------------------------------------------------------------------------
public String getBodyHTML() {
if (null != document && null != fieldName) {
if (this.isDebugMode()) {
System.out.println("Started getBodyHTML()");
}
final DominoRichTextItem drti = document.getRichTextItem(fieldName);
if (null != drti) {
try {
String html = drti.getHTML();
if (null != html) {
final List<FileRowData> fileRowDataList = document.getEmbeddedImagesList(fieldName);
if (null != fileRowDataList) {
final Matcher matcher = imgRegExp.matcher(html);
while (matcher.find()) {
String src = matcher.group();
final String srcToken = "src=\"";
final int x = src.indexOf(srcToken);
final int y = src.indexOf("\"", x + srcToken.length());
final String srcText = src.substring(x + srcToken.length(), y);
for (FileRowData fileRowData : fileRowDataList) {
final String srcImage = fileRowData.getHref();
final String cidImage = ((AttachmentValueHolder) fileRowData).getCID();
if (srcText.endsWith(srcImage)) {
final String newSrc = src.replace(srcText, "cid:" + cidImage);
html = html.replace(src, newSrc);
if (this.isDebugMode()) {
System.out.println("CID referenced image: " + srcText + " with CID:"
+ cidImage);
}
}
}
}
}
}
if (this.isDebugMode()) {
System.out.println("Completed getBodyHTML() : " + html);
}
return html;
} catch (Exception e) {
if (this.isDebugMode()) {
System.out.println("Failed getBodyHTML() : " + e.getMessage());
}
}
}
}
return null;
}
public void setBodyHTML(final String bodyHTML) throws NotImplementedException {
if (this.isDebugMode()) {
System.out.println("Method setBodyHTML(string) is not permitted");
}
throw new NotImplementedException();
}
// -------------------------------------------------------------------------
public String getFooterHTML() {
return this.footerHTML;
}
public void setFooterHTML(final String footerHTML) {
this.footerHTML = footerHTML;
}
public String getUnid() {
return unid;
}
public void setUnid(final String unid) {
this.unid = unid;
}
// -------------------------------------------------------------------------
} // end EmailBean
The Email.setUNID statement is wrong. Try:
Email.setUnid(emlDoc.getUniversalID());

How do I combine two separate parsed jsonObjects into a single arraylist?

I would like to combine two separate parsed jsonObjects into a single arraylist, then display the results as Strings?
I would like to store summaryJsonObject & segment in storylineData. When I step through the code using the debugger summaryJsonObject & segment both hold the raw json. The raw json data also shows in the logcat but storylineData remains null & unavailable throughout.
Here is the parsing code.
public class StorylineData {
private static String date;
private ArrayList<SummaryData> summary;
private ArrayList<SegmentData> segments;
private String caloriesIdle;
private String lastUpdate;
public String getDate() {
return date;
}
public ArrayList<SummaryData> getSummary() {
return summary;
}
public ArrayList<SegmentData> getSegments() {
return segments;
}
public String getCaloriesIdle() {
return caloriesIdle;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setDate(String date) {
this.date = date;
}
public void setSummary(ArrayList<SummaryData> summary) {
this.summary = summary;
}
public void setSegments(ArrayList<SegmentData> segments) {
this.segments = segments;
}
public void setCaloriesIdle(String caloriesIdle) {
this.caloriesIdle = caloriesIdle;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static StorylineData parse(JSONObject jsonObject) {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = new ArrayList<SummaryData>();
storylineData.segments = new ArrayList<SegmentData>();
JSONArray summariesJsonArray= jsonObject.optJSONArray("summary");
if (summariesJsonArray != null) {
for (int i = 0; i < summariesJsonArray.length(); i++) {
JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);
if (summaryJsonObject != null) {
storylineData.summary.add(SummaryData.parse(summaryJsonObject));
Log.d("storylineHandler", summaryJsonObject.toString());
}
}
}
JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
if (segmentsJsonArray != null) {
for (int i = 0; i < segmentsJsonArray.length(); i++) {
JSONObject segment = segmentsJsonArray.optJSONObject(i);
if (segment != null) {
storylineData.segments.add(SegmentData.parse(segment));
Log.d("storylineHandler", segment.toString());
}
}
}
return storylineData;
}
return null;
}
}
The MainActivity looks like this:
MainActivity
public class MainActivity extends FragmentActivity implements OnClickListener{
..other variables here..
List<StorylineData> storylineData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...other ui elements here...
mEditTextResponse = (TextView) findViewById(R.id.editResponse);
storylineData = new StorylineData();
MovesAPI.init(this, CLIENT_ID, CLIENT_SECRET, CLIENT_SCOPES.....
#Override
public void onClick(View v) {
toggleProgress(true);
switch (mSpinnerAPI.getSelectedItemPosition()) {
... other cases here...
break;
...other cases here...
case 4: // Get Summary Day
MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117"
break;
Other cases here..
case 10: // Get Storyline Day
MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", null, false);//Date changed to "20150418"
break;
...Other cases here..
}
}
... Other MovesHandlers here...
private JSONObject summaryJsonObject;
private List<StorylineData> storylineList;
private JSONObject summariesJsonArray;
private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() {
#Override
public void onSuccess(ArrayList<StorylineData> result) {
toggleProgress(false);
storylineList = (List<StorylineData>) StorylineData.parse(summaryJsonObject);
updateResponse( + storylineData.toString() + "\n" //displays true to layout view
result.add(StorylineData.parse(summariesJsonArray))+ "\n"
+Log.d("call result", result.toString()) + "\n" //displays 60 in layout view & com.protogeo.moves.demos.apps.storyline.StorylineData#52824f88, null]
+ Log.d("Log.d storylineHandler", storylineHandler.toString()) + "\n" ); //returns 78 in layout view & com.protogeo.moves.demos.apps.Mainactivity#234234 to log cat
onFailure code here..
}
};
public void toggleProgress(final boolean isProgrressing) {
togglePregress code here..
}
public void updateResponse(final String message) {
runOnUiThread(new Runnable() {
public List<StorylineData> storylineList;
#Override
public void run() {
mEditTextResponse.setText(message);
if (storylineData!= null) {
for (StorylineData storylineData : storylineList) {
mEditTextResponse.append(("storylineData" + storylineData.toString()));
}
}
}
});
}
}
HttpClass
public static void getDailyStorylineList(final MovesHandler<JSONArray> handler,
final String specificSummary,
final String from,
final String to,
final String pastDays,
final String updatedSince,
final boolean needTrackPoints) {
new Thread(new Runnable() {
#Override
public void run() {
try {
/* Refresh access token if only AuthData.MOVES_REFRESHBEFORE days are there to expire current token */
AuthData.refreshAccessTokenIfNeeded();
/* Exchange the authorization code we obtained after login to get access token */
HashMap<String, String> nameValuePairs = new HashMap<String, String>();
nameValuePairs.put("access_token", AuthData.getAuthData().getAccessToken());
// if (specificSummary != null && specificSummary.length() > 0) nameValuePairs.put("specificSummary", specificSummary);//att
if (from != null && from.length() > 0) nameValuePairs.put("from", from);
if (to != null && to.length() > 0) nameValuePairs.put("to", to);
if (pastDays != null && pastDays.length() > 0) nameValuePairs.put("pastDays", pastDays);
if (updatedSince != null && updatedSince.length() > 0) nameValuePairs.put("updatedSince", updatedSince);
if (needTrackPoints) nameValuePairs.put("trackPoints", "true");
URL url = new URL(MovesAPI.API_BASE + MovesAPI.API_PATH_STORYLINE + (specificSummary != null ? specificSummary : "") + "?" + Utilities.encodeUrl(nameValuePairs));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
if (urlConnection.getResponseCode() != 200) {
/* All other HTTP errors from Moves will fall here */
handler.onFailure(getErrorStatus(Utilities.readStream(urlConnection.getErrorStream()), urlConnection.getResponseCode()), "Server not responded with success ("+ urlConnection.getResponseCode() +")");
return;
}
String response = Utilities.readStream(urlConnection.getInputStream());
Object object = new JSONTokener(response).nextValue();
if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
ArrayList<StorylineData> storylineData = new ArrayList<StorylineData>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject storylineJsonObject = jsonArray.optJSONObject(i);
if (storylineJsonObject != null) {
storylineData.add(StorylineData.parse(storylineJsonObject));
}
}
}
handler.onSuccess(storylineData);
} else {
handler.onFailure(MovesStatus.INVALID_RESPONSE, "Expected a JSONArray from server, but failed");
}
} catch (Exception ex) {
ex.printStackTrace();
handler.onFailure(MovesStatus.UNEXPECTED_ERROR, "An unexpected error occured, please check logcat");
}
}
}).start();
}
MovesHandler
public interface MovesHandler<T> {//T stands for generic type
/**
* Implement this method to get success notifications along with the result
* #param result : Result of the operation completed with this handler
*/
public void onSuccess(ProfileData result);
/**
* Implement this method to get failure notifications along with the {#link MovesStatus} code and a brief message
* #param status : Status code of the failure
* #param message : A brief message about the reason behind failure
*/
public void onFailure(MovesStatus status, String message);
}
If you wanted to have one ArrayList to store both SummaryData and SegmentData, you could just created an ArrayList of Objects, ArrayList<Object>. This would be the more general solution.
The alternative would be having SummaryData and SegmentData inherit the same class or implement the same interface.
Using an extended class, you could have:
class Data {
}
class SegmentData extends Data {
}
class SummaryData extends Data {
}
You could then have an ArrayList that would be able to add both SegmentData and SummaryData objects.
If you wanted to show each item as a String you would need to loop through the list and call the toString() function of each item
ArrayList<Data> dataList;
for (Data d : dataList) {
Log.d("data", d.toString())
}
Just make sure to overwrite the toString() function in SegmentData and SummaryData
EDIT: Showing how to print JsonArray
If you wanted to just print for JsonArrays, you could:
public class StorylineData {
private static String date;
private JSONArray summary;
private JSONArray segments;
private String caloriesIdle;
private String lastUpdate;
public String getDate() {
return date;
}
public JSONArray getSummary() {
return summary;
}
public JSONArray getSegments() {
return segments;
}
public String getCaloriesIdle() {
return caloriesIdle;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setDate(String date) {
this.date = date;
}
public void setSummary(JSONArray summary) {
this.summary = summary;
}
public void setSegments(JSONArray segments) {
this.segments = segments;
}
public void setCaloriesIdle(String caloriesIdle) {
this.caloriesIdle = caloriesIdle;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static StorylineData parse(JSONObject jsonObject) {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = jsonObject.optJSONArray("summary");
storylineData.segments = jsonObject.optJSONArray("segments");
return storylineData;
}
return null;
}
#Override
public String toString() {
JSONArray combined = new JSONArray(summary);
combined.put(segment);
return combined.toString();
}
}
In your MainActivity
private StorylineData storylineData;
private MovesHandler<JSONArray> storylineHandler = new MovesHandler<JSONArray>() {
#Override
public void onSuccess(JSONArray result) {
toggleProgress(false);
storylineData = StorylineData.parse(summaryJsonObject);
updateResponse(storylineData.toString()) //displays true to layout view
result.add(storylineData.getSummary());
Log.d("call result", result.toString());
Log.d("Log.d storylineHandler", storylineHandler.toString());
}
};

Android JSON Parser "User cannot be resolved to a type"

public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public List readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
return readMessagesArray(reader);
} finally {
reader.close();
}
}
public List readMessagesArray(JsonReader reader) throws IOException {
List messages = new ArrayList();
reader.beginArray();
while (reader.hasNext()) {
messages.add(readMessage(reader));
}
reader.endArray();
return messages;
}
public Message readMessage(JsonReader reader) throws IOException {
long id = -1;
String text = null;
User user = null;
List geo = null;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if(name.equals("id")) {
id = reader.nextLong();
} else if (name.equals("text")) {
text = reader.nextString();
} else if (name.equals("geo") && reader.peek() != JsonToken.NULL) {
geo = readDoublesArray(reader);
} else if (name.equals("user")) {
user = readUser(reader);
} else {
reader.skipValue();
}
}
reader.endObject();
return new Message(id, text, user, geo);
}
public List readDoublesArray(JsonReader reader)throws IOException {
List doubles = new ArrayList();
reader.beginArray();
return doubles;
}
public User readUser(JsonReader reader) throws IOException {
String username = null;
int followersCount = -1;
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if(name.equals("name")) {
username = reader.nextString();
} else if (name.equals("followers_count")) {
followersCount = reader.nextInt();
} else {
reader.skipValue();
}
}
reader.endObject();
return new User(username, followersCount);
}}
I'm using the exact example from http://developer.android.com/reference/android/util/JsonReader.html. However, there is a problem with "User cannot be resolved to a type".
'User' class in the given example is just to show how it may work. You may substitute it with something like this:
public class User{
String name;
int followers_count;
public User(String name, int followers_count){
this.name=name;
this.followers_count=followers_count;
}
}

Categories