Oracle Analytics Server Web service for get user info - oracle

i have installed the Oracle Analytics Server 5.9(New version of Oracle BI) in my linux server and we migrate the configurations and the meta data and repository from old version to this one.
also we had a .NET app that work with the web service of Oracle BI to get and set the user and groups of security realm in the domain of BI.
but now in Oracle Analytics Server, the web service does not work properly.
in the local domain it does work properly but when we deploy on the server of Analytics Server, it does not work properly.
my source code is :
#WebService
public class UserGroupMemberCls {
private static JMXConnector jmxConnector = null;
private static MBeanServerConnection mBeanServerConnection = null;
private static String webLogicHostname = "192.168.24.63";
private static String webLogicPort = "9500";
private static String webLogicUsername = "weblogic";
private static String webLogicPassword = "123456";
.
.
.
.
#WebMethod(exclude = true)
public static List getListOfGroups() throws Exception {
ObjectName securityMBeanName1 = new ObjectName("Security:Name=myrealmDefaultAuthenticator");
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST2");
try {
initConnection(webLogicHostname, webLogicPort);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST13");
List<String> allUsers = new ArrayList();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST14");
String cursor =
(String) mBeanServerConnection.invoke(securityMBeanName1, "listGroups",
new Object[] { "*", Integer.valueOf(100) },
new String[] { "java.lang.String", "java.lang.Integer" });
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST15");
boolean haveCurrent =
((Boolean) mBeanServerConnection.invoke(securityMBeanName1, "haveCurrent", new Object[] { cursor },
new String[] { "java.lang.String" })).booleanValue();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST16");
while (haveCurrent) {
String currentName =
(String) mBeanServerConnection.invoke(securityMBeanName1, "getCurrentName", new Object[] { cursor },
new String[] { "java.lang.String" });
allUsers.add(currentName);
mBeanServerConnection.invoke(securityMBeanName1, "advance", new Object[] { cursor },
new String[] { "java.lang.String" });
haveCurrent =
((Boolean) mBeanServerConnection.invoke(securityMBeanName1, "haveCurrent", new Object[] { cursor },
new String[] { "java.lang.String" })).booleanValue();
}
mBeanServerConnection.invoke(securityMBeanName1, "close", new Object[] { cursor },
new String[] { String.class.getName() });
jmxConnector.close();
jmxConnector = null;
return allUsers;
} catch (Exception ex) {
ex.printStackTrace();
jmxConnector.close();
throw new RuntimeException(ex);
}
}
.
.
.
.
#WebMethod(exclude = true)
public static void initConnection(String hostname, String portString) throws IOException, MalformedURLException {
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST3");
Integer portInteger = Integer.valueOf(portString);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST4");
int port = portInteger.intValue();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST5");
String mserver = "/weblogic.management.mbeanservers.runtime";
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TES6");
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "hostname : " + hostname);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "port : " + port);
JMXServiceURL serviceURL =
new JMXServiceURL("service:jmx:iiop:///jndi/iiop://" + hostname + ":" + port + mserver);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "serviceURL : " + serviceURL);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST7");
Hashtable<Object, Object> h = new Hashtable<Object, Object>();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "h1 : " + h);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST8");
String[] credentials = { webLogicUsername, webLogicPassword };
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST9");
h.put("jmx.remote.credentials", credentials);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "h2 : " + h);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST10");
try {
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "(Map) h : " + (Map) h);
jmxConnector = JMXConnectorFactory.connect(serviceURL, (Map) h);
} catch (IOException ioe) {
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME)
.log(Level.SEVERE,
"MESSAGE : " + ioe.getMessage() + " >>>> " + "STACKTRACE : " + ioe.getStackTrace() +
" >>>> " + " CAUSE : " + ioe.getCause());
// TODO: Add catch code
ioe.printStackTrace();
}
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "jmxConnector : " + jmxConnector);
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST11");
mBeanServerConnection = jmxConnector.getMBeanServerConnection();
Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).log(Level.SEVERE, "TEST12");
}
and the output is :

Related

How to write a junit test case for private methods that are inside an if condition?

This is my service class, It has public method getFilesFromDirAndUploadtoHost() and inside that i have a reattempt() inside an if condition. I need to cover more codes by junit. What will be the modified test class, test class i mentioned below.*
#Service
public class FileTransferServiceImpl {
#Override
public Boolean getFilesFromDirAndUploadtoHost() throws SftpException {
List<String> files = Stream.of(new File(sourcePath).listFiles()).filter(file -> !file.isDirectory())
.map(File::getName).filter(file -> !file.endsWith("zip")).collect(Collectors.toList());
if(files.isEmpty()){
logger.info("No Files found to transfer");
return true;
}
ChannelSftp channelSftp = createChannelSftp();
Boolean result = false;
Integer attemptNo = 0;
Date date = new Date();
SimpleDateFormat formatDate = new SimpleDateFormat("dd-MM-yyyy HH mm ss z");
formatDate.setTimeZone(TimeZone.getTimeZone("IST"));
String dirName = formatDate.format(date);
if (channelSftp != null) {
// Create new folder in target
try {
channelSftp.mkdir("/" + dirName);
} catch (SftpException e) {
logger.error("Directory creation unsuccessful", e);
}
// Initial Attempt
List<ProcessFile> processFiles = copyFilestoTarget(channelSftp, files, attemptNo, dirName);
List<ProcessFile> failedFiles = processFiles.stream().filter(processFile -> !processFile.getSuccessfulYN())
.collect(Collectors.toList());
// If any Failed files found set to retry
if (!failedFiles.isEmpty()) {
reattempt(channelSftp, failedFiles, attemptNo, processFiles, dirName);
}
disconnectChannelSftp(channelSftp);
// populaate Process Run
populateAndSaveProcessRun(processFiles, files, dirName);
result = true;
}
return result;
}
private List<ProcessFile> copyFilestoTarget(ChannelSftp channelSftp, List<String> files, Integer attempNo,
String dirName) {
List<ProcessFile> processFiles = new ArrayList<>();
for (String fileName : files) {
try {
if (!channelSftp.isConnected()) {
channelSftp = recreateChannelSftp();
}
channelSftp.put(sourcePath + "/" + fileName, targetPath + "/" + dirName);
processFiles.add(populateProcessFiles(fileName, attempNo, dirName, true));
} catch (JSchException e) {
logger.error("Reconnection failed attempt No: " + attempNo);
processFiles.add(populateProcessFiles(fileName, attempNo, dirName, false));
} catch (SftpException e) {
logger.error("File : " + fileName + " Transfer Failed Attempt No: " + attempNo);
processFiles.add(populateProcessFiles(fileName, attempNo, dirName, false));
}
}
return processFiles;
}
private void reattempt(ChannelSftp channelSftp, List<ProcessFile> failedFiles, Integer attemptNo,
List<ProcessFile> processFiles, String dirName) {
attemptNo = 1;
List<ProcessFile> newFailedFile = failedFiles;
while (attemptNo <= 3) {
newFailedFile = copyFilestoTarget(channelSftp,
newFailedFile.stream().filter(processFile -> !processFile.getSuccessfulYN())
.map(processFile -> processFile.getFileName()).collect(Collectors.toList()),
attemptNo, dirName);
processFiles.addAll(newFailedFile);
if (newFailedFile.stream().filter(processFile -> !processFile.getSuccessfulYN())
.collect(Collectors.toList()).isEmpty()) {
attemptNo = 4;
} else {
attemptNo++;
}
}
}
}
This is my test class what i shoule modify here so that i can cover more lines. Here i am not sure how to do that. If any one can help it will be great.
#ExtendWith(MockitoExtension.class)
public class FileTransferServiceTest {
#InjectMocks
private FileTransferServiceImpl fileTransferService = new FileTransferServiceImpl();
#Mock
private ProcessFileService processFileService;
#BeforeEach
public void beforeClass() {
ReflectionTestUtils.setField(fileTransferService, "sourcePath", "F:\\Sample-sftp prjt\\needToTransfer");
ReflectionTestUtils.setField(fileTransferService, "host", "SDC-CDPGP01-test.com.au");
ReflectionTestUtils.setField(fileTransferService, "port", 2222);
ReflectionTestUtils.setField(fileTransferService, "username", "tester");
ReflectionTestUtils.setField(fileTransferService, "password", "password");
ReflectionTestUtils.setField(fileTransferService, "sessionTimeout", 15000);
ReflectionTestUtils.setField(fileTransferService, "channelTimeout", 15000);
ReflectionTestUtils.setField(fileTransferService, "targetPath", "/");
}
#Test
void uploadToAemo() throws SftpException {
assertNotNull(fileTransferService.getFilesFromDirAndUploadtoHost());
}
}

Files are sending to wrong sftp location while using Spring SFTP outbound gateway

We are using Spring SFTP (outbound) using Gateway to transfer files to multiple destinations. But often, few files are sent to the wrong destination. Can't find any clue as we don't get any error in our log except file count error after sending files.
Here is our configuration:
#Configuration
public class BankWiseSFTPConfig {
private final ExpressionParser EXPRESSION_PARSER;
private final BankConfigService bankConfigService;
public BankWiseSFTPConfig(BankConfigService bankConfigService) {
this.EXPRESSION_PARSER = new SpelExpressionParser();
this.bankConfigService = bankConfigService;
}
#Bean
public DelegatingSessionFactory<LsEntry> sessionFactory() {
List<BankConfigEntity> bankList = bankConfigService.getAll();
Map<Object, SessionFactory<LsEntry>> factories = new LinkedHashMap<>();
for (BankConfigEntity bank : bankList) {
DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory();
factory.setHost(bank.getSftpHost());
factory.setUser(bank.getSftpUser());
factory.setPort(bank.getSftpPort());
factory.setPassword(bank.getSftpPass());
factory.setAllowUnknownKeys(true);
factories.put(bank.getBankName(), factory);
}
bankList.clear();
return new DelegatingSessionFactory<LsEntry>(factories, factories.values().iterator().next());
}
#ServiceActivator(inputChannel = "toSftp")
#Bean
public SftpMessageHandler handler() {
SftpMessageHandler handler = new SftpMessageHandler(new SftpRemoteFileTemplate(sessionFactory()));
handler.setRemoteDirectoryExpression(EXPRESSION_PARSER.parseExpression("headers['path']"));
return handler;
}
#MessagingGateway
public interface SFTPOutboundGateway {
#Gateway(requestChannel = "toSftp")
void push(File file, #Header("path") String path);
#Gateway(requestChannel = "sftpChannel")
List<String> executeCommand(String path);
}
#Bean
#ServiceActivator(inputChannel = "sftpChannel")
public MessageHandler messageHandlerLs() {
SftpOutboundGateway sftpOutboundGateway = new SftpOutboundGateway(sessionFactory(), "ls", "payload");
sftpOutboundGateway.setOptions("-1 -R");
return sftpOutboundGateway;
}
}
Here are our push and file count methods:
private void pushReport(String bankName,
String destinationPath,
String sourcePath,
String refundType,
List<BankReportEntity> failedBankReportEntities,
List<BankReportEntity> pushedFiles,
BankReportEntity bankReportEntity) {
String sftpStatus = SlotBankStatus.BANK_SFTP_INITIATED.name();
String errorReason = StringUtils.EMPTY;
String fileName = bankReportEntity.getFileName();
String filePath = sourcePath + fileName;
File file = new File(filePath);
bankReportEntity.setSftpStatus(sftpStatus);
log.debug("{} :: SFTP Push Initiated for {} and File {}", refundType, bankName, fileName);
try {
log.info("{} :: SFTP Push trying for {} and {}", refundType, bankName, file);
gateway.push(file, destinationPath);
sftpStatus = SlotBankStatus.BANK_SFTP_COMPLETED.name();
pushedFiles.add(bankReportEntity);
log.info("{} :: SFTP Push success for {} and {}", refundType, bankName, file);
} catch (Exception e) {
emailService.sendSFTPExceptionEmail(
"File push error for file : " + fileName +
" and FileTransferType " + bankReportEntity.getFileTransferType() +
". Error : " + e.getLocalizedMessage(),
bankName);
sftpStatus = SlotBankStatus.BANK_SFTP_PENDING.name();
errorReason = ErrorCode.SFTP_PUSH_FAILED.name();
failedBankReportEntities.add(bankReportEntity);
log.error("{} :: File push error for file : {}, Bank {}, FileTransferType {}, Error : {}",
refundType,
fileName,
bankName,
bankReportEntity.getFileTransferType(),
e.getMessage(),
e
);
} finally {
log.info("{} :: SFTP to {} Status Updated for : {}", refundType, bankName, bankReportEntity);
bankReportEntity.setSftpStatus(sftpStatus);
bankReportEntity.setErrorReason(errorReason);
}
}
private SFTPPushFileCountDto getSFTPSuccessfulFileCount(
String bankName,
String path,
String refundType,
List<BankReportEntity> pushedFiles,
List<BankReportEntity> failedBankReports) {
int totalSuccessfulPush = pushedFiles.size();
int totalFailedPush = failedBankReports.size();
log.info("{} :: getSFTPSuccessfulFileCount() for {}, from {}", refundType, bankName, path);
try {
List<String> remoteFiles = gateway.executeCommand(path);
for (Iterator<BankReportEntity> pushedFilesIterator = pushedFiles.iterator(); pushedFilesIterator.hasNext(); ) {
BankReportEntity bankReport = pushedFilesIterator.next();
String fileName = bankReport.getFileName();
if (!remoteFiles.contains(fileName)) {
log.error("getSFTPSuccessfulFileCount() : File not found in remote {}. File: {}", path, fileName);
totalFailedPush++;
totalSuccessfulPush--;
bankReport.setSftpStatus(SlotBankStatus.BANK_SFTP_PENDING.name());
bankReport.setErrorReason(ErrorCode.UNKNOWN_ERROR_CODE.name());
pushedFilesIterator.remove();
failedBankReports.add(bankReport);
emailService.sendSFTPExceptionEmail(
"File push error for file : " + fileName +
" and FileTransferType " + bankReport.getFileTransferType() +
". Error : " + ErrorCode.UNKNOWN_ERROR_CODE.description(),
bankName);
}
}
} catch (Exception ex) {
emailService.sendSFTPExceptionEmail("SFTP file count Failed from path " + path, bankName);
log.error("{} :: getSFTPSuccessfulFileCount() Failed for {}. Error : {}",
refundType,
bankName,
ex.getMessage(),
ex);
}
return SFTPPushFileCountDto.builder()
.totalSuccessfulPush(totalSuccessfulPush)
.totalFailedPush(totalFailedPush)
.build();
}
We can't reproduce the problem in our environment.
Can anybody help?

How to trim video with start and end pos of seekbar using FFmpeg android?

String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};
private void trimVideo(ProgressDialog progressDialog) {
outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
+ "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
+ "filter_apply.mp4";
if (startTrim.equals("")) {
startTrim = "00:00:00";
}
if (endTrim.equals("")) {
endTrim = timeTrim(player.getDuration());
}
String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};
execFFmpegBinary1(cmd, progressDialog);
}
private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {
ProgressDialog progressDialog = prpg;
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
#Override
public void onFailure(String s) {
progressDialog.dismiss();
Toast.makeText(PlayerActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
Log.d(TAG, "FAILED with output : " + s);
}
#Override
public void onSuccess(String s) {
Log.d(TAG, "SUCCESS wgith output : " + s);
String finalPath = outputAudioMux;
videoPath = outputAudioMux;
Toast.makeText(PlayerActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(PlayerActivity.this, ShareVideoActivity.class);
intent.putExtra("pathGPU", finalPath);
startActivity(intent);
finish();
MediaScannerConnection.scanFile(PlayerActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);
}
#Override
public void onProgress(String s) {
Log.d(TAG, "Started gcommand : ffmpeg " + command);
progressDialog.setMessage("Please Wait video triming...");
}
#Override
public void onStart() {
Log.d(TAG, "Startedf command : ffmpeg " + command);
}
#Override
public void onFinish() {
Log.d(TAG, "Finished f command : ffmpeg " + command);
progressDialog.dismiss();
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
}
}

when i start .jar app on mac do nothing

I have made a simple JavaFx application, wich read/write the txt file (the code is below). I have tested it on windows platform (7 and higher).
After i gave app my friend for test on Mac. But when we run it, just do nothing. The GUI did not appear.
I tried run it through terminal (just "drug and drop" the icon to terminal, then enter in teminal. I don't know did i do right?) and terminal returned message "Permission denied". Can somebody explain what is require to run application, and what is not permitted exactly?
I found the similar question there but it have not answer...
Code:
import javafx.application.*;
import javafx.concurrent.Task;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.text.Font;
import javafx.stage.*;
import javafx.scene.layout.*;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class Main extends Application {
static Properties props;
static double fontSize;
static String charsetName;
static long mills;
static String delimiter;
static String pathToDictionary;
static String pathErrLog;
static {
String pathFileProps = System.getProperty("user.dir") + "\\props.txt";
props = new Properties();
try {
FileInputStream fis = new FileInputStream(pathFileProps);
props.load(fis);
fontSize = Double.parseDouble(props.getProperty("Font"));
charsetName = props.getProperty("Charset");
mills = Long.parseLong(props.getProperty("mills"));
delimiter = props.getProperty("delimiter");
pathToDictionary = props.getProperty("dict.path");
fis.close();
} catch (IOException e) {
try {
props.put("Font", "20");
props.put("Charset", "UTF-8");
props.put("mills", "1000");
props.put("delimiter", "\t");
props.put("dict.path", System.getProperty("user.dir") + "\\dict.txt");
System.out.println("dictPath:" + System.getProperty("user.dir") + "\\dict.txt");
System.setProperty("file.encoding", "UTF-8");
FileOutputStream fos = new FileOutputStream(pathFileProps);
props.store(fos
, "Props description:" + "\n" +
"Font" + "\t\t" + "size of font's words " + "\n" +
"Charset" + "\t" + "charset of file-dictionary" + "\n" +
"mills" + "\t\t" + "per animations in milliseconds" + "\n" +
"delimiter" + "\t" + "delimiter between a pair words in string: eng<->rus \"<->\" is delimiter there." + "\n" +
"dict.path" + "\t" + "path to file-dictionary. Use \"/\"-symbol in path. Ex: C:/temp/dict.txt" + "\n" +
"\t\t\t" + "Use only eng symbols to set path!" + "\n" +
"\tYou can change only values!\n");
fos.close();
System.exit(0);
} catch (IOException e1) {
errPrint(e1,"Ошибка создания файла: " + pathFileProps + "\n");
}
}
}
ArrayList<String> dictionary = new ArrayList<>();
public static void errPrint(Exception exc, String note) {
if (pathErrLog == null) {
pathErrLog = System.getProperty("user.dir") + "\\errors.log";
}
try {
PrintWriter outFile = new PrintWriter(new FileWriter(pathErrLog, true));
outFile.println(note);
exc.printStackTrace(outFile);
outFile.close();
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
launch(args);
}
public void init() throws IOException {
try {
BufferedReader reader = new BufferedReader(new FileReader(pathToDictionary));
int cnt = 0;
while (reader.ready()) {
String line = new String(reader.readLine().getBytes(), Charset.forName(charsetName));
dictionary.add(line);
}
} catch (FileNotFoundException e) {
errPrint(e,"Не найден файл " + pathToDictionary);
} catch (IOException e) {
errPrint(e,"Ошибка чтения файла " + pathToDictionary);
}
}
public void start(Stage myStage) {
myStage.setTitle("WordsLearner");
SplitPane sp = new SplitPane();
sp.setOrientation(Orientation.VERTICAL);
Label labelUp = new Label();
Label labelDw = new Label();
labelUp.setFont(new Font(fontSize));
labelDw.setFont(new Font(fontSize));
Scene scene = new Scene(sp, 600, 200);
myStage.setScene(scene);
final StackPane sp1 = new StackPane();
sp1.getChildren().add(labelUp);
sp1.setAlignment(Pos.BOTTOM_CENTER);
final StackPane sp2 = new StackPane();
sp2.getChildren().add(labelDw);
sp2.setAlignment(Pos.TOP_CENTER);
final boolean[] flag = {true};
sp.setOnMouseClicked(event -> {
Task<Void> task = new Task<Void>() {
#Override
public Void call() throws Exception {
if (flag[0]) {
flag[0] = false;
final String[] str = new String[1];
final String[] eng = new String[1];
final String[] rus = new String[1];
while (true) {
Platform.runLater(() -> {
try {
str[0] = dictionary.get(ThreadLocalRandom.current().nextInt(0, dictionary.size()));
eng[0] = str[0].split(delimiter)[0];
rus[0] = str[0].split(delimiter)[1];
labelUp.setText(eng[0]);
labelDw.setText(rus[0]);
} catch (Exception e) {
System.exit(-1);
}
});
Thread.sleep(mills);
}
}
return null;
}
};
new Thread(task).start();
});
sp.getItems().addAll(sp1, sp2);
sp.setDividerPositions(0.5f, 0.5f);
myStage.show();
}
public void stop() {
System.exit(0);
}
}

Using one progressDialog in two or more android stringRequest Volley

In my code I have to stringRequest Volley that works just fine, but now I want to use a progressDialog. I have create 1 method to put the progressDialog like this
private void showProgress(String message) {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Data " + message);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
and I have these 2 stringRequest like this:
private void fetchDataPoMurni(final String tipe, final String user_id, final String last_date) {
showProgress("Murni");
String tag_string_req = "Request Po Dapat";
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
AppConfig.URL_FETCH_REPORT_PO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if(!error) {
JSONArray resultPo = jsonObject.getJSONArray("result");
for(int i = 0; i < resultPo.length(); i++) {
JSONObject result = (JSONObject) resultPo.get(i);
String _cabang_id = result.getString("branch_id");
String _area_id = result.getString("areacode");
String _cabang = result.getString("branch_name");
Log.d("FETCHING DATA MURNI: ", _cabang_id + " " + _area_id + " " + _cabang);
dataBaseHelper.insertDataPoMurni(new PoModel(_cabang_id.trim(), _area_id.trim(), _cabang.trim()));
}
} else {
String errorMsg = jsonObject.getString("result");
showAlertDialog(errorMsg);
}
} catch (JSONException e) {
showAlertDialog(e.getMessage());
}
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
showAlertDialog(volleyError.getMessage());
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tipe", tipe);
params.put("uid", user_id);
params.put("last_date", last_date);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
and the other request:
private void fetchDataPoDapat(final String tipe, final String user_id, final String last_date) {
showProgress("Dapat");
String tag_string_req = "Request Po Dapat";
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
AppConfig.URL_FETCH_REPORT_PO,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
boolean error = jsonObject.getBoolean("error");
if(!error) {
JSONArray resultPo = jsonObject.getJSONArray("result");
for(int i = 0; i < resultPo.length(); i++) {
JSONObject result = (JSONObject) resultPo.get(i);
String _cabang_id = result.getString("branch_id");
String _area_id = result.getString("areacode");
String _cabang = result.getString("branch_name");
Log.d("FETCHING DATA DAPAT : ", _cabang_id + " " + _area_id + " " + _cabang);
dataBaseHelper.insertDataPoDapat(new PoModel(_cabang_id.trim(), _area_id.trim(), _cabang.trim()));
}
} else {
String errorMsg = jsonObject.getString("result");
showAlertDialog(errorMsg);
}
} catch (JSONException e) {
showAlertDialog(e.getMessage());
}
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
showAlertDialog(volleyError.getMessage());
if (progressDialog != null) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tipe", tipe);
params.put("uid", user_id);
params.put("last_date", last_date);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest, tag_string_req);
}
I execute the 2 request through a method like this:
private void exeRequest() {
fetchDataPoMurni(valuea,value2,value3);
fetchDataPoDapat(valueb,value2,value3);
}
the progressDialog is showing, and the message is changing, but the problem is when reach the second request the progressDialog doesn't want to dismiss.
Whats wrong with my code above, and how to achieve what I want?
private void showProgress(String message) {
progressDialog=null;// Initialize to null
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Loading Data " + message);
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
Try this .. Initialize all instances of the progressDialog to null as soon as you create a new progress dialog

Resources