List of usage examples for java.lang StringBuffer delete
@Override public synchronized StringBuffer delete(int start, int end)
From source file:com.github.gekoh.yagen.ddl.CreateDDL.java
public String updateCreateTable(Dialect dialect, StringBuffer buf, String tableName, Map columnMap) { LOG.info("modify DDL created by hibernate for table {}", tableName); boolean isOracle = isOracle(dialect); String nameLC = tableName.toLowerCase(); String entityClassName = getEntityClassName(nameLC); Set<String> columns = new LinkedHashSet<String>(columnMap.keySet()); if (!renderTable(nameLC)) { return "-- skipped creation statement for table '" + tableName + "' as the mapped entity was not chosen to be processed"; }/*from w ww . ja v a 2 s. co m*/ TableConfig tableConfig = tblNameToConfig.get(nameLC); checkTableName(dialect, tableName); if (externalViews.contains(nameLC)) { return "-- skipped creation statement for table '" + tableName + "' since there will be a view in place"; } String sqlCreate = buf.toString(); buf = new StringBuffer(); Map<String, String> comments = getProfile().getComments() != null ? getProfile().getComments().get(nameLC) : null; String liveTableName = nameLC; Set<String> columnNames = columns; List<String> pkCols = getPkColumnNamesFrom(sqlCreate); if (comments != null && comments.size() < 1) { comments = null; } Auditable auditable = tableConfig.getTableAnnotationOfType(Auditable.class); if (auditable != null && auditable.createNonExistingColumns()) { sqlCreate = addAuditColumns(dialect, sqlCreate, columns); } sqlCreate = processCascadeNullable(dialect, buf, nameLC, sqlCreate, tableConfig.getColumnNamesIsCascadeNullable()); String i18nFK = tableConfig.getI18nBaseEntityFkCol(); if (i18nFK != null) { String baseEntityTableName = tableConfig.getI18nBaseEntityTblName(); String i18nTblName = getProfile().getNamingStrategy().tableName(getI18NDetailTableName(nameLC)); liveTableName = i18nTblName; columnNames = getI18NEntityColumns(columns); sqlCreate = getI18NDetailTableCreateString(dialect, sqlCreate, i18nTblName, i18nFK); addDropStatement(nameLC, getIfExistsDropStatement(dialect, "drop table " + i18nTblName, null)); pkCols = getPkColumnNamesFrom(sqlCreate); if (dialect.supportsCommentOn()) { buf.append(STATEMENT_SEPARATOR).append("comment on table ").append(i18nTblName) .append(" is 'Base table for I18N descriptions, for comments see view ").append(nameLC) .append("'\n"); } deferredDdl.append(STATEMENT_SEPARATOR).append(getI18NDetailViewCreateString(dialect, nameLC, baseEntityTableName, i18nTblName, i18nFK, columnNames)); if (comments != null && isOracle) { addComments(deferredDdl, nameLC, comments); comments = null; } writeI18NDetailViewTriggerCreateString(dialect, deferredDdl, nameLC, i18nTblName, i18nFK, columnNames); } if (comments != null && isOracle) { addComments(buf, nameLC, comments); } addAuditTrigger(dialect, buf, liveTableName, columns); IntervalPartitioning partitioning = tableConfig.getTableAnnotationOfType(IntervalPartitioning.class); TemporalEntity temporalEntity = getProfile().isNoHistory() ? null : tableConfig.getTableAnnotationOfType(TemporalEntity.class); if (temporalEntity != null) { try { String histTableName; if (entityClassName != null) { String hstEntityClassName = entityClassName + CreateEntities.HISTORY_ENTITY_SUFFIX; histTableName = getProfile().getNamingStrategy().classToTableName(hstEntityClassName); // this will throw an exception when the history entity class is not found TableConfig hstConfig = new TableConfig(this, Class.forName(hstEntityClassName), histTableName); hstConfig.setTableToBeRendered(false); tblNameToConfig.put(hstConfig.getTableName(), hstConfig); } else { // there is no entity for the live table, e.g. for ManyToMany relations histTableName = getProfile().getNamingStrategy().tableName(temporalEntity.historyTableName()); } Matcher tblMatcher = TBL_PATTERN_WO_PK.matcher(sqlCreate); if (!tblMatcher.find()) { throw new IllegalStateException("cannot find create table statement in sql: " + sqlCreate); } String histColNameLC = temporalEntity.historyTimestampColumnName().toLowerCase(); List<String> historyRelevantCols = getHistoryRelevantColumns(columnNames, temporalEntity.ignoreChangeOfColumns(), histColNameLC); if (StringUtils.isEmpty(histTableName)) { histTableName = tblMatcher.group(TBL_PATTERN_WO_PK_IDX_TBLNAME) + Constants._HST; } if (pkCols == null) { JoinTable joinTable = tableConfig.getTableAnnotationOfType(JoinTable.class); CollectionTable collectionTable = tableConfig.getTableAnnotationOfType(CollectionTable.class); javax.persistence.UniqueConstraint[] uniqueConstraints = joinTable != null ? joinTable.uniqueConstraints() : collectionTable != null ? collectionTable.uniqueConstraints() : null; if (uniqueConstraints == null || uniqueConstraints.length < 1) { throw new IllegalStateException("cannot create history for table " + liveTableName + " since this table has no unique or primary key"); } pkCols = Arrays.asList(uniqueConstraints[0].columnNames()); } buf.append(STATEMENT_SEPARATOR).append("-- adding history table due to annotation ") .append(temporalEntity.annotationType().getName()).append(" on entity of table ") .append(tableName).append("\n").append(getHistTableSqlCreateString(dialect, sqlCreate, histTableName, histColNameLC, columnNames, pkCols, partitioning)); if (isOracle) { buf.append(STATEMENT_SEPARATOR); buf.append("-- creating trigger for inserting history rows from table ").append(tableName) .append("\n").append(getOracleHistTriggerSql(dialect, liveTableName, histTableName, histColNameLC, columnNames, pkCols, historyRelevantCols)) .append("\n/"); } else if (isPostgreSql(dialect)) { buf.append(STATEMENT_SEPARATOR).append(getPostgreSQLHistTriggerFunction(dialect, liveTableName, histTableName, histColNameLC, columnNames, pkCols, historyRelevantCols)).append("\n/"); buf.append(STATEMENT_SEPARATOR).append("create trigger ").append(liveTableName).append("_htU\n") .append("after update on ").append(liveTableName).append("\n").append("for each row\n") .append("when ("); for (String historyRelevantCol : historyRelevantCols) { buf.append("new.").append(historyRelevantCol).append(" is distinct from old.") .append(historyRelevantCol).append(" or\n"); } buf.delete(buf.length() - 4, buf.length()); buf.append(")\nexecute procedure ").append(liveTableName).append("_htr_function()"); buf.append(STATEMENT_SEPARATOR).append("create trigger ").append(liveTableName).append("_htr\n") .append("after insert or delete on ").append(liveTableName).append("\n") .append("for each row\n").append("execute procedure ").append(liveTableName) .append("_htr_function()"); } else { buf.append(getHsqlDBHistTriggerSql(dialect, liveTableName, histTableName, histColNameLC, columnNames, pkCols, historyRelevantCols)); } if (!historyInitSet) { getProfile().addHeaderDdl(new DDLGenerator.AddTemplateDDLEntry( CreateDDL.class.getResource("/com/github/gekoh/yagen/ddl/InitHistory.ddl.sql"))); historyInitSet = true; } } catch (ClassNotFoundException e) { LOG.info( "not generating history table of live table {} since corresponding history entity class not found in classpath", nameLC); } } for (Sequence sequence : tableConfig.getSequences()) { String seqName = getProfile().getNamingStrategy().sequenceName(sequence.name()); buf.append(STATEMENT_SEPARATOR); if (objectNames.contains(seqName.toLowerCase())) { buf.append( "-- WARNING: duplicate definition of sequence or name already defined for another object!\n--"); } else { checkObjectName(dialect, seqName.toLowerCase()); } buf.append("create sequence ").append(seqName).append(" start with ").append(sequence.startWith()) .append(" increment by ").append(sequence.incrementBy()); if (sequence.cache() > 1) { buf.append(" cache ").append(sequence.cache()); } } if (supportsPartitioning(dialect) && partitioning != null) { sqlCreate = addPartitioning(buf, partitioning, nameLC, sqlCreate, columns, pkCols); } sqlCreate = addConstraintsAndNames(dialect, buf, sqlCreate, nameLC, tableConfig.getColumnNameToEnumCheckConstraints()); sqlCreate = addDefaultValues(sqlCreate, nameLC); addIndexes(buf, dialect, tableConfig); if (buf.length() == 0) { return sqlCreate; } getProfile().duplex(ObjectType.TABLE, tableName, sqlCreate); buf.insert(0, sqlCreate); buf.insert(0, STATEMENT_SEPARATOR); return buf.toString(); }
From source file:usbong.android.likha_collection_1.UsbongDecisionTreeEngineActivity.java
public void processNextButtonPressed() { wasNextButtonPressed = true;//from w ww .jav a2s .c o m hasUpdatedDecisionTrackerContainer = false; //edited by Mike, 20160417 if ((mTts != null) && (mTts.isSpeaking())) { mTts.stop(); } //edited by Mike, 20160417 if ((myMediaPlayer != null) && (myMediaPlayer.isPlaying())) { myMediaPlayer.stop(); } if (currAudioRecorder != null) { try { //if stop button is pressable if (stopButton.isEnabled()) { currAudioRecorder.stop(); } if (currAudioRecorder.isPlaying()) { currAudioRecorder.stopPlayback(); } } catch (Exception e) { e.printStackTrace(); } String path = currAudioRecorder.getPath(); // System.out.println(">>>>>>>>>>>>>>>>>>>currAudioRecorder: "+currAudioRecorder); if (!attachmentFilePaths.contains(path)) { attachmentFilePaths.add(path); // System.out.println(">>>>>>>>>>>>>>>>adding path: "+path); } } //END_STATE_SCREEN = last screen if (currScreen == UsbongConstants.END_STATE_SCREEN) { int usbongAnswerContainerSize = usbongAnswerContainer.size(); StringBuffer outputStringBuffer = new StringBuffer(); for (int i = 0; i < usbongAnswerContainerSize; i++) { outputStringBuffer.append(usbongAnswerContainer.elementAt(i)); } myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/"; if (UsbongUtils.STORE_OUTPUT) { try { UsbongUtils.createNewOutputFolderStructure(); } catch (Exception e) { e.printStackTrace(); } UsbongUtils.storeOutputInSDCard( UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString()); } else { UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH + myOutputDirectory)); } //wasNextButtonPressed=false; //no need to make this true, because this is the last node hasUpdatedDecisionTrackerContainer = true; /* //send to server UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv"); //send to email Intent emailIntent = UsbongUtils.performEmailProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv", attachmentFilePaths); emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // emailIntent.addFlags(RESULT_OK); startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS); */ //added by Mike, Sept. 10, 2014 UsbongUtils.clearTempFolder(); //added by Mike, 20160415 if (UsbongUtils.IS_IN_AUTO_LOOP_MODE) { //added by Mike, 20161118 AppRater.showRateDialog(this); isAutoLoopedTree = true; initParser(myTree); return; } else { //return to main activity finish(); //added by Mike, 20161118 Intent toUsbongMainActivityIntent = new Intent(UsbongDecisionTreeEngineActivity.this, UsbongMainActivity.class); toUsbongMainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); toUsbongMainActivityIntent.putExtra("completed_tree", "true"); startActivity(toUsbongMainActivityIntent); } } else { if (currScreen == UsbongConstants.YES_NO_DECISION_SCREEN) { RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton); RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton); if (myYesRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else if (myNoRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfNo; // usbongAnswerContainer.addElement("N;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else { //if no radio button was checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.SEND_TO_WEBSERVER_SCREEN) { RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton); RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton); if (myYesRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfYes; // usbongAnswerContainer.addElement("Y;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement()); // wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer hasUpdatedDecisionTrackerContainer = true; //edited by Mike, March 4, 2013 //"save" the output into the SDCard as "output.txt" // int usbongAnswerContainerSize = usbongAnswerContainer.size(); int usbongAnswerContainerSize = usbongAnswerContainerCounter; StringBuffer outputStringBuffer = new StringBuffer(); for (int i = 0; i < usbongAnswerContainerSize; i++) { outputStringBuffer.append(usbongAnswerContainer.elementAt(i)); } myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/"; try { UsbongUtils.createNewOutputFolderStructure(); } catch (Exception e) { e.printStackTrace(); } UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString()); //send to server UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv"); } else if (myNoRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfNo; // usbongAnswerContainer.addElement("N;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; } else { //if no radio button was checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; // initParser(); } initParser(); } else if (currScreen == UsbongConstants.SEND_TO_CLOUD_BASED_SERVICE_SCREEN) { RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton); RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton); if (myYesRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfYes; // usbongAnswerContainer.addElement("Y;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement()); // wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer hasUpdatedDecisionTrackerContainer = true; StringBuffer sb = new StringBuffer(); for (int i = 0; i < decisionTrackerContainer.size(); i++) { sb.append(decisionTrackerContainer.elementAt(i)); } Log.d(">>>>>>>>>>>>>decisionTrackerContainer", sb.toString()); //edited by Mike, March 4, 2013 //"save" the output into the SDCard as "output.txt" // int usbongAnswerContainerSize = usbongAnswerContainer.size(); int usbongAnswerContainerSize = usbongAnswerContainerCounter; StringBuffer outputStringBuffer = new StringBuffer(); for (int i = 0; i < usbongAnswerContainerSize; i++) { outputStringBuffer.append(usbongAnswerContainer.elementAt(i)); } myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/"; try { UsbongUtils.createNewOutputFolderStructure(); } catch (Exception e) { e.printStackTrace(); } UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString()); //send to cloud-based service Intent sendToCloudBasedServiceIntent = UsbongUtils .performSendToCloudBasedServiceProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv", attachmentFilePaths); /*emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); */ // emailIntent.addFlags(RESULT_OK); // startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS); //answer from Llango J, stackoverflow //Reference: http://stackoverflow.com/questions/7479883/problem-with-sending-email-goes-back-to-previous-activity; //last accessed: 22 Oct. 2012 startActivity( Intent.createChooser(sendToCloudBasedServiceIntent, "Send to Cloud-based Service:")); } else if (myNoRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfNo; // usbongAnswerContainer.addElement("N;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; } else { //if no radio button was checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; // initParser(); /* if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed=false; hasUpdatedDecisionTrackerContainer=true; return; } else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" // usbongAnswerContainer.addElement("A;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } */ } /* currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" usbongAnswerContainer.addElement("Any;"); */ initParser(); } else if (currScreen == UsbongConstants.MULTIPLE_CHECKBOXES_SCREEN) { // requiredTotalCheckedBoxes LinearLayout myMultipleCheckboxesLinearLayout = (LinearLayout) findViewById( R.id.multiple_checkboxes_linearlayout); StringBuffer sb = new StringBuffer(); int totalCheckedBoxes = 0; int totalCheckBoxChildren = myMultipleCheckboxesLinearLayout.getChildCount(); //begin with i=1, because i=0 is for checkboxes_textview for (int i = 1; i < totalCheckBoxChildren; i++) { if (((CheckBox) myMultipleCheckboxesLinearLayout.getChildAt(i)).isChecked()) { totalCheckedBoxes++; sb.append("," + (i - 1)); //do a (i-1) so that i starts with 0 for the checkboxes (excluding checkboxes_textview) to maintain consistency with the other components } } if (totalCheckedBoxes >= requiredTotalCheckedBoxes) { currUsbongNode = nextUsbongNodeIfYes; sb.insert(0, "Y"); //insert in front of stringBuffer sb.append(";"); } else { currUsbongNode = nextUsbongNodeIfNo; sb.delete(0, sb.length()); sb.append("N,;"); //make sure to add the comma } // usbongAnswerContainer.addElement(sb.toString()); UsbongUtils.addElementToContainer(usbongAnswerContainer, sb.toString(), usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup); // if (UsbongUtils.IS_IN_DEBUG_MODE==false) { if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { // usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } // } /* else { // usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId()+";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } */ } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup); /* if (UsbongUtils.IS_IN_DEBUG_MODE==false) { */ if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { if (myMultipleRadioButtonsWithAnswerScreenAnswer .equals("" + myRadioGroup.getCheckedRadioButtonId())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); } else { currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); } usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.LINK_SCREEN) { RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup); try { currUsbongNode = UsbongUtils.getLinkFromRadioButton( radioButtonsContainer.elementAt(myRadioGroup.getCheckedRadioButtonId())); } catch (Exception e) { //if the user hasn't ticked any radio button yet //put the currUsbongNode to default // currUsbongNode = UsbongUtils.getLinkFromRadioButton(nextUsbongNodeIfYes); //nextUsbongNodeIfNo will also do, since this is "Any" //of course, showPleaseAnswerAlert() will be called //edited by Mike, 20160613 //don't change the currUsbongNode anymore if no radio button has been ticked } // Log.d(">>>>>>>>>>currUsbongNode",currUsbongNode); if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked // if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } // } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { // usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } /* } else { usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";"); initParser(); } */ } else if ((currScreen == UsbongConstants.TEXTFIELD_SCREEN) || (currScreen == UsbongConstants.TEXTFIELD_WITH_UNIT_SCREEN) || (currScreen == UsbongConstants.TEXTFIELD_NUMERICAL_SCREEN)) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext); // if (UsbongUtils.IS_IN_DEBUG_MODE==false) { //if it's blank if (myTextFieldScreenEditText.getText().toString().trim().equals("")) { if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" // usbongAnswerContainer.addElement("A;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { // usbongAnswerContainer.addElement("A,"+myTextFieldScreenEditText.getText()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myTextFieldScreenEditText.getText() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.TEXTFIELD_WITH_ANSWER_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext); //if it's blank if (myTextFieldScreenEditText.getText().toString().trim().equals("")) { if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myTextFieldScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else { //added by Mike, Jan. 27, 2014 Vector<String> myPossibleAnswers = new Vector<String>(); StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer( myTextFieldWithAnswerScreenAnswer, "||"); if (myPossibleAnswersStringTokenizer != null) { while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textFieldWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike") myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken()); } } int size = myPossibleAnswers.size(); for (int i = 0; i < size; i++) { if (myPossibleAnswers.elementAt(i) .equals(myTextFieldScreenEditText.getText().toString().trim())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myTextFieldScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); break; } if (i == size - 1) { //if this is the last element in the vector currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N," + myTextFieldScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); } } /* if (myTextFieldWithAnswerScreenAnswer.equals(myTextFieldScreenEditText.getText().toString().trim())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter); } else { currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter); } */ usbongAnswerContainerCounter++; initParser(); } } else if ((currScreen == UsbongConstants.TEXTAREA_SCREEN)) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext); // if (UsbongUtils.IS_IN_DEBUG_MODE==false) { //if it's blank if (myTextAreaScreenEditText.getText().toString().trim().equals("")) { if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { // usbongAnswerContainer.addElement("A,"+myTextAreaScreenEditText.getText()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myTextAreaScreenEditText.getText() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.TEXTAREA_WITH_ANSWER_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext); //if it's blank if (myTextAreaScreenEditText.getText().toString().trim().equals("")) { if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myTextAreaScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else { /* if (myTextAreaWithAnswerScreenAnswer.equals(myTextAreaScreenEditText.getText().toString().trim())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter); } else { currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter); } */ //added by Mike, Jan. 27, 2014 Vector<String> myPossibleAnswers = new Vector<String>(); StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer( myTextAreaWithAnswerScreenAnswer, "||"); if (myPossibleAnswersStringTokenizer != null) { while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textAreaWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike||mike") myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken()); } } int size = myPossibleAnswers.size(); for (int i = 0; i < size; i++) { // Log.d(">>>>>>myPossibleAnswers: ",myPossibleAnswers.elementAt(i)); if (myPossibleAnswers.elementAt(i) .equals(myTextAreaScreenEditText.getText().toString().trim())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myTextAreaScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); break; } if (i == size - 1) { //if this is the last element in the vector currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N," + myTextAreaScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); } } usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.GPS_LOCATION_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do TextView myLongitudeTextView = (TextView) findViewById(R.id.longitude_textview); TextView myLatitudeTextView = (TextView) findViewById(R.id.latitude_textview); // usbongAnswerContainer.addElement(myLongitudeTextView.getText()+","+myLatitudeTextView.getText()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myLongitudeTextView.getText() + "," + myLatitudeTextView.getText() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else if (currScreen == UsbongConstants.SIMPLE_ENCRYPT_SCREEN) { EditText myPinEditText = (EditText) findViewById(R.id.pin_edittext); if (myPinEditText.getText().toString().length() != 4) { String message = ""; if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) { message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageFILIPINO); } else if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) { message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageJAPANESE); } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) { message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageENGLISH); } new AlertDialog.Builder(UsbongDecisionTreeEngineActivity.this).setTitle("Hey!") .setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } else { int yourKey = Integer.parseInt(myPinEditText.getText().toString()); currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; // Log.d(">>>>>>>start encode","encode"); for (int i = 0; i < usbongAnswerContainerCounter; i++) { try { usbongAnswerContainer.set(i, UsbongUtils.performSimpleFileEncrypt(yourKey, usbongAnswerContainer.elementAt(i))); // Log.d(">>>>>>"+i,""+usbongAnswerContainer.get(i)); // Log.d(">>>decoded"+i,""+UsbongUtils.performSimpleFileDecode(yourKey, usbongAnswerContainer.get(i))); } catch (Exception e) { e.printStackTrace(); } } initParser(); } } else if (currScreen == UsbongConstants.DATE_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //added by Mike, 13 Oct. 2015 DatePicker myDatePicker = (DatePicker) findViewById(R.id.date_picker); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myDatePicker.getMonth() + myDatePicker.getDayOfMonth() + "," + myDatePicker.getYear() + ";", usbongAnswerContainerCounter); /* Spinner dateMonthSpinner = (Spinner) findViewById(R.id.date_month_spinner); Spinner dateDaySpinner = (Spinner) findViewById(R.id.date_day_spinner); EditText myDateYearEditText = (EditText)findViewById(R.id.date_edittext); // usbongAnswerContainer.addElement("A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() + // dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," + // myDateYearEditText.getText().toString()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() + dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," + myDateYearEditText.getText().toString()+";", usbongAnswerContainerCounter); */ usbongAnswerContainerCounter++; // System.out.println(">>>>>>>>>>>>>Date screen: "+usbongAnswerContainer.lastElement()); initParser(); } else if (currScreen == UsbongConstants.TIMESTAMP_DISPLAY_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, timestampString + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else if (currScreen == UsbongConstants.QR_CODE_READER_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do if (!myQRCodeContent.equals("")) { // usbongAnswerContainer.addElement("Y,"+myQRCodeContent+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myQRCodeContent + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; } else { // usbongAnswerContainer.addElement("N;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; } initParser(); } else if ((currScreen == UsbongConstants.DCAT_SUMMARY_SCREEN)) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do /* LinearLayout myDCATSummaryLinearLayout = (LinearLayout)findViewById(R.id.dcat_summary_linearlayout); int total = myDCATSummaryLinearLayout.getChildCount(); StringBuffer dcatSummary= new StringBuffer(); for (int i=0; i<total; i++) { dcatSummary.append(((TextView) myDCATSummaryLinearLayout.getChildAt(i)).getText().toString()); } */ // UsbongUtils.addElementToContainer(usbongAnswerContainer, "dcat_end;", usbongAnswerContainerCounter); UsbongUtils.addElementToContainer(usbongAnswerContainer, "dcat_end," + myDcatSummaryStringBuffer.toString() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else { //TODO: do this for now currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" // usbongAnswerContainer.addElement("A;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } } }
From source file:usbong.android.retrocc.UsbongDecisionTreeEngineActivity.java
public void processNextButtonPressed() { wasNextButtonPressed = true;/*from w ww . ja va 2s . com*/ hasUpdatedDecisionTrackerContainer = false; //edited by Mike, 20160417 if ((mTts != null) && (mTts.isSpeaking())) { mTts.stop(); } //edited by Mike, 20160417 if ((myMediaPlayer != null) && (myMediaPlayer.isPlaying())) { myMediaPlayer.stop(); } if (currAudioRecorder != null) { try { //if stop button is pressable if (stopButton.isEnabled()) { currAudioRecorder.stop(); } if (currAudioRecorder.isPlaying()) { currAudioRecorder.stopPlayback(); } } catch (Exception e) { e.printStackTrace(); } String path = currAudioRecorder.getPath(); // System.out.println(">>>>>>>>>>>>>>>>>>>currAudioRecorder: "+currAudioRecorder); if (!attachmentFilePaths.contains(path)) { attachmentFilePaths.add(path); // System.out.println(">>>>>>>>>>>>>>>>adding path: "+path); } } //END_STATE_SCREEN = last screen if (currScreen == UsbongConstants.END_STATE_SCREEN) { int usbongAnswerContainerSize = usbongAnswerContainer.size(); StringBuffer outputStringBuffer = new StringBuffer(); for (int i = 0; i < usbongAnswerContainerSize; i++) { outputStringBuffer.append(usbongAnswerContainer.elementAt(i)); } myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/"; if (UsbongUtils.STORE_OUTPUT) { try { UsbongUtils.createNewOutputFolderStructure(); } catch (Exception e) { e.printStackTrace(); } UsbongUtils.storeOutputInSDCard( UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString()); } else { UsbongUtils.deleteRecursive(new File(UsbongUtils.BASE_FILE_PATH + myOutputDirectory)); } //wasNextButtonPressed=false; //no need to make this true, because this is the last node hasUpdatedDecisionTrackerContainer = true; /* //send to server UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv"); //send to email Intent emailIntent = UsbongUtils.performEmailProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getTimeStamp() + ".csv", attachmentFilePaths); emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // emailIntent.addFlags(RESULT_OK); startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS); */ //added by Mike, Sept. 10, 2014 UsbongUtils.clearTempFolder(); //added by Mike, 20160415 if (UsbongUtils.IS_IN_AUTO_LOOP_MODE) { //added by Mike, 20161117 AppRater.showRateDialog(this); isAutoLoopedTree = true; initParser(myTree); return; } else { //return to main activity finish(); //added by Mike, 20161117 Intent toUsbongMainActivityIntent = new Intent(UsbongDecisionTreeEngineActivity.this, UsbongMainActivity.class); toUsbongMainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); toUsbongMainActivityIntent.putExtra("completed_tree", "true"); startActivity(toUsbongMainActivityIntent); } } else { if (currScreen == UsbongConstants.YES_NO_DECISION_SCREEN) { RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton); RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton); if (myYesRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else if (myNoRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfNo; // usbongAnswerContainer.addElement("N;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else { //if no radio button was checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.SEND_TO_WEBSERVER_SCREEN) { RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton); RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton); if (myYesRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfYes; // usbongAnswerContainer.addElement("Y;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement()); // wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer hasUpdatedDecisionTrackerContainer = true; //edited by Mike, March 4, 2013 //"save" the output into the SDCard as "output.txt" // int usbongAnswerContainerSize = usbongAnswerContainer.size(); int usbongAnswerContainerSize = usbongAnswerContainerCounter; StringBuffer outputStringBuffer = new StringBuffer(); for (int i = 0; i < usbongAnswerContainerSize; i++) { outputStringBuffer.append(usbongAnswerContainer.elementAt(i)); } myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/"; try { UsbongUtils.createNewOutputFolderStructure(); } catch (Exception e) { e.printStackTrace(); } UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString()); //send to server UsbongUtils.performFileUpload(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv"); } else if (myNoRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfNo; // usbongAnswerContainer.addElement("N;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; } else { //if no radio button was checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; // initParser(); } initParser(); } else if (currScreen == UsbongConstants.SEND_TO_CLOUD_BASED_SERVICE_SCREEN) { RadioButton myYesRadioButton = (RadioButton) findViewById(R.id.yes_radiobutton); RadioButton myNoRadioButton = (RadioButton) findViewById(R.id.no_radiobutton); if (myYesRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfYes; // usbongAnswerContainer.addElement("Y;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; decisionTrackerContainer.addElement(usbongAnswerContainer.lastElement()); // wasNextButtonPressed=false; //no need to make this true, because "Y;" has already been added to decisionTrackerContainer hasUpdatedDecisionTrackerContainer = true; StringBuffer sb = new StringBuffer(); for (int i = 0; i < decisionTrackerContainer.size(); i++) { sb.append(decisionTrackerContainer.elementAt(i)); } Log.d(">>>>>>>>>>>>>decisionTrackerContainer", sb.toString()); //edited by Mike, March 4, 2013 //"save" the output into the SDCard as "output.txt" // int usbongAnswerContainerSize = usbongAnswerContainer.size(); int usbongAnswerContainerSize = usbongAnswerContainerCounter; StringBuffer outputStringBuffer = new StringBuffer(); for (int i = 0; i < usbongAnswerContainerSize; i++) { outputStringBuffer.append(usbongAnswerContainer.elementAt(i)); } myOutputDirectory = UsbongUtils.getDateTimeStamp() + "/"; try { UsbongUtils.createNewOutputFolderStructure(); } catch (Exception e) { e.printStackTrace(); } UsbongUtils.storeOutputInSDCard(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv", outputStringBuffer.toString()); //send to cloud-based service Intent sendToCloudBasedServiceIntent = UsbongUtils .performSendToCloudBasedServiceProcess(UsbongUtils.BASE_FILE_PATH + myOutputDirectory + UsbongUtils.getDateTimeStamp() + ".csv", attachmentFilePaths); /*emailIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); */ // emailIntent.addFlags(RESULT_OK); // startActivityForResult(Intent.createChooser(emailIntent, "Email:"),EMAIL_SENDING_SUCCESS); //answer from Llango J, stackoverflow //Reference: http://stackoverflow.com/questions/7479883/problem-with-sending-email-goes-back-to-previous-activity; //last accessed: 22 Oct. 2012 startActivity(Intent.createChooser(sendToCloudBasedServiceIntent, "Email Book Request:")); } else if (myNoRadioButton.isChecked()) { currUsbongNode = nextUsbongNodeIfNo; // usbongAnswerContainer.addElement("N;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; } else { //if no radio button was checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; // initParser(); /* if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed=false; hasUpdatedDecisionTrackerContainer=true; return; } else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" // usbongAnswerContainer.addElement("A;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } */ } /* currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" usbongAnswerContainer.addElement("Any;"); */ initParser(); } else if (currScreen == UsbongConstants.MULTIPLE_CHECKBOXES_SCREEN) { // requiredTotalCheckedBoxes LinearLayout myMultipleCheckboxesLinearLayout = (LinearLayout) findViewById( R.id.multiple_checkboxes_linearlayout); StringBuffer sb = new StringBuffer(); int totalCheckedBoxes = 0; int totalCheckBoxChildren = myMultipleCheckboxesLinearLayout.getChildCount(); //begin with i=1, because i=0 is for checkboxes_textview for (int i = 1; i < totalCheckBoxChildren; i++) { if (((CheckBox) myMultipleCheckboxesLinearLayout.getChildAt(i)).isChecked()) { totalCheckedBoxes++; sb.append("," + (i - 1)); //do a (i-1) so that i starts with 0 for the checkboxes (excluding checkboxes_textview) to maintain consistency with the other components } } if (totalCheckedBoxes >= requiredTotalCheckedBoxes) { currUsbongNode = nextUsbongNodeIfYes; sb.insert(0, "Y"); //insert in front of stringBuffer sb.append(";"); } else { currUsbongNode = nextUsbongNodeIfNo; sb.delete(0, sb.length()); sb.append("N,;"); //make sure to add the comma } // usbongAnswerContainer.addElement(sb.toString()); UsbongUtils.addElementToContainer(usbongAnswerContainer, sb.toString(), usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup); // if (UsbongUtils.IS_IN_DEBUG_MODE==false) { if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { // usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } // } /* else { // usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId()+";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } */ } else if (currScreen == UsbongConstants.MULTIPLE_RADIO_BUTTONS_WITH_ANSWER_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup); /* if (UsbongUtils.IS_IN_DEBUG_MODE==false) { */ if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { if (myMultipleRadioButtonsWithAnswerScreenAnswer .equals("" + myRadioGroup.getCheckedRadioButtonId())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); } else { currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N," + myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); } usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.LINK_SCREEN) { RadioGroup myRadioGroup = (RadioGroup) findViewById(R.id.multiple_radio_buttons_radiogroup); try { currUsbongNode = UsbongUtils.getLinkFromRadioButton( radioButtonsContainer.elementAt(myRadioGroup.getCheckedRadioButtonId())); } catch (Exception e) { //if the user hasn't ticked any radio button yet //put the currUsbongNode to default currUsbongNode = UsbongUtils.getLinkFromRadioButton(nextUsbongNodeIfYes); //nextUsbongNodeIfNo will also do, since this is "Any" //of course, showPleaseAnswerAlert() will be called } // Log.d(">>>>>>>>>>currUsbongNode",currUsbongNode); if (myRadioGroup.getCheckedRadioButtonId() == -1) { //no radio button checked // if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_CHOOSE_AN_ANSWER_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } // } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { // usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, myRadioGroup.getCheckedRadioButtonId() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } /* } else { usbongAnswerContainer.addElement(myRadioGroup.getCheckedRadioButtonId()+";"); initParser(); } */ } else if ((currScreen == UsbongConstants.TEXTFIELD_SCREEN) || (currScreen == UsbongConstants.TEXTFIELD_WITH_UNIT_SCREEN) || (currScreen == UsbongConstants.TEXTFIELD_NUMERICAL_SCREEN)) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext); // if (UsbongUtils.IS_IN_DEBUG_MODE==false) { //if it's blank if (myTextFieldScreenEditText.getText().toString().trim().equals("")) { if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" // usbongAnswerContainer.addElement("A;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { //added by Mike, 20170207 TextView myTextFieldScreenTextView = (TextView) this.findViewById(R.id.textfield_textview); //Reference: http://stackoverflow.com/questions/23024831/android-shared-preferences-example //; last accessed: 20150609 //answer by Elenasys //added by Mike, 20170207 SharedPreferences.Editor editor = getSharedPreferences(UsbongConstants.MY_ACCOUNT_DETAILS, MODE_PRIVATE).edit(); if (myTextFieldScreenTextView.getText().toString().contains("First Name")) { editor.putString("firstName", myTextFieldScreenEditText.getText().toString()); } else if (myTextFieldScreenTextView.getText().toString().contains("Surname")) { editor.putString("surname", myTextFieldScreenEditText.getText().toString()); } else if (myTextFieldScreenTextView.getText().toString().contains("Contact Number")) { editor.putString("contactNumber", myTextFieldScreenEditText.getText().toString()); } else if (myTextFieldScreenTextView.getText().toString().contains("Shipping Address")) { editor.putString("shippingAddress", myTextFieldScreenEditText.getText().toString()); } editor.commit(); // usbongAnswerContainer.addElement("A,"+myTextFieldScreenEditText.getText()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myTextFieldScreenEditText.getText() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.TEXTFIELD_WITH_ANSWER_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; EditText myTextFieldScreenEditText = (EditText) findViewById(R.id.textfield_edittext); //if it's blank if (myTextFieldScreenEditText.getText().toString().trim().equals("")) { if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myTextFieldScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else { //added by Mike, Jan. 27, 2014 Vector<String> myPossibleAnswers = new Vector<String>(); StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer( myTextFieldWithAnswerScreenAnswer, "||"); if (myPossibleAnswersStringTokenizer != null) { while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textFieldWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike") myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken()); } } int size = myPossibleAnswers.size(); for (int i = 0; i < size; i++) { if (myPossibleAnswers.elementAt(i) .equals(myTextFieldScreenEditText.getText().toString().trim())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myTextFieldScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); break; } if (i == size - 1) { //if this is the last element in the vector currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N," + myTextFieldScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); } } /* if (myTextFieldWithAnswerScreenAnswer.equals(myTextFieldScreenEditText.getText().toString().trim())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter); } else { currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextFieldScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter); } */ usbongAnswerContainerCounter++; initParser(); } } else if ((currScreen == UsbongConstants.TEXTAREA_SCREEN)) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext); // if (UsbongUtils.IS_IN_DEBUG_MODE==false) { //if it's blank if (myTextAreaScreenEditText.getText().toString().trim().equals("")) { if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } // else { currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A,;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); // } } else { // usbongAnswerContainer.addElement("A,"+myTextAreaScreenEditText.getText()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myTextAreaScreenEditText.getText() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.TEXTAREA_WITH_ANSWER_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; EditText myTextAreaScreenEditText = (EditText) findViewById(R.id.textarea_edittext); //if it's blank if (myTextAreaScreenEditText.getText().toString().trim().equals("")) { if (!UsbongUtils.IS_IN_DEBUG_MODE) { if (!isAnOptionalNode) { showRequiredFieldAlert(PLEASE_ANSWER_FIELD_ALERT_TYPE); wasNextButtonPressed = false; hasUpdatedDecisionTrackerContainer = true; return; } } currUsbongNode = nextUsbongNodeIfYes; //choose Yes if "Any" UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myTextAreaScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else { /* if (myTextAreaWithAnswerScreenAnswer.equals(myTextAreaScreenEditText.getText().toString().trim())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter); } else { currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N,"+myTextAreaScreenEditText.getText().toString().trim()+";", usbongAnswerContainerCounter); } */ //added by Mike, Jan. 27, 2014 Vector<String> myPossibleAnswers = new Vector<String>(); StringTokenizer myPossibleAnswersStringTokenizer = new StringTokenizer( myTextAreaWithAnswerScreenAnswer, "||"); if (myPossibleAnswersStringTokenizer != null) { while (myPossibleAnswersStringTokenizer.hasMoreTokens()) { //get last element (i.e. Mike in "textAreaWithAnswer~Who is the founder of Usbong (nickname)?Answer=Mike||mike") myPossibleAnswers.add(myPossibleAnswersStringTokenizer.nextToken()); } } int size = myPossibleAnswers.size(); for (int i = 0; i < size; i++) { // Log.d(">>>>>>myPossibleAnswers: ",myPossibleAnswers.elementAt(i)); if (myPossibleAnswers.elementAt(i) .equals(myTextAreaScreenEditText.getText().toString().trim())) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myTextAreaScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); break; } if (i == size - 1) { //if this is the last element in the vector currUsbongNode = nextUsbongNodeIfNo; UsbongUtils.addElementToContainer(usbongAnswerContainer, "N," + myTextAreaScreenEditText.getText().toString().trim() + ";", usbongAnswerContainerCounter); } } usbongAnswerContainerCounter++; initParser(); } } else if (currScreen == UsbongConstants.GPS_LOCATION_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do TextView myLongitudeTextView = (TextView) findViewById(R.id.longitude_textview); TextView myLatitudeTextView = (TextView) findViewById(R.id.latitude_textview); // usbongAnswerContainer.addElement(myLongitudeTextView.getText()+","+myLatitudeTextView.getText()+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + myLongitudeTextView.getText() + "," + myLatitudeTextView.getText() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else if (currScreen == UsbongConstants.SIMPLE_ENCRYPT_SCREEN) { EditText myPinEditText = (EditText) findViewById(R.id.pin_edittext); if (myPinEditText.getText().toString().length() != 4) { String message = ""; if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_FILIPINO) { message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageFILIPINO); } else if (currLanguageBeingUsed == UsbongUtils.LANGUAGE_JAPANESE) { message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageJAPANESE); } else { //if (udtea.currLanguageBeingUsed==UsbongUtils.LANGUAGE_ENGLISH) { message = (String) getResources().getText(R.string.Usbong4DigitsPinAlertMessageENGLISH); } new AlertDialog.Builder(UsbongDecisionTreeEngineActivity.this).setTitle("Hey!") .setMessage(message).setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } else { int yourKey = Integer.parseInt(myPinEditText.getText().toString()); currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; // Log.d(">>>>>>>start encode","encode"); for (int i = 0; i < usbongAnswerContainerCounter; i++) { try { usbongAnswerContainer.set(i, UsbongUtils.performSimpleFileEncrypt(yourKey, usbongAnswerContainer.elementAt(i))); // Log.d(">>>>>>"+i,""+usbongAnswerContainer.get(i)); // Log.d(">>>decoded"+i,""+UsbongUtils.performSimpleFileDecode(yourKey, usbongAnswerContainer.get(i))); } catch (Exception e) { e.printStackTrace(); } } initParser(); } } else if (currScreen == UsbongConstants.DATE_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; Spinner dateMonthSpinner = (Spinner) findViewById(R.id.date_month_spinner); Spinner dateDaySpinner = (Spinner) findViewById(R.id.date_day_spinner); EditText myDateYearEditText = (EditText) findViewById(R.id.date_edittext); /* usbongAnswerContainer.addElement("A,"+monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() + dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," + myDateYearEditText.getText().toString()+";"); */ UsbongUtils.addElementToContainer(usbongAnswerContainer, "A," + monthAdapter.getItem(dateMonthSpinner.getSelectedItemPosition()).toString() + dayAdapter.getItem(dateDaySpinner.getSelectedItemPosition()).toString() + "," + myDateYearEditText.getText().toString() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; // System.out.println(">>>>>>>>>>>>>Date screen: "+usbongAnswerContainer.lastElement()); initParser(); } else if (currScreen == UsbongConstants.TIMESTAMP_DISPLAY_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; UsbongUtils.addElementToContainer(usbongAnswerContainer, timestampString + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else if (currScreen == UsbongConstants.QR_CODE_READER_SCREEN) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do if (!myQRCodeContent.equals("")) { // usbongAnswerContainer.addElement("Y,"+myQRCodeContent+";"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "Y," + myQRCodeContent + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; } else { // usbongAnswerContainer.addElement("N;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "N;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; } initParser(); } else if ((currScreen == UsbongConstants.DCAT_SUMMARY_SCREEN)) { currUsbongNode = nextUsbongNodeIfYes; //= nextIMCIQuestionIfNo will also do /* LinearLayout myDCATSummaryLinearLayout = (LinearLayout)findViewById(R.id.dcat_summary_linearlayout); int total = myDCATSummaryLinearLayout.getChildCount(); StringBuffer dcatSummary= new StringBuffer(); for (int i=0; i<total; i++) { dcatSummary.append(((TextView) myDCATSummaryLinearLayout.getChildAt(i)).getText().toString()); } */ // UsbongUtils.addElementToContainer(usbongAnswerContainer, "dcat_end;", usbongAnswerContainerCounter); UsbongUtils.addElementToContainer(usbongAnswerContainer, "dcat_end," + myDcatSummaryStringBuffer.toString() + ";", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } else { //TODO: do this for now currUsbongNode = nextUsbongNodeIfYes; //nextUsbongNodeIfNo will also do, since this is "Any" // usbongAnswerContainer.addElement("A;"); UsbongUtils.addElementToContainer(usbongAnswerContainer, "A;", usbongAnswerContainerCounter); usbongAnswerContainerCounter++; initParser(); } } }
From source file:dao.CollabrumDaoDb.java
private void deleteRBCollabrum(String directoryId, String collabrumId, String userId, String userLogin) throws BaseDaoException { if (RegexStrUtil.isNull(userId) || RegexStrUtil.isNull(collabrumId) || RegexStrUtil.isNull(directoryId) || RegexStrUtil.isNull(userLogin)) { throw new BaseDaoException("params are null"); }// w ww . j a va 2 s .com List tidList = getTidList(collabrumId); List blobEntryList = getBlobEntryList(collabrumId); Vector ridVector = new Vector(); for (int i = 0; i < tidList.size(); i++) { /* get list of rids from collmessages */ List ridList = getRidList((String) ((ColTopic) tidList.get(i)).getValue(DbConstants.TID)); ridVector.add(ridList); } /** * get the members list from collmembers, then access each record in this table * collblock (deleteAllColBlockQuery) partitioned on loginid * deleteColBlockQuery.run(conn, collabrumId); */ deleteBlockedMembers(collabrumId); /** * Get scalability datasource with no partitions for colladmin, collmembers, dircoll, collabrum */ String sourceName = scalabilityManager.getWriteZeroScalability(); ds = scalabilityManager.getSource(sourceName); if (ds == null) { StringBuffer sb = new StringBuffer("ds is null, deleteCollabrum() "); sb.append(sourceName); sb.append(" collabrumId = "); sb.append(collabrumId); throw new BaseDaoException(sb.toString()); } HashSet result = null; Connection conn = null; /** * non partitioned tables */ try { conn = ds.getConnection(); conn.setAutoCommit(false); result = listModeratorQuery.run(conn, collabrumId); /** * Not partitioned * collabrum, (deleteQuery) * colladmin (deleteAdminQuery) * dircoll (deleteDirColQuery) * collmembers (deleteColMembersQuery), * * collblobtags (deleteColBlobTagsQuery) * collblogtags (deleteColBlogTagsQuery) * collabrum_ind, (deleteCollabrumIndexQuery) * collblob_ind, (deleteColBlobIndexQuery) * collmessages_ind, (deleteColMessagesIndexQuery) * colltopics_ind, (deleteColTopicsIndexQuery) */ deleteQuery.run(conn, collabrumId); deleteAdminQuery.run(conn, collabrumId); deleteDircollQuery.run(conn, collabrumId); deleteAllMembersQuery.run(conn, collabrumId); /* new ones */ deleteColBlobTagsQuery.run(conn, collabrumId); deleteColBlogTagsQuery.run(conn, collabrumId); deleteCollabrumIndexQuery.run(conn, collabrumId); for (int i = 0; i < blobEntryList.size(); i++) { deleteColBlobIndexQuery.run(conn, (String) ((Photo) blobEntryList.get(i)).getValue(DbConstants.ENTRYID)); } for (int i = 0; i < tidList.size(); i++) { deleteColTopicsIndexQuery.run(conn, (String) ((ColTopic) tidList.get(i)).getValue(DbConstants.TID)); } for (int i = 0; i < ridVector.size(); i++) { List ridList = (List) ridVector.elementAt(i); for (int j = 0; i < ridList.size(); j++) { deleteColMessagesIndexQuery.run(conn, (String) ((ColMessage) ridList.get(j)).getValue(DbConstants.RID)); } } } catch (Exception e) { try { conn.rollback(); } catch (Exception e1) { try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e2) { StringBuffer sb = new StringBuffer( "conn.close exception for rollback(), for deleteCollabrum() "); sb.append("collabrumId = "); sb.append(collabrumId); sb.append(" userId = "); sb.append(userId); throw new BaseDaoException(sb.toString(), e2); } StringBuffer sb = new StringBuffer(" rollback() exception, for deleteCollabrum() "); sb.append("collabrumId = "); sb.append(collabrumId); sb.append(" userId = "); sb.append(userId); throw new BaseDaoException(sb.toString(), e1); } } // connection commit try { conn.commit(); } catch (Exception e3) { StringBuffer sb = new StringBuffer(" commit() exception, for deleteCollabrum() collabrumId = "); sb.append(collabrumId); sb.append(" userId = "); sb.append(userId); throw new BaseDaoException(sb.toString(), e3); } try { if (conn != null) { conn.setAutoCommit(true); conn.close(); } } catch (Exception e4) { StringBuffer sb = new StringBuffer( " conn.close() exception, for commit(), deleteCollabrum() collabrumId = "); sb.append(collabrumId); sb.append(" userId = "); sb.append(userId); throw new BaseDaoException(sb.toString(), e4); } deleteCollMessages(collabrumId, tidList); deleteCollTopics(collabrumId, tidList); /** * Jboss methods * fqn - full qualified name * check if the collabrum already exists in the cache * If it exists, remove the collabrum from the cache */ Fqn fqn = cacheUtil.fqn(DbConstants.COLLABRUM); if (treeCache.exists(fqn, collabrumId)) { treeCache.remove(fqn, collabrumId); } fqn = cacheUtil.fqn(DbConstants.ORGANIZERS); if (treeCache.exists(fqn, collabrumId)) { treeCache.remove(fqn, collabrumId); } fqn = cacheUtil.fqn(DbConstants.COLLABRUM_EDIT); if (treeCache.exists(fqn, collabrumId)) { treeCache.remove(fqn, collabrumId); } fqn = cacheUtil.fqn(DbConstants.DIRECTORY); if (treeCache.exists(fqn, directoryId)) { treeCache.remove(fqn, directoryId); } fqn = cacheUtil.fqn(DbConstants.COLTOPICS); if (treeCache.exists(fqn, collabrumId)) { treeCache.remove(fqn, collabrumId); } fqn = cacheUtil.fqn(DbConstants.COLTRAFFIC); if (treeCache.exists(fqn, collabrumId)) { treeCache.remove(fqn, collabrumId); } /** * delete collabrum messages */ for (int i = 0; i < tidList.size(); i++) { StringBuffer sb = new StringBuffer(collabrumId); sb.append("-"); sb.append(tidList.get(i)); String key = sb.toString(); fqn = cacheUtil.fqn(DbConstants.COLMSGS); if (treeCache.exists(fqn, key)) { treeCache.remove(fqn, key); } fqn = cacheUtil.fqn(DbConstants.COLTOPIC); if (treeCache.exists(fqn, key)) { treeCache.remove(fqn, key); } } fqn = cacheUtil.fqn(DbConstants.COLLABRUM_STREAM_BLOBS); if (treeCache.exists(fqn, collabrumId)) { treeCache.remove(fqn, collabrumId); } // deleting user pages for each admin as we want them to be updated if ((result != null) && (result.size() > 0)) { Iterator it = result.iterator(); StringBuffer sb = new StringBuffer(); while (it.hasNext()) { Collabrum collabrum = (Collabrum) it.next(); String adminUser = collabrum.getValue(DbConstants.LOGIN); if (!RegexStrUtil.isNull(adminUser)) { fqn = cacheUtil.fqn(DbConstants.USER_PAGE); if (treeCache.exists(fqn, adminUser)) { treeCache.remove(fqn, adminUser); } fqn = cacheUtil.fqn(DbConstants.MEM_AS_ORGANIZER_LIST); if (treeCache.exists(fqn, adminUser)) { treeCache.remove(fqn, adminUser); } fqn = cacheUtil.fqn(DbConstants.MEM_AS_MODERATOR_LIST); if (treeCache.exists(fqn, adminUser)) { treeCache.remove(fqn, adminUser); } String adminId = collabrum.getValue(DbConstants.LOGIN_ID); fqn = cacheUtil.fqn(DbConstants.BLOCKED_COLLABRUM_LIST); if (treeCache.exists(fqn, adminId)) { treeCache.remove(fqn, adminId); } // delete organizer key = collabrumid-memberid sb.delete(0, sb.length()); sb.append(collabrumId); sb.append("-"); sb.append(adminId); fqn = cacheUtil.fqn(DbConstants.ORGANIZER); if (treeCache.exists(fqn, sb.toString())) { treeCache.remove(fqn, sb.toString()); } } } } fqn = cacheUtil.fqn(DbConstants.COLLABRUM_LIST); if (treeCache.exists(fqn, directoryId)) { treeCache.remove(fqn, directoryId); } /** * Jboss methods - * fqn - full qualified name * check if the streamblob already set in the cache * If it exists, remove the bean from the cache. */ for (int i = 0; i < blobEntryList.size(); i++) { String entryId = (String) ((Photo) blobEntryList.get(i)).getValue(DbConstants.ENTRYID); fqn = cacheUtil.fqn(DbConstants.PHOTO); if (treeCache.exists(fqn, entryId)) { treeCache.remove(fqn, entryId); } StringBuffer buf = new StringBuffer(collabrumId); buf.append("-"); buf.append(entryId); String key = buf.toString(); fqn = cacheUtil.fqn(DbConstants.COL_STREAM_BLOB); if (treeCache.exists(fqn, key)) { treeCache.remove(fqn, key); } fqn = cacheUtil.fqn(DbConstants.DEFAULT_PHOTO); if (treeCache.exists(fqn, key)) { treeCache.remove(fqn, key); } } fqn = cacheUtil.fqn(DbConstants.COLL_CAT); StringBuffer sb = new StringBuffer(collabrumId); sb.append("-"); sb.append(DbConstants.PHOTO_CATEGORY); if (treeCache.exists(fqn, sb.toString())) { treeCache.remove(fqn, sb.toString()); } sb.delete(0, sb.length()); sb.append(collabrumId); sb.append("-"); sb.append(DbConstants.FILE_CATEGORY); if (treeCache.exists(fqn, sb.toString())) { treeCache.remove(fqn, sb.toString()); } }
From source file:stg.pr.engine.CProcessRequestEngine.java
/** * Starts the Stand Alone service engine. * /*from www . j a v a 2 s . co m*/ * Gets the connection from the pool and Continuously scans the * PROCESS_REQUEST table for queued standalone requests and executes them * sequentially * * <p> * Scanning continues in a loop until the bEngineTerminated_ attribute is * false. This attribute is set to true when the engine is interrupted, and * this loop exits. * </p> * <p> * The query picks up requests, from the table PROCESS_REQUEST, that have * the Req_Stat='Q' and GRP_ST_IND = 'S'. If requests are found then each * record is processed sequentially If no records are found then the engine * waits for a specified time (picked up from property file) and then * resumes scanning * </p> * * <p> * This method will <b>spawn Threads</b> for processing stand alone * requests, thus taking maximum advantage of the CPU. The threads are * created by taking into account the number of connections available in the * pool - 2. As two connections are internally used by the Engine, One for * making updates for status and another for processing Grouped Requests. * </p> * * @throws CProcessRequestEngineException * */ private void startServiceForNormalRequests() throws CProcessRequestEngineException { boolean isQueuedReqFound = false; ProcessRequestController objPrCont_ = null; StringBuffer reqLogFileName; StringBuffer reqLogFileUrl; // final int iNoOfThreads_ = (bValidLicense_?Integer.MAX_VALUE:2); try { reqLogFileName = new StringBuffer(50); reqLogFileUrl = new StringBuffer(50); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Starting StandAlone Engine ...."); } if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.info("Getting JDBC Connection for the StandAlone Engine ...."); } // staticConnection_ = // poolManager_.getConnection(CSettings.get("pr.dsforstandaloneeng")); DataSource ds = dataSourceFactory_.getDataSource(CSettings.get("pr.dsforstandaloneeng")); if (ds == null) { throw new CProcessRequestEngineException("NullPointerException for DataSource"); } staticConnection_ = ds.getConnection(); CDynamicDataContainer objDdc_ = new CDynamicDataContainer(); objDdc_.addWhereClause(FILTER_CONDITION); objDdc_.addOrderByClause(ORDER_BY_CLAUSE); ProcessRequestEntityBean objPrEb_ = new ProcessRequestEntityBean(); objPrCont_ = new ProcessRequestController(staticConnection_); setRebootCounter(-1); // Ideally here the Engine can be considered // as started. checkClusterPRE(); if (!tMain_.isInterrupted() || !bEngineTerminated_.get()) { objEngineLogger_.log(LogLevel.NOTICE, "Stand Alone Engine Started.."); } Iterator<RequestStatusVO> failOverRequestIterator = context_.getFailedOverRequests().iterator(); while (!tMain_.isInterrupted()) { context_.setPREActive(true); boolean bTerminate = false; // try { // LicenseVerifier.verify(readLicense()); // } catch (LicenseContentException lce) { // bTerminate = true; // objEngineLogger_.fatal(lce.getLocalizedMessage()); // } catch (Exception e) { // bTerminate = true; // objEngineLogger_.fatal(e.getLocalizedMessage()); // } if (bTerminate) { if (tEngine_ != null) { tEngine_.interrupt(); } break; } try { isQueuedReqFound = false; boolean failOverRequest = false; if (!bEngineTerminated_.get()) { if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Entered infintite loop, Initializing Request Entity Bean ...."); } setReboot(false); objPrEb_.initialize(); if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Building query ...."); } if (objEngineLogger_.isDebugEnabled()) { objEngineLogger_.debug("Querying for queued requests ...."); } if (failOverRequestIterator.hasNext()) { RequestStatusVO vo = failOverRequestIterator.next(); objEngineLogger_.log(LogLevel.NOTICE, "Re-Executing Failed-Over Request #" + vo.getReqId()); objPrEb_.setReqId(vo.getReqId()); objPrEb_.setReqStat(vo.getStatus()); objDdc_.build(staticConnection_, objPrEb_); objDdc_.setMaximumFetchSize(iMaximumFetchSizeAtATime_); objDdc_.setPartialFetch(true); failOverRequestIterator.remove(); isQueuedReqFound = objDdc_.executeQuery(staticConnection_, objPrCont_, objPrEb_); failOverRequest = true; } else { objPrEb_.setReqStat(REQUEST_STATUS.QUEUED.getID()); objPrEb_.setGrpStInd(REQUEST_TYPE.STANDALONE.getID()); objPrEb_.setScheduledTime(getCurrentTimestamp(staticConnection_)); objDdc_.build(staticConnection_, objPrEb_, hmWhereCondition_); objDdc_.setMaximumFetchSize(iMaximumFetchSizeAtATime_); objDdc_.setPartialFetch(true); // This has been added later by Kedar on 3/1/2003 isQueuedReqFound = objDdc_.executeQuery(staticConnection_, objPrCont_, objPrEb_); failOverRequest = false; } } // If engine is not terminated then only do the above // stuff. if (isQueuedReqFound) {// pending requests exist if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Queued requests exists ...."); } // The bEngineTerminated_ flag with an OR condition was // added on 21.01.2004 by Kedar. // This is because if the StopEngine tires terminate the // engine and if there is a process // already running then the engine should not enter the // while loop. while (objDdc_.next() && !(tMain_.isInterrupted() || bEngineTerminated_.get())) { if (iThreadCounter_.get() <= iStandAloneMaximumThread_ // && iThreadCounter_.get() <= licContent_ // .getConsumerAmount() ) // if ( iThreadCounter_ < // CSettings.getInt(("pr.standalonemaximumthreads", // "2")) && iThreadCounter_ <= // licContent_.getConsumerAmount()) { ProcessRequestEntityBean objPrEb = (ProcessRequestEntityBean) objDdc_.get(); reqLogFileName.delete(0, reqLogFileName.length()); reqLogFileUrl.delete(0, reqLogFileUrl.length()); reqLogFileName.append(strReqLogFilePath_); reqLogFileName.append(objPrEb.getReqId()); reqLogFileName.append("."); reqLogFileName.append(strReqLogFileExtension_); reqLogFileUrl.append(strReqLogFileUrl_); reqLogFileUrl.append(objPrEb.getReqId()); reqLogFileUrl.append("."); reqLogFileUrl.append(strReqLogFileExtension_); // objEngineLogger_.info("Initialize Request Log File ...."); updateRequestStatus(staticConnection_, objPrCont_, objPrEb, REQUEST_STATUS.LAUNCHING, reqLogFileUrl.toString()); // Create a new thread and start the process. // Increament the Thread counter so that if // thread counter reaches // Maximum of the connections available in pool // then the engine should not spawn a new // thread. ThreadProcess tp = new ThreadProcess("Thread-ReqId#" + objPrEb.getReqId()); // tp.join(); //Joins the new thread to the // parent (tEngine). addStandAloneProcess(tp); tp.setProcessRequestEntityBean(objPrEb); tp.setLogFileName(reqLogFileName.toString()); tp.setLogFileNameURL(reqLogFileUrl.toString()); tp.setPool(dataSourceFactory_); // So that the // ThreadProcess // can request // connection // from Pool tp.setFailedOver(failOverRequest); tp.start(); } // if ( iThreadCounter_ < // iTotalConnectionsInPool_) // If all the available threads are spawned then // wait for 10 seconds. This should be // parameterised. // If thread.sleep is not called then for that while // loop it will take a huge CPU time and rest of the // threads will be slow. // The above comment is debatable. So commented // currently. boolean bInWaitMode = false; if (iThreadCounter_.get() > iStandAloneMaximumThread_) { bInWaitMode = true; if (objEngineLogger_.isEnabledFor(LogLevel.FINE)) { objEngineLogger_.log(LogLevel.FINE, "Maximum thread spawning capacity (#" + (iThreadCounter_.get() - 1) + ") has reached. Going into Wait mode till one of the JOB gets over."); } } long lCurrentTime = System.currentTimeMillis(); while (iThreadCounter_.get() > iStandAloneMaximumThread_) { // try // { // Thread.sleep(10000); // } // catch (InterruptedException ie) // { // System.exit(1); // } } long lWaitTime = System.currentTimeMillis() - lCurrentTime; if (bInWaitMode) { bInWaitMode = false; if (objEngineLogger_.isEnabledFor(LogLevel.FINE)) { objEngineLogger_.log(LogLevel.FINE, "Wait Over. Waited for #" + lWaitTime + " milliseconds for some JOB to get over."); } } } // end of while(objDdc.next()) } // end of if objDdc.getTotalRows() > 0 else { if (!failOverRequestIterator.hasNext()) { // no failover // jobs. lWaitInterval_ = (Math.abs(Long.parseLong(CSettings.get("pr.waitinterval")))); if (!(bEngineTerminated_.get() || tMain_.isInterrupted())) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info(mfSleepMessageForEngine_ .format(new Object[] { "StandAlone", lWaitInterval_ })); } try { Thread.yield(); TimeUnit.SECONDS.sleep(lWaitInterval_); // Thread.sleep(lWaitInterval_); } catch (InterruptedException ie) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Engine Thread Interrupted .."); } break; } } else { if (bEngineTerminated_.get()) { tMain_.interrupt(); } } } } // end of else } catch (CDynamicDataContainerException cdce) { // This is under the assumption that the IO Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the Engine // itself and so engine should get terminated. stopMessageForEmail_ = exceptionToString(cdce); objEngineLogger_.fatal("CDynamicQueryException Caught. Terminating StandAlone Engine", cdce); setReboot(true); break; } catch (CDynamicQueryException cdqe) { // This is under the assumption that the IO Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the Engine // itself and so engine should get terminated. stopMessageForEmail_ = exceptionToString(cdqe); objEngineLogger_.fatal("CDynamicQueryException Caught. Terminating StandAlone Engine", cdqe); setReboot(true); break; } catch (IOException ioe) { // This is under the assumption that the IO Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the // Connection. try { staticConnection_ = refreshJDBCConnection(4, staticConnection_, CSettings.get("pr.dsforstandaloneeng")); } catch (Exception e) { stopMessageForEmail_ = exceptionToString(ioe); objEngineLogger_.fatal("IOException Caught. Terminating StandAlone Engine", ioe); setReboot(true); ; break; } } catch (SQLException se) { // This is under the assumption that the SQL Exception can // never be thrown by the object // executed by the Engine as it can only throw // CProcessRequestEngineException. This exception // means that something wrong has happened in the // Connection. objEngineLogger_.error("SQLException caught", se); try { staticConnection_ = refreshJDBCConnection(4, staticConnection_, CSettings.get("pr.dsforstandaloneeng")); // StackTraceElement[] elements = se.getStackTrace(); // for (int i = 0; i < elements.length; i++) { // // } } catch (Exception e) { stopMessageForEmail_ = exceptionToString(se); objEngineLogger_.fatal("SQLException Caught. Terminating StandAlone Engine", se); setReboot(true); break; } } catch (RuntimeException ree) { objEngineLogger_.error("Runtime Exception Caught", ree); // Just catch; no need to throw exception. } catch (CProcessRequestEngineException cree) { objEngineLogger_.error("CProcessRequestEngineException Caught", cree); // Just catch; no need to throw exception. } catch (Exception e) { objEngineLogger_.error("Exception Caught", e); // Just catch; no need to throw exception. } catch (Error e) { if (e instanceof ThreadDeath) { objEngineLogger_.fatal("Process killed through the PRE Web Service"); } else { stopMessageForEmail_ = exceptionToString(e); objEngineLogger_.fatal(e); throw e; } } } // end of while true } catch (ConnectException e) { stopMessageForEmail_ = exceptionToString(e); objEngineLogger_.fatal("ConnectException Caught. Terminating StandAlone Engine", e); if (getRebootCounter() > 0) { setReboot(true); } } catch (SQLException e) { stopMessageForEmail_ = exceptionToString(e); objEngineLogger_.fatal("SQLException Caught. Terminating StandAlone Engine", e); if (getRebootCounter() > 0) { setReboot(true); } } catch (IOException e) { stopMessageForEmail_ = exceptionToString(e); objEngineLogger_.fatal("IOException Caught. Terminating StandAlone Engine", e); if (getRebootCounter() > 0) { setReboot(true); } } catch (Exception e) { throw new CProcessRequestEngineException(e.getMessage(), e); } // end of 1st try catch block finally { ((PREContextImpl) context_).setPREActive(false); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Releasing Stand Alone Resources And Confirming Termination ..."); } if (objPrCont_ != null) { try { objPrCont_.close(); } catch (SQLException e) { objEngineLogger_.error("Caught exception while closing PRController.", e); } } // pool_.stopShrinking(); reqLogFileName = null; // Nullifying the variables. reqLogFileUrl = null; // Nullifying the variables. if (tInterrupt_ != null) { if (tInterrupt_.isAlive()) { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Interrupting Shutdown Hook from Stand Alone Requests..."); } tInterrupt_.interrupt(); } } bEngineTerminated_.set(true); } }
From source file:com.exilant.eGov.src.reports.GeneralLedgerReport.java
/** * glcode2 is not used at all//from w ww . ja v a 2 s . c om * * @param reportBean * @return * @throws TaskFailedException */ public LinkedList getGeneralLedgerList(final GeneralLedgerReportBean reportBean) throws TaskFailedException { final LinkedList dataList = new LinkedList(); if (LOGGER.isInfoEnabled()) LOGGER.info("Indise the loop.........."); new CashBook(null); String isconfirmed = ""; String glCode1 = ""; glCode1 = reportBean.getGlCode1(); try { final String snapShotDateTime = reportBean.getSnapShotDateTime(); if (snapShotDateTime.equalsIgnoreCase("")) effTime = ""; else effTime = eGovernCommon.getEffectiveDateFilter(snapShotDateTime); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw taskExc; } final String fundId = reportBean.getFund_id(); final String deptId = reportBean.getDepartmentId(); final String fundSourceId = reportBean.getFundSource_id(); reportBean.setFundName(getFundName(fundId)); reportBean.setAccountCode(getAccountName(glCode1)); String formstartDate = ""; String formendDate = ""; final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); final SimpleDateFormat formatter1 = new SimpleDateFormat("dd-MMM-yyyy"); Date dt = new Date(); String endDate1 = reportBean.getEndDate(); if (endDate1 == "" || endDate1.length() == 0) { endDate1 = new SimpleDateFormat("dd/MM/yyyy").format(new Date()); } isCurDate(endDate1); try { endDate = reportBean.getEndDate(); if (endDate == "" || endDate.length() == 0) { endDate = endDate1; } dt = sdf.parse(endDate); formendDate = formatter1.format(dt); } catch (final Exception e) { LOGGER.error("inside the try-startdate" + e, e); throw taskExc; } try { startDate = reportBean.getStartDate(); if (!startDate.equalsIgnoreCase("null")) { dt = sdf.parse(startDate); formstartDate = formatter1.format(dt); } if (startDate.equalsIgnoreCase("null")) { final CFinancialYear finYearByDate = financialYearDAO.getFinYearByDate(dt); if (finYearByDate != null) startDate = formatter1.format(finYearByDate.getStartingDate()); // SETTING START DATE IN reportBean reportBean.setStartDate(startDate); final Date dtOBj = sdf.parse(startDate); startDate = formatter1.format(dtOBj); } else startDate = formstartDate; } catch (final Exception e) { LOGGER.error("inside the try-startdate" + e, e); throw taskExc; } accEntityId = reportBean.getAccEntityId(); accEntityKey = reportBean.getAccEntityKey(); endDate = formendDate; final String startDateformat = startDate; String startDateformat1 = ""; try { dt = formatter1.parse(startDateformat); startDateformat1 = sdf.format(dt); } catch (final Exception e) { LOGGER.error("Parse Exception" + e, e); throw taskExc; } Date dd = new Date(); final String endDateformat = endDate; try { dd = formatter1.parse(endDateformat); } catch (final ParseException e1) { } final CFinancialYear finYearByDate = financialYearDAO.getFinYearByDate(dd); final String fyId = finYearByDate.getId().toString(); if (fyId.equalsIgnoreCase("")) { if (LOGGER.isInfoEnabled()) LOGGER.info("Financial Year Not Valid"); throw taskExc; } CodeValidator.getInstance(); /* * if (!cv.isValidCode(glCode1)) { LOGGER.error(glCode1 + " Not Valid"); * throw taskExc; } */ double txnDrSum = 0, txnCrSum = 0, openingBalance = 0, closingBalance = 0; // String query = getQuery(glCode1,fundId, fundSourceId, startDate, // endDate); // engine.setAppConfigValuesService(appConfigValuesService); final ReportEngineBean reBean = engine.populateReportEngineBean(reportBean); engineQry = engine.getVouchersListQuery(reBean); final String query = getQuery(glCode1, startDate, endDate, accEntityId, accEntityKey, reportBean.getFieldId(), reBean.getFunctionId()); final String functionId = reBean.getFunctionId(); if (LOGGER.isInfoEnabled()) LOGGER.info("**************QUERY: " + query); try { try { pstmt = persistenceService.getSession().createSQLQuery(query); } catch (final Exception e) { LOGGER.error("Exception in creating statement:" + pstmt, e); throw taskExc; } final List list = pstmt.list(); resultset1 = list; list.toArray(); final ArrayList data = new ArrayList(); String accCode = "", vcNum = "", vcDate = "", narration = "", vcTypeName = "", voucherHeaderId = ""; StringBuffer detail = new StringBuffer(); StringBuffer amount = new StringBuffer(); int vhId = 0, curVHID = 0, cout = 0, VhidPrevious = 0; final int lenAfterAppend = 0, lenBeforeAppend = 0, lenDetailBefore = 0, lenDetailAfter = 0; double txnDebit = 0, txnCredit = 0, previousDebit = 0, previousCredit = 0; String code = "", currCode = "", accCodePrevious = "", cgn = ""; /** * When using ResultSet.TYPE_SCROLL_INSENSITIVE in createStatement * if no records are there, rs.next() will return true but when * trying to access (rs.getXXX()), it will throw an error **/ int totalCount = 0, isConfirmedCount = 0; String vn2 = ""; if (LOGGER.isDebugEnabled()) LOGGER.debug("resultset1---------------------------->" + resultset1); if (resultset1 == null || resultset1.size() == 0) { // Will consider // the startdate // of report as // the end date // of the // opening // balance. // Actually it considers 1 date less than startdate or you can // say // opb<startdate startDate = sdf.format(formatter1.parse(startDate)); final OpBal opbal = getOpeningBalance(glCode1, fundId, fundSourceId, fyId, accEntityId, accEntityKey, startDate, functionId, deptId); final String arr[] = new String[15]; openingBalance = opbal.dr - opbal.cr; if (LOGGER.isInfoEnabled()) LOGGER.info("openingBalance--------------->" + openingBalance); final String sqlString = "select name as \"glname\" from chartofaccounts where glcode=?"; pstmt = persistenceService.getSession().createSQLQuery(sqlString); pstmt.setString(0, glCode1); final List res = pstmt.list(); String aName = ""; if (res != null) aName = res.get(0).toString(); arr[1] = ""; arr[2] = arr[3] = arr[6] = arr[7] = arr[10] = arr[11] = arr[12] = arr[13] = ""; arr[14] = ""; if (vhId == 0) arr[8] = ""; arr[9] = glCode1 + "-" + aName; if (openingBalance > 0) { arr[4] = "" + numberToString(((Double) Math.abs(openingBalance)).toString()).toString() + ""; arr[5] = ""; } else if (openingBalance < 0) { arr[4] = ""; arr[5] = "" + numberToString(((Double) Math.abs(openingBalance)).toString()).toString() + ""; } else { arr[4] = ""; arr[5] = ""; } arr[0] = "Opening Balance"; if (vhId == 0 && !(openingBalance > 0 || openingBalance < 0)) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Inside if condition"); } else data.add(arr); final String arr2[] = new String[15]; closingBalance = openingBalance; if (closingBalance > 0) { arr2[4] = ""; arr2[5] = "" + numberToString(((Double) Math.abs(closingBalance)).toString()).toString() + ""; } else if (closingBalance < 0) { arr2[4] = "" + numberToString(((Double) Math.abs(closingBalance)).toString()).toString() + ""; arr2[5] = ""; } else { arr2[4] = ""; arr2[5] = ""; } arr2[2] = ""; arr2[0] = "Closing Balance"; arr2[1] = ""; arr2[3] = arr2[6] = arr2[7] = arr2[8] = arr2[9] = arr2[10] = arr2[11] = arr[12] = arr[13] = ""; arr2[14] = ""; data.add(arr2); } for (final Object[] element : resultset1) { if (LOGGER.isInfoEnabled()) LOGGER.info(" inside resultset"); try { code = element[0].toString(); if (element[14] == null) isconfirmed = ""; else isconfirmed = element[14].toString(); // 9 is the dummy value used in the query // To display X in Y are unconfirmed if (isconfirmed != null && !isconfirmed.equalsIgnoreCase("") && !isconfirmed.equalsIgnoreCase("9")) { final String vn1 = element[5].toString(); if (!vn1.equalsIgnoreCase(vn2)) { vn2 = vn1; totalCount = totalCount + 1; if (isconfirmed.equalsIgnoreCase("0")) isConfirmedCount = isConfirmedCount + 1; } } // cout1=0; vhId = Integer.parseInt(element[2].toString()); /** * When the main GLCODES are changing.We need to get the * opening balance first. */ if (!code.equals(currCode)) { // glType=resultset1.getString("glType"); final String arr[] = new String[15]; startDate = sdf.format(formatter1.parse(startDate)); final OpBal opbal = getOpeningBalance(code, fundId, fundSourceId, fyId, accEntityId, accEntityKey, startDate, functionId, deptId); openingBalance = opbal.dr - opbal.cr; String fundName = ""; if (element[13].toString() != null) fundName = element[13].toString(); final String sqlString1 = "select name as \"glname\" from chartofaccounts where glcode=?"; pstmt = persistenceService.getSession().createSQLQuery(sqlString1); pstmt.setString(0, code); final List res = pstmt.list(); String aName = ""; if (res != null) aName = res.get(0).toString(); arr[1] = ""; arr[2] = arr[3] = arr[6] = arr[7] = arr[10] = arr[11] = arr[12] = arr[13] = ""; arr[14] = ""; if (vhId == 0) arr[8] = ""; else arr[8] = fundName; arr[9] = code + "-" + aName; if (openingBalance > 0) { arr[4] = "" + numberToString(((Double) Math.abs(openingBalance)).toString()).toString() + ""; arr[5] = ""; } else if (openingBalance < 0) { arr[4] = ""; arr[5] = "" + numberToString(((Double) Math.abs(openingBalance)).toString()).toString() + ""; } else { arr[4] = ""; arr[5] = ""; } arr[0] = "Opening Balance"; if (vhId == 0 && !(openingBalance > 0 || openingBalance < 0)) { if (LOGGER.isDebugEnabled()) LOGGER.debug("Inside if"); } else data.add(arr); currCode = code; } // End If glcodes changing } catch (final Exception ex) { LOGGER.error("ERROR (not an error): ResultSet is Empty", ex); throw taskExc; } // Vouchers are changing if (curVHID > 0 && vhId != curVHID && cout == 0 && vhId != 0) { if (txnDebit > 0) { previousDebit = 0; previousCredit = 0; final String arr9[] = new String[15]; arr9[0] = vcDate; arr9[1] = vcNum; arr9[14] = voucherHeaderId; arr9[2] = detail.toString(); arr9[3] = ""; arr9[4] = numberToString(((Double) txnDebit).toString()) + ""; arr9[5] = ""; if (narration != null) arr9[6] = "" + narration; else arr9[6] = ""; arr9[7] = cgn; txnDrSum = txnDrSum + txnDebit; txnCrSum = txnCrSum + txnCredit; arr9[10] = ""; arr9[11] = ""; // End arr9[8] = arr9[9] = ""; arr9[12] = vcTypeName; arr9[13] = ""; data.add(arr9); } else if (txnCredit > 0) { previousDebit = 0; previousCredit = 0; final String arr9[] = new String[15]; arr9[0] = ""; arr9[1] = ""; arr9[2] = ""; arr9[3] = detail.toString(); arr9[5] = numberToString(((Double) txnCredit).toString()) + ""; arr9[4] = ""; if (narration != null) arr9[6] = "" + narration; else arr9[6] = ""; arr9[7] = cgn; txnDrSum = txnDrSum + txnDebit; txnCrSum = txnCrSum + txnCredit; arr9[10] = vcDate; arr9[11] = vcNum; arr9[12] = ""; arr9[13] = vcTypeName; arr9[14] = voucherHeaderId; // End arr9[8] = arr9[9] = ""; data.add(arr9); } detail.delete(0, detail.length()); amount.delete(0, amount.length()); // cnt = 0; vcDate = vcNum = voucherHeaderId = accCode = narration = vcTypeName = ""; } // End If curVHID = vhId; cout = 0; accCode = element[6].toString(); String detailId = null; if (!accEntityKey.equals("")) detailId = element[15].toString(); if (LOGGER.isDebugEnabled()) LOGGER.debug("accEntityKey---->" + accEntityKey); if (!accCode.equalsIgnoreCase(accCodePrevious)) { previousDebit = 0; previousCredit = 0; } if (accCode.equalsIgnoreCase(code)) { if (detailId != null && !detailId.equals(accEntityKey)) { slDrAmount = slDrAmount.add(new BigDecimal(element[11].toString())); slCrAmount = slCrAmount.add(new BigDecimal(element[12].toString())); } } else if (!accEntityKey.equals("")) { /* * if(slCrAmount.compareTo(BigDecimal.ZERO)!=0) { detail= * detail.append(" " + glCode1+" "+ * element[8].toString()); slCrAmount=new * BigDecimal("0.00"); } else * if(slDrAmount.compareTo(BigDecimal.ZERO)!=0) { detail= * detail.append(" " + glCode1+" "+ * element[8].toString()); slDrAmount=new * BigDecimal("0.00"); } */ // detail= detail.append(" " + glCode1+" "+ // element[8].toString()); slCrAmount = new BigDecimal("0.00"); slDrAmount = new BigDecimal("0.00"); } if (vhId != 0 && (detailId == null || detailId.equals(accEntityKey)) && !accEntityKey.equals("")) { // get the details other than patriculars if (LOGGER.isDebugEnabled()) LOGGER.debug("detailId-->" + detailId + "accCode-->" + accCode + "::code:" + code); if (accCode.equalsIgnoreCase(code)) { if (LOGGER.isDebugEnabled()) LOGGER.debug("accCode...................." + accCode); double currentDebit = 0, currentCredit = 0, debit = 0, credit = 0; if (vhId == VhidPrevious && accCode.equalsIgnoreCase(accCodePrevious)) { if (LOGGER.isDebugEnabled()) LOGGER.debug("vhId:::::::::::::::::" + vhId); vcDate = element[4].toString(); vcNum = element[5].toString(); voucherHeaderId = element[2].toString(); vcTypeName = element[16].toString(); final String vhId1 = element[2].toString(); if (LOGGER.isInfoEnabled()) LOGGER.info("vhId1:::" + vhId1); // cgn = cashbook.getCGN(vhId1); // type = resultset1.getString("type"); if (detailId != null) { currentDebit = Double.parseDouble(element[11].toString()); currentCredit = Double.parseDouble(element[12].toString()); debit = previousDebit + currentDebit - (previousCredit + currentCredit); if (debit > 0) txnDebit = debit; else txnDebit = 0; credit = previousCredit + currentCredit - (previousDebit + currentDebit); if (credit > 0) txnCredit = credit; else txnCredit = 0; previousDebit = previousDebit + currentDebit; previousCredit = previousCredit + currentCredit; } narration = element[9] != null ? element[9].toString() : StringUtils.EMPTY; } else { vcDate = element[4].toString(); vcNum = element[5].toString(); voucherHeaderId = element[2].toString(); vcTypeName = element[16].toString(); final String vhId1 = element[2].toString(); if (LOGGER.isInfoEnabled()) LOGGER.info("vhId1:::" + vhId1); // cgn = cashbook.getCGN(vhId1); // type = resultset1.getString("type"); if (detailId != null) { txnDebit = Double.parseDouble(element[11].toString()); previousDebit = txnDebit; txnCredit = Double.parseDouble(element[12].toString()); previousCredit = txnCredit; } narration = element[9] != null ? element[9].toString() : StringUtils.EMPTY; } } else if (vhId == VhidPrevious && accCode.equalsIgnoreCase(accCodePrevious)) { double currentDebit = 0, currentCredit = 0, debit = 0, credit = 0; String debitAmount = "", creditAmount = ""; amount.delete(lenBeforeAppend, lenAfterAppend); detail.delete(lenDetailBefore, lenDetailAfter); detail = detail.append(" " + element[6].toString() + "" + element[8].toString()); currentDebit = Double.parseDouble(element[11].toString()); currentCredit = Double.parseDouble(element[12].toString()); debit = previousDebit + currentDebit - (previousCredit + currentCredit); if (debit > 0) { debitAmount = "Dr." + ExilPrecision.convertToString(debit, 2) + "0"; amount = amount.append(" " + debitAmount); } credit = previousCredit + currentCredit - (previousDebit + currentDebit); if (credit > 0) { creditAmount = "Cr." + ExilPrecision.convertToString(credit, 2) + "0"; amount = amount.append(" " + creditAmount); } } else { detail = detail.append(" " + element[6].toString() + "" + element[8].toString()); previousDebit = Double.parseDouble(element[11].toString()); previousCredit = Double.parseDouble(element[12].toString()); } } else if (vhId != 0 && accEntityKey.equals("")) { // if(LOGGER.isDebugEnabled()) // LOGGER.debug(" inside vhId != 0"); // get the details other than patriculars if (accCode.equalsIgnoreCase(code)) { double currentDebit = 0, currentCredit = 0, debit = 0, credit = 0; if (vhId == VhidPrevious && accCode.equalsIgnoreCase(accCodePrevious) // && // (StringUtils.isEmpty(reBean.getFunctionId()) // || // reBean.getFunctionId().equals(resultset1.getString("functionid"))) ) { vcDate = element[4].toString(); vcNum = element[5].toString(); voucherHeaderId = element[2].toString(); vcTypeName = element[16].toString(); final String vhId1 = element[2].toString(); if (LOGGER.isInfoEnabled()) LOGGER.info("vhId1:::" + vhId1); // cgn = cashbook.getCGN(vhId1); // type = resultset1.getString("type"); currentDebit = Double.parseDouble(element[11].toString()); currentCredit = Double.parseDouble(element[12].toString()); debit = previousDebit + currentDebit - (previousCredit + currentCredit); if (debit > 0) txnDebit = debit; else txnDebit = 0; credit = previousCredit + currentCredit - (previousDebit + currentDebit); if (credit > 0) txnCredit = credit; else txnCredit = 0; narration = element[9] != null ? element[9].toString() : StringUtils.EMPTY; /* * previousDebit=currentDebit; * previousCredit=currentCredit; */ previousDebit = txnDebit; previousCredit = txnCredit; } else // if // (StringUtils.isEmpty(reBean.getFunctionId()) // || // reBean.getFunctionId().equals(resultset1.getString("functionid"))) { vcDate = element[4].toString(); vcNum = element[5].toString(); voucherHeaderId = element[2].toString(); vcTypeName = element[16].toString(); final String vhId1 = element[2].toString(); if (LOGGER.isInfoEnabled()) LOGGER.info("vhId1:::" + vhId1); cgn = ""; // type = resultset1.getString("type"); txnDebit = Double.parseDouble(element[11].toString()); previousDebit = txnDebit; txnCredit = Double.parseDouble(element[12].toString()); previousCredit = txnCredit; narration = element[9] != null ? element[9].toString() : StringUtils.EMPTY; } /* * else { detail= detail.append(" " + * element[6].toString()+" "+ * element[8].toString()); } */ } else if (vhId == VhidPrevious && accCode.equalsIgnoreCase(accCodePrevious) // && // (StringUtils.isEmpty(reBean.getFunctionId()) // || // reBean.getFunctionId().equals(resultset1.getString("functionid"))) ) { double currentDebit = 0, currentCredit = 0, debit = 0, credit = 0; String debitAmount = "", creditAmount = ""; amount.delete(lenBeforeAppend, lenAfterAppend); detail.delete(lenDetailBefore, lenDetailAfter); detail = detail.append(" " + element[6].toString() + "" + element[8].toString()); currentDebit = Double.parseDouble(element[11].toString()); currentCredit = Double.parseDouble(element[12].toString()); debit = previousDebit + currentDebit - (previousCredit + currentCredit); if (debit > 0) { debitAmount = "Dr." + ExilPrecision.convertToString(debit, 2) + "0"; amount = amount.append(" " + debitAmount); } credit = previousCredit + currentCredit - (previousDebit + currentDebit); if (credit > 0) { creditAmount = "Cr." + ExilPrecision.convertToString(credit, 2) + "0"; amount = amount.append(" " + creditAmount); } } else { detail = detail.append(" " + element[6].toString() + "" + element[8].toString()); previousDebit = Double.parseDouble(element[11].toString()); previousCredit = Double.parseDouble(element[12].toString()); } } else if (vhId != 0 && !accEntityKey.equals("")) detail = detail.append(" " + element[6].toString() + "" + element[8].toString()); accCodePrevious = accCode; VhidPrevious = vhId; if (element.equals(resultset1.get(resultset1.size() - 1))) { if (txnDebit > 0) { final String arr[] = new String[15]; arr[0] = vcDate; arr[1] = vcNum; arr[14] = voucherHeaderId; arr[2] = detail.toString(); arr[3] = ""; arr[4] = numberToString(((Double) txnDebit).toString()) + ""; arr[5] = ""; if (narration != null) arr[6] = "" + narration; else arr[6] = ""; txnDrSum = txnDrSum + txnDebit; txnCrSum = txnCrSum + txnCredit; arr[8] = arr[9] = ""; arr[4] = arr[4].equalsIgnoreCase(".00") ? "" : arr[4]; arr[7] = cgn; arr[10] = ""; arr[11] = ""; arr[12] = vcTypeName; arr[13] = ""; data.add(arr); } else if (txnCredit > 0) { final String arr[] = new String[15]; arr[0] = ""; arr[1] = ""; arr[2] = ""; arr[3] = detail.toString(); arr[4] = ""; arr[5] = numberToString(((Double) txnCredit).toString()) + ""; if (narration != null) arr[6] = "" + narration; else arr[6] = ""; txnDrSum = txnDrSum + txnDebit; txnCrSum = txnCrSum + txnCredit; arr[8] = arr[9] = ""; arr[5] = arr[5].equalsIgnoreCase(".00") ? "" : arr[5]; arr[7] = cgn; arr[10] = vcDate; arr[11] = vcNum; arr[12] = ""; arr[13] = vcTypeName; arr[14] = voucherHeaderId; data.add(arr); } detail.delete(0, detail.length()); amount.delete(0, amount.length()); // cnt = 0; vcDate = vcNum = voucherHeaderId = accCode = narration = ""; final String arr2[] = new String[15]; if (openingBalance > 0) txnDrSum = txnDrSum + Math.abs(openingBalance); else txnCrSum = txnCrSum + Math.abs(openingBalance); closingBalance = txnDrSum - txnCrSum; if (closingBalance > 0) { txnCrSum = txnCrSum + Math.abs(closingBalance); arr2[4] = ""; arr2[5] = "" + numberToString(((Double) Math.abs(closingBalance)).toString()).toString() + ""; } else if (closingBalance < 0) { txnDrSum = txnDrSum + Math.abs(closingBalance); arr2[4] = "" + numberToString(((Double) Math.abs(closingBalance)).toString()).toString() + ""; arr2[5] = ""; } else { arr2[4] = ""; arr2[5] = ""; } arr2[2] = ""; arr2[0] = "Closing Balance"; arr2[1] = ""; arr2[3] = arr2[6] = arr2[7] = arr2[8] = arr2[9] = arr2[10] = arr2[11] = arr2[12] = arr2[13] = ""; data.add(arr2); final String arr1[] = new String[15]; if (txnDrSum > 0) arr1[4] = "" + numberToString(((Double) txnDrSum).toString()) + ""; else arr1[4] = ""; if (txnCrSum > 0) arr1[5] = "" + numberToString(((Double) txnDrSum).toString()) + ""; else arr1[5] = ""; arr1[2] = ""; arr1[0] = "Total"; arr1[1] = ""; arr1[3] = arr1[6] = arr1[7] = arr1[8] = arr1[9] = arr1[10] = arr1[11] = arr1[12] = arr1[13] = ""; data.add(arr1); txnDrSum = 0; txnCrSum = 0; } // End If last } // End While // Adding data to 2 dimension array to pass to Linkedlist final String gridData[][] = new String[data.size() + 1][15]; gridData[0][0] = "voucherdate"; gridData[0][1] = "vouchernumber"; gridData[0][2] = "debitparticular"; gridData[0][3] = "creditparticular"; gridData[0][4] = "debitamount"; gridData[0][5] = "creditamount"; gridData[0][6] = "narration"; gridData[0][7] = "cgn"; gridData[0][8] = "fund"; gridData[0][9] = "glcode"; gridData[0][10] = "creditdate"; gridData[0][11] = "creditvouchernumber"; gridData[0][12] = "debitVoucherTypeName"; gridData[0][13] = "creditVoucherTypeName"; gridData[0][14] = "vhId"; for (int i = 1; i <= data.size(); i++) gridData[i] = (String[]) data.get(i - 1); for (int i = 1; i <= data.size(); i++) { final GeneralLedgerBean generalLedgerBean = new GeneralLedgerBean(); generalLedgerBean.setGlcode(gridData[i][9]); generalLedgerBean.setVoucherdate(gridData[i][0]); generalLedgerBean.setVouchernumber(gridData[i][1]); int counter = 0; final String testTemp = gridData[i][2]; final char testArrayTemp[] = testTemp.toCharArray(); for (counter = 0; counter < testArrayTemp.length; counter++) if (testArrayTemp[counter] == '<' && (testArrayTemp[counter + 1] == 'b' || testArrayTemp[counter + 1] == 'B')) break; generalLedgerBean.setDebitparticular(gridData[i][2]); final String test = gridData[i][7]; final char testArray[] = test.toCharArray(); for (counter = 0; counter < testArray.length; counter++) if (testArray[counter] == 'r') break; generalLedgerBean.setNarration(gridData[i][6]); generalLedgerBean.setCreditparticular(gridData[i][3]); generalLedgerBean.setDebitamount(gridData[i][4]); generalLedgerBean.setCreditamount(gridData[i][5]); generalLedgerBean.setFund(gridData[i][8]); if (i == data.size()) generalLedgerBean.setCGN(""); else generalLedgerBean.setCGN(gridData[i][7]); generalLedgerBean.setCreditdate(gridData[i][10]); generalLedgerBean.setCreditvouchernumber(gridData[i][11]); generalLedgerBean.setDebitVoucherTypeName(gridData[i][12]); generalLedgerBean.setCreditVoucherTypeName(gridData[i][13]); generalLedgerBean.setVhId(gridData[i][14]); reportBean.setStartDate(startDateformat1); reportBean.setTotalCount(Integer.toString(totalCount)); reportBean.setIsConfirmedCount(Integer.toString(isConfirmedCount)); dataList.add(generalLedgerBean); } } catch (final Exception ex) { LOGGER.error("ERROR in getGeneralLedgerList " + ex.toString(), ex); throw taskExc; } return dataList; }