Example usage for java.lang StringBuffer insert

List of usage examples for java.lang StringBuffer insert

Introduction

In this page you can find the example usage for java.lang StringBuffer insert.

Prototype

@Override
public StringBuffer insert(int offset, double d) 

Source Link

Usage

From source file:com.xpn.xwiki.render.filter.XWikiLinkFilter.java

@Override
public void handleMatch(StringBuffer buffer, org.radeox.regex.MatchResult result, FilterContext context) {
    RenderEngine engine = context.getRenderContext().getRenderEngine();

    if (engine instanceof WikiRenderEngine) {
        WikiRenderEngine wikiEngine = (WikiRenderEngine) engine;
        Writer writer = new StringBufferWriter(buffer);

        XWikiContext xcontext = (XWikiContext) context.getRenderContext().get("xcontext");
        String str = result.group(1);
        if (str != null) {
            // TODO: This line creates bug XWIKI-188. The encoder seems to be broken. Fix this!
            // The only unescaping done should be %xx => char,
            // since &#nnn; must be preserved (the active encoding cannot handle the character)
            // and + should be preserved (for "Doc.C++ examples").
            // Anyway, this unescaper only treats &#nnn;
            // trim the name and unescape it
            // str = Encoder.unescape(str.trim());
            str = str.trim();/*from w w w .j ava 2  s . c om*/
            String text = null, href = null, target = null;
            boolean specificText = false;

            // Is there an alias like [alias|link] ?
            int pipeIndex = str.indexOf('|');
            int pipeLength = 1;
            if (pipeIndex == -1) {
                pipeIndex = str.indexOf('>');
            }
            if (pipeIndex == -1) {
                pipeIndex = str.indexOf(">");
                pipeLength = 4;
            }
            if (-1 != pipeIndex) {
                text = str.substring(0, pipeIndex).trim();
                str = str.substring(pipeIndex + pipeLength);
                specificText = true;
            }

            // Is there a target like [alias|link|target] ?
            pipeIndex = str.indexOf('|');
            pipeLength = 1;
            if (pipeIndex == -1) {
                pipeIndex = str.indexOf('>');
            }
            if (pipeIndex == -1) {
                pipeIndex = str.indexOf(">");
                pipeLength = 4;
            }
            if (-1 != pipeIndex) {
                target = str.substring(pipeIndex + pipeLength).trim();
                str = str.substring(0, pipeIndex);
            }
            // Done splitting

            // Fill in missing components
            href = str.trim();
            if (text == null) {
                text = href;
            }
            // Done, now print the link

            // Determine target type: external, interwiki, internal
            int protocolIndex = href.indexOf("://");
            if (((protocolIndex >= 0) && (protocolIndex < 10)) || (href.indexOf("mailto:") == 0)) {
                // External link
                buffer.append("<span class=\"wikiexternallink\"><a href=\"");
                buffer.append(Utils.createPlaceholder(Util.escapeURL(href), xcontext));
                buffer.append("\"");
                if (target != null) {
                    buffer.append(" " + constructRelAttribute(target, xcontext));
                } else {
                    XWiki xwiki = xcontext.getWiki();
                    String defaulttarget = xwiki.Param("xwiki.render.externallinks.defaulttarget", "");
                    if (!defaulttarget.equals("")) {
                        buffer.append(" " + constructRelAttribute(defaulttarget, xcontext));
                    }
                }
                buffer.append(">");
                buffer.append(Utils.createPlaceholder(cleanText(text), xcontext));
                buffer.append("</a></span>");
                return;
            }

            int hashIndex = href.lastIndexOf('#');
            String hash = "";

            if (-1 != hashIndex && hashIndex != href.length() - 1) {
                hash = href.substring(hashIndex + 1);
                href = href.substring(0, hashIndex);
            }
            if (href.trim().equals("")) {
                // Internal (anchor) link
                buffer.append("<span class=\"wikilink\"><a href=\"#");
                buffer.append(hash);
                buffer.append("\">");
                if (!specificText || text.length() == 0) {
                    text = Encoder.unescape(hash);
                }
                buffer.append(cleanText(text));
                buffer.append("</a></span>");
                return;
            }

            /*
             * // We need to keep this in XWiki int colonIndex = name.indexOf(':'); // typed link ? if (-1 !=
             * colonIndex) { // for now throw away the type information name = name.substring(colonIndex + 1); }
             */

            int atIndex = href.lastIndexOf('@');
            // InterWiki link
            if (-1 != atIndex) {
                String extSpace = href.substring(atIndex + 1);
                // Kown extarnal space?
                InterWiki interWiki = InterWiki.getInstance();
                if (interWiki.contains(extSpace)) {
                    href = href.substring(0, atIndex);
                    try {
                        if (-1 != hashIndex) {
                            interWiki.expand(writer, extSpace, href, text, hash);
                        } else {
                            interWiki.expand(writer, extSpace, href, text);
                        }
                    } catch (IOException e) {
                        log.debug("InterWiki " + extSpace + " not found.");
                    }
                } else {
                    buffer.append("&#91;<span class=\"error\">");
                    buffer.append(result.group(1));
                    buffer.append("?</span>&#93;");
                }
            } else {
                // internal link
                if (wikiEngine.exists(href)) {
                    if (specificText == false) {
                        text = getWikiView(href);
                        wikiEngine.appendLink(buffer, href, text, hash);
                    } else {
                        wikiEngine.appendLink(buffer, href, text, hash);
                    }
                } else if (wikiEngine.showCreate()) {
                    if (specificText == false) {
                        text = getWikiView(href);
                    }
                    wikiEngine.appendCreateLink(buffer, href, text);
                    // links with "create" are not cacheable because
                    // a missing wiki could be created
                    context.getRenderContext().setCacheable(false);
                } else {
                    // cannot display/create wiki, so just display the text
                    buffer.append(text);
                }
                if (target != null) {
                    int where = buffer.lastIndexOf(" href=\"");
                    if (where >= 0) {
                        buffer.insert(where, " " + constructRelAttribute(target, xcontext));
                    }
                }
            }
        } else {
            buffer.append(Encoder.escape(result.group(0)));
        }
    }
}

From source file:fr.paris.lutece.plugins.directory.web.action.ExportDirectoryAction.java

/**
 * {@inheritDoc}/*from   w  w  w .  jav a2 s.  co  m*/
 */
@Override
public IPluginActionResult process(HttpServletRequest request, HttpServletResponse response,
        AdminUser adminUser, DirectoryAdminSearchFields searchFields) throws AccessDeniedException {
    DefaultPluginActionResult result = new DefaultPluginActionResult();

    String strIdDirectory = request.getParameter(PARAMETER_ID_DIRECTORY);
    int nIdDirectory = DirectoryUtils.convertStringToInt(strIdDirectory);
    Directory directory = DirectoryHome.findByPrimaryKey(nIdDirectory, getPlugin());
    String strIdDirectoryXsl = request.getParameter(PARAMETER_ID_DIRECTORY_XSL);
    int nIdDirectoryXsl = DirectoryUtils.convertStringToInt(strIdDirectoryXsl);
    WorkflowService workflowService = WorkflowService.getInstance();
    boolean bWorkflowServiceEnable = workflowService.isAvailable();
    String strShotExportFinalOutPut = null;
    DirectoryXsl directoryXsl = DirectoryXslHome.findByPrimaryKey(nIdDirectoryXsl, getPlugin());

    // -----------------------------------------------------------------------
    if ((directory == null) || (directoryXsl == null) || !RBACService.isAuthorized(Directory.RESOURCE_TYPE,
            strIdDirectory, DirectoryResourceIdService.PERMISSION_MANAGE_RECORD, adminUser)) {
        throw new AccessDeniedException(
                I18nService.getLocalizedString(MESSAGE_ACCESS_DENIED, request.getLocale()));
    }

    String strFileExtension = directoryXsl.getExtension();
    String strFileName = directory.getTitle() + "." + strFileExtension;
    strFileName = UploadUtil.cleanFileName(strFileName);

    boolean bIsCsvExport = strFileExtension.equals(EXPORT_CSV_EXT);
    boolean bDisplayDateCreation = directory.isDateShownInExport();
    boolean bDisplayDateModification = directory.isDateModificationShownInExport();

    List<Integer> listResultRecordId = new ArrayList<Integer>();

    if (request.getParameter(PARAMETER_BUTTON_EXPORT_SEARCH) != null) {
        String[] selectedRecords = request.getParameterValues(PARAMETER_SELECTED_RECORD);
        List<String> listSelectedRecords;

        if (selectedRecords != null) {
            listSelectedRecords = Arrays.asList(selectedRecords);

            if ((listSelectedRecords != null) && (listSelectedRecords.size() > 0)) {
                for (String strRecordId : listSelectedRecords) {
                    listResultRecordId.add(Integer.parseInt(strRecordId));
                }
            }
        } else {
            // sort order and sort entry are not needed in export
            listResultRecordId = DirectoryUtils.getListResults(request, directory, bWorkflowServiceEnable, true,
                    null, RecordFieldFilter.ORDER_NONE, searchFields, adminUser, adminUser.getLocale());
        }
    } else {
        // sort order and sort entry are not needed in export
        listResultRecordId = DirectoryUtils.getListResults(request, directory, bWorkflowServiceEnable, false,
                null, RecordFieldFilter.ORDER_NONE, searchFields, adminUser, adminUser.getLocale());
    }

    EntryFilter entryFilter = new EntryFilter();
    entryFilter.setIdDirectory(directory.getIdDirectory());
    entryFilter.setIsGroup(EntryFilter.FILTER_FALSE);
    entryFilter.setIsComment(EntryFilter.FILTER_FALSE);
    entryFilter.setIsShownInExport(EntryFilter.FILTER_TRUE);

    List<IEntry> listEntryResultSearch = EntryHome.getEntryList(entryFilter, getPlugin());

    Map<Integer, Field> hashFields = DirectoryUtils.getMapFieldsOfListEntry(listEntryResultSearch, getPlugin());

    StringBuffer strBufferListRecordXml = null;

    java.io.File tmpFile = null;
    BufferedWriter bufferedWriter = null;
    OutputStreamWriter outputStreamWriter = null;

    File fileTemplate = null;
    String strFileOutPut = DirectoryUtils.EMPTY_STRING;

    if (directoryXsl.getFile() != null) {
        fileTemplate = FileHome.findByPrimaryKey(directoryXsl.getFile().getIdFile(), getPlugin());
    }

    XmlTransformerService xmlTransformerService = null;
    PhysicalFile physicalFile = null;
    String strXslId = null;

    if ((fileTemplate != null) && (fileTemplate.getPhysicalFile() != null)) {
        fileTemplate.setPhysicalFile(PhysicalFileHome
                .findByPrimaryKey(fileTemplate.getPhysicalFile().getIdPhysicalFile(), getPlugin()));

        xmlTransformerService = new XmlTransformerService();
        physicalFile = fileTemplate.getPhysicalFile();
        strXslId = XSL_UNIQUE_PREFIX_ID + physicalFile.getIdPhysicalFile();
    }

    int nSize = listResultRecordId.size();
    boolean bIsBigExport = (nSize > EXPORT_RECORD_STEP);

    // Encoding export
    String strEncoding = StringUtils.EMPTY;

    if (bIsCsvExport) {
        strEncoding = DirectoryParameterService.getService().getExportCSVEncoding();
    } else {
        strEncoding = DirectoryParameterService.getService().getExportXMLEncoding();
    }

    if (bIsBigExport) {
        try {
            String strPath = AppPathService.getWebAppPath()
                    + AppPropertiesService.getProperty(PROPERTY_PATH_TMP);
            java.io.File tmpDir = new java.io.File(strPath);
            tmpFile = java.io.File.createTempFile(EXPORT_TMPFILE_PREFIX, EXPORT_TMPFILE_SUFIX, tmpDir);
        } catch (IOException e) {
            AppLogService.error("Unable to create temp file in webapp tmp dir");

            try {
                tmpFile = java.io.File.createTempFile(EXPORT_TMPFILE_PREFIX, EXPORT_TMPFILE_SUFIX);
            } catch (IOException e1) {
                AppLogService.error(e1);
            }
        }

        try {
            tmpFile.deleteOnExit();
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream(tmpFile), strEncoding);
            bufferedWriter = new BufferedWriter(outputStreamWriter);
        } catch (IOException e) {
            AppLogService.error(e);
        }
    }

    Plugin plugin = this.getPlugin();
    Locale locale = request.getLocale();

    // ---------------------------------------------------------------------
    StringBuffer strBufferListEntryXml = new StringBuffer();

    if (bDisplayDateCreation && bIsCsvExport) {
        Map<String, String> model = new HashMap<String, String>();
        model.put(Entry.ATTRIBUTE_ENTRY_ID, "0");
        XmlUtil.beginElement(strBufferListEntryXml, Entry.TAG_ENTRY, model);

        String strDateCreation = I18nService.getLocalizedString(PROPERTY_ENTRY_TYPE_DATE_CREATION_TITLE,
                locale);
        XmlUtil.addElementHtml(strBufferListEntryXml, Entry.TAG_TITLE, strDateCreation);
        XmlUtil.endElement(strBufferListEntryXml, Entry.TAG_ENTRY);
    }

    if (bDisplayDateModification && bIsCsvExport) {
        Map<String, String> model = new HashMap<String, String>();
        model.put(Entry.ATTRIBUTE_ENTRY_ID, "0");
        XmlUtil.beginElement(strBufferListEntryXml, Entry.TAG_ENTRY, model);

        String strDateModification = I18nService.getLocalizedString(PROPERTY_ENTRY_TYPE_DATE_MODIFICATION_TITLE,
                locale);
        XmlUtil.addElementHtml(strBufferListEntryXml, Entry.TAG_TITLE, strDateModification);
        XmlUtil.endElement(strBufferListEntryXml, Entry.TAG_ENTRY);
    }

    for (IEntry entry : listEntryResultSearch) {
        entry.getXml(plugin, locale, strBufferListEntryXml);
    }

    Map<String, String> model = new HashMap<String, String>();

    if ((directory.getIdWorkflow() != DirectoryUtils.CONSTANT_ID_NULL) && bWorkflowServiceEnable) {
        model.put(TAG_DISPLAY, TAG_YES);
    } else {
        model.put(TAG_DISPLAY, TAG_NO);
    }

    XmlUtil.addEmptyElement(strBufferListEntryXml, TAG_STATUS, model);

    StringBuilder strBufferDirectoryXml = new StringBuilder();
    strBufferDirectoryXml.append(XmlUtil.getXmlHeader());

    if (bIsBigExport) {
        strBufferDirectoryXml
                .append(directory.getXml(plugin, locale, new StringBuffer(), strBufferListEntryXml));

        strBufferListRecordXml = new StringBuffer(EXPORT_STRINGBUFFER_INITIAL_SIZE);

        strFileOutPut = xmlTransformerService.transformBySourceWithXslCache(strBufferDirectoryXml.toString(),
                physicalFile.getValue(), strXslId, null, null);

        String strFinalOutPut = null;

        if (!bIsCsvExport) {
            int pos = strFileOutPut.indexOf(EXPORT_XSL_EMPTY_LIST_RECORD);
            strFinalOutPut = strFileOutPut.substring(0, pos) + EXPORT_XSL_BEGIN_LIST_RECORD;
        } else {
            strFinalOutPut = strFileOutPut;
        }

        try {
            bufferedWriter.write(strFinalOutPut);
        } catch (IOException e) {
            AppLogService.error(e);
        }
    } else {
        strBufferListRecordXml = new StringBuffer();
    }

    // -----------------------------------------------------------------------
    List<Integer> nTmpListId = new ArrayList<Integer>();
    int idWorflow = directory.getIdWorkflow();
    IRecordService recordService = SpringContextService.getBean(RecordService.BEAN_SERVICE);

    if (bIsBigExport) {
        int nXmlHeaderLength = XmlUtil.getXmlHeader().length() - 1;
        int max = nSize / EXPORT_RECORD_STEP;
        int max1 = nSize - EXPORT_RECORD_STEP;

        for (int i = 0; i < max1; i += EXPORT_RECORD_STEP) {
            AppLogService.debug("Directory export progress : " + (((float) i / nSize) * 100) + "%");

            nTmpListId = new ArrayList<Integer>();

            int k = i + EXPORT_RECORD_STEP;

            for (int j = i; j < k; j++) {
                nTmpListId.add(listResultRecordId.get(j));
            }

            List<Record> nTmpListRecords = recordService.loadListByListId(nTmpListId, plugin);

            for (Record record : nTmpListRecords) {
                State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE,
                        idWorflow, Integer.valueOf(directory.getIdDirectory()));

                if (bIsCsvExport) {
                    strBufferListRecordXml.append(record.getXmlForCsvExport(plugin, locale, false, state,
                            listEntryResultSearch, false, false, true, bDisplayDateCreation,
                            bDisplayDateModification, hashFields));
                } else {
                    strBufferListRecordXml
                            .append(record.getXml(plugin, locale, false, state, listEntryResultSearch, false,
                                    false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
                }
            }

            strBufferListRecordXml = this.appendPartialContent(strBufferListRecordXml, bufferedWriter,
                    physicalFile, bIsCsvExport, strXslId, nXmlHeaderLength, xmlTransformerService);
        }

        // -----------------------------------------------------------------------
        int max2 = EXPORT_RECORD_STEP * max;
        nTmpListId = new ArrayList<Integer>();

        for (int i = max2; i < nSize; i++) {
            nTmpListId.add(listResultRecordId.get((i)));
        }

        List<Record> nTmpListRecords = recordService.loadListByListId(nTmpListId, plugin);

        for (Record record : nTmpListRecords) {
            State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE,
                    idWorflow, Integer.valueOf(directory.getIdDirectory()));

            if (bIsCsvExport) {
                strBufferListRecordXml.append(
                        record.getXmlForCsvExport(plugin, locale, false, state, listEntryResultSearch, false,
                                false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
            } else {
                strBufferListRecordXml.append(record.getXml(plugin, locale, false, state, listEntryResultSearch,
                        false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
            }
        }

        strBufferListRecordXml = this.appendPartialContent(strBufferListRecordXml, bufferedWriter, physicalFile,
                bIsCsvExport, strXslId, nXmlHeaderLength, xmlTransformerService);

        strBufferListRecordXml.insert(0, EXPORT_XSL_BEGIN_PARTIAL_EXPORT);
        strBufferListRecordXml.insert(0, XmlUtil.getXmlHeader());
        strBufferListRecordXml.append(EXPORT_XSL_END_PARTIAL_EXPORT);
        strFileOutPut = xmlTransformerService.transformBySourceWithXslCache(strBufferListRecordXml.toString(),
                physicalFile.getValue(), strXslId, null, null);

        try {
            if (bIsCsvExport) {
                bufferedWriter.write(strFileOutPut);
            } else {
                bufferedWriter.write(strFileOutPut.substring(nXmlHeaderLength));
                bufferedWriter
                        .write(EXPORT_XSL_END_LIST_RECORD + EXPORT_XSL_NEW_LINE + EXPORT_XSL_END_DIRECTORY);
            }
        } catch (IOException e) {
            AppLogService.error(e);
        } finally {
            IOUtils.closeQuietly(bufferedWriter);
            IOUtils.closeQuietly(outputStreamWriter);
        }
    } else {
        List<Record> nTmpListRecords = recordService.loadListByListId(listResultRecordId, plugin);

        for (Record record : nTmpListRecords) {
            State state = workflowService.getState(record.getIdRecord(), Record.WORKFLOW_RESOURCE_TYPE,
                    idWorflow, Integer.valueOf(directory.getIdDirectory()));

            if (bIsCsvExport) {
                strBufferListRecordXml.append(
                        record.getXmlForCsvExport(plugin, locale, false, state, listEntryResultSearch, false,
                                false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
            } else {
                strBufferListRecordXml.append(record.getXml(plugin, locale, false, state, listEntryResultSearch,
                        false, false, true, bDisplayDateCreation, bDisplayDateModification, hashFields));
            }
        }

        strBufferDirectoryXml
                .append(directory.getXml(plugin, locale, strBufferListRecordXml, strBufferListEntryXml));
        strShotExportFinalOutPut = xmlTransformerService.transformBySourceWithXslCache(
                strBufferDirectoryXml.toString(), physicalFile.getValue(), strXslId, null, null);
    }

    // ----------------------------------------------------------------------- 
    DirectoryUtils.addHeaderResponse(request, response, strFileName);
    response.setCharacterEncoding(strEncoding);

    if (bIsCsvExport) {
        response.setContentType(CONSTANT_MIME_TYPE_CSV);
    } else {
        String strMimeType = FileSystemUtil.getMIMEType(strFileName);

        if (strMimeType != null) {
            response.setContentType(strMimeType);
        } else {
            response.setContentType(CONSTANT_MIME_TYPE_OCTETSTREAM);
        }
    }

    if (bIsBigExport) {
        FileChannel in = null;
        WritableByteChannel writeChannelOut = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(tmpFile).getChannel();
            out = response.getOutputStream();
            writeChannelOut = Channels.newChannel(out);
            response.setContentLength(Long.valueOf(in.size()).intValue());
            in.transferTo(0, in.size(), writeChannelOut);
            response.getOutputStream().close();
        } catch (IOException e) {
            AppLogService.error(e);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    AppLogService.error(e.getMessage(), e);
                }
            }

            IOUtils.closeQuietly(out);

            tmpFile.delete();
        }
    } else {
        PrintWriter out = null;

        try {
            out = response.getWriter();
            out.print(strShotExportFinalOutPut);
        } catch (IOException e) {
            AppLogService.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }

    result.setNoop(true);

    return result;
}

From source file:usbong.android.likha_collection_1.UsbongDecisionTreeEngineActivity.java

public void processNextButtonPressed() {
    wasNextButtonPressed = true;//from  w ww. j  a  va2  s . c  om
    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;// w  ww . j ava2 s. 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, 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:com.xpn.xwiki.doc.XWikiDocument.java

/**
 * @param fieldname the name of the field to display
 * @param type the type of the field to display
 * @param pref the prefix to add in the field identifier in edit display for example
 * @param obj the object containing the field to display
 * @param wrappingSyntaxId the syntax of the content in which the result will be included. This to take care of some
 *            escaping depending of the syntax.
 * @param context the XWiki context/*from  www.ja va2s .  c o m*/
 * @return the rendered field
 */
public String display(String fieldname, String type, String pref, BaseObject obj, String wrappingSyntaxId,
        XWikiContext context) {
    if (obj == null) {
        return "";
    }

    boolean isInRenderingEngine = BooleanUtils.toBoolean((Boolean) context.get("isInRenderingEngine"));
    HashMap<String, Object> backup = new HashMap<String, Object>();
    try {
        backupContext(backup, context);
        setAsContextDoc(context);

        type = type.toLowerCase();
        StringBuffer result = new StringBuffer();
        PropertyClass pclass = (PropertyClass) obj.getXClass(context).get(fieldname);
        String prefix = pref
                + this.localEntityReferenceSerializer.serialize(obj.getXClass(context).getDocumentReference())
                + "_" + obj.getNumber() + "_";

        if (pclass == null) {
            return "";
        } else if (pclass.isCustomDisplayed(context)) {
            pclass.displayCustom(result, fieldname, prefix, type, obj, context);
        } else if (type.equals("view")) {
            pclass.displayView(result, fieldname, prefix, obj, context);
        } else if (type.equals("rendered")) {
            String fcontent = pclass.displayView(fieldname, prefix, obj, context);
            // This mode is deprecated for the new rendering and should also be removed for the old rendering
            // since the way to implement this now is to choose the type of rendering to do in the class itself.
            // Thus for the new rendering we simply make this mode work like the "view" mode.
            if (is10Syntax(wrappingSyntaxId)) {
                result.append(getRenderedContent(fcontent, getSyntaxId(), context));
            } else {
                result.append(fcontent);
            }
        } else if (type.equals("edit")) {
            context.addDisplayedField(fieldname);
            // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
            // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
            // escaping. For example for a textarea check the TextAreaClass class.
            if (is10Syntax(wrappingSyntaxId)) {
                // Don't use pre when not in the rendernig engine since for template we don't evaluate wiki syntax.
                if (isInRenderingEngine) {
                    result.append("{pre}");
                }
            }
            pclass.displayEdit(result, fieldname, prefix, obj, context);
            if (is10Syntax(wrappingSyntaxId)) {
                if (isInRenderingEngine) {
                    result.append("{/pre}");
                }
            }
        } else if (type.equals("hidden")) {
            // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
            // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
            // escaping. For example for a textarea check the TextAreaClass class.
            if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
                result.append("{pre}");
            }
            pclass.displayHidden(result, fieldname, prefix, obj, context);
            if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
                result.append("{/pre}");
            }
        } else if (type.equals("search")) {
            // If the Syntax id is "xwiki/1.0" then use the old rendering subsystem and prevent wiki syntax
            // rendering using the pre macro. In the new rendering system it's the XWiki Class itself that does the
            // escaping. For example for a textarea check the TextAreaClass class.
            if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
                result.append("{pre}");
            }
            prefix = this.localEntityReferenceSerializer
                    .serialize(obj.getXClass(context).getDocumentReference()) + "_";
            pclass.displaySearch(result, fieldname, prefix, (XWikiCriteria) context.get("query"), context);
            if (is10Syntax(wrappingSyntaxId) && isInRenderingEngine) {
                result.append("{/pre}");
            }
        } else {
            pclass.displayView(result, fieldname, prefix, obj, context);
        }

        // If we're in new rendering engine we want to wrap the HTML returned by displayView() in
        // a {{html/}} macro so that the user doesn't have to do it.
        // We test if we're inside the rendering engine since it's also possible that this display() method is
        // called
        // directly from a template and in this case we only want HTML as a result and not wiki syntax.
        // TODO: find a more generic way to handle html macro because this works only for XWiki 1.0 and XWiki 2.0
        // Add the {{html}}{{/html}} only when result really contains html since it's not needed for pure text
        if (isInRenderingEngine && !is10Syntax(wrappingSyntaxId)
                && (result.indexOf("<") != -1 || result.indexOf(">") != -1)) {
            result.insert(0, "{{html clean=\"false\" wiki=\"false\"}}");
            result.append("{{/html}}");
        }

        return result.toString();
    } catch (Exception ex) {
        // TODO: It would better to check if the field exists rather than catching an exception
        // raised by a NPE as this is currently the case here...
        LOGGER.warn(
                "Failed to display field [" + fieldname + "] in [" + type + "] mode for Object of Class ["
                        + this.defaultEntityReferenceSerializer.serialize(obj.getDocumentReference()) + "]",
                ex);
        return "";
    } finally {
        restoreContext(backup, context);
    }
}

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 w  w  .j a  va  2s  .c o  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:cn.jsprun.struts.action.BasicSettingsAction.java

@SuppressWarnings("unchecked")
public ActionForward toCredits(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from   w  w  w . j  a  v  a2s.c  om
    try {
        if (submitCheck(request, "settingsubmit")) {
            String projectsave = request.getParameter("projectsave");
            String projectId = request.getParameter("projectid");
            Map<String, String> oldSettingMap = ForumInit.settings;
            Map<String, String> newSettingMap = new HashMap<String, String>();
            Map<Integer, Map> extcreditsMap = new HashMap<Integer, Map>();
            Map<String, Map> creditspolicyMap = new HashMap<String, Map>();
            Map<Integer, Integer> creditspolicyValue_post = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_reply = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_digest = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_postattach = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_getattach = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_pm = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_search = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_promotion_visit = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_promotion_register = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_tradefinished = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_votepoll = new TreeMap<Integer, Integer>();
            Map<Integer, Integer> creditspolicyValue_lowerlimit = new TreeMap<Integer, Integer>();
            String[] extcreditId = request.getParameterValues("extcreditId");
            StringBuffer initcreditBuffer = new StringBuffer();
            String creditstrans = request.getParameter("creditstrans");
            Map<String, String> creditMap = new HashMap<String, String>();
            for (int i = 0; i < extcreditId.length; i++) {
                Integer extcreditsKey = new Integer(extcreditId[i]);
                String extcredits_title = request.getParameter("extcredits_title_" + extcreditId[i]);
                String extcredits_unit = request.getParameter("extcredits_unit_" + extcreditId[i]);
                String extcredits_ratio = request.getParameter("extcredits_ratio_" + extcreditId[i]);
                extcredits_ratio = FormDataCheck.turnToDoubleString(extcredits_ratio);
                String extcredits_available = request.getParameter("extcredits_available_" + extcreditId[i]);
                if (extcredits_available == null && creditstrans.equals(extcreditId[i])) {
                    request.setAttribute("message", getMessage(request, "a_setting_creditstrans_invalid"));
                    request.setAttribute("return", true);
                    return mapping.findForward("message");
                }
                String extcredits_showinthread = request
                        .getParameter("extcredits_showinthread_" + extcreditId[i]);
                String extcredits_allowexchangeout = request
                        .getParameter("extcredits_allowexchangeout_" + extcreditId[i]);
                String extcredits_allowexchangein = request
                        .getParameter("extcredits_allowexchangein_" + extcreditId[i]);
                String creditspolicy_lowerlimit = request
                        .getParameter("creditspolicy_lowerlimit_" + extcreditId[i]);
                if (creditspolicy_lowerlimit == null) {
                    creditspolicy_lowerlimit = "0";
                } else {
                    creditspolicy_lowerlimit = getTrueString(creditspolicy_lowerlimit);
                }
                Map<String, Object> extcreditsValue = new TreeMap<String, Object>();
                extcreditsValue.put("title", extcredits_title);
                extcreditsValue.put("unit", extcredits_unit);
                extcreditsValue.put("ratio", Double.valueOf(extcredits_ratio));
                extcreditsValue.put("available", extcredits_available);
                extcreditsValue.put("showinthread", extcredits_showinthread);
                extcreditsValue.put("allowexchangeout", extcredits_allowexchangeout);
                extcreditsValue.put("allowexchangein", extcredits_allowexchangein);
                extcreditsValue.put("lowerlimit", Integer.valueOf(creditspolicy_lowerlimit));
                extcreditsMap.put(extcreditsKey, extcreditsValue);
                String creditspolicy_post = request.getParameter("creditspolicy_post_" + extcreditId[i]);
                if (creditspolicy_post != null) {
                    creditspolicy_post = getTrueString(creditspolicy_post);
                }
                String creditspolicy_reply = request.getParameter("creditspolicy_reply_" + extcreditId[i]);
                if (creditspolicy_reply != null) {
                    creditspolicy_reply = getTrueString(creditspolicy_reply);
                }
                String creditspolicy_digest = request.getParameter("creditspolicy_digest_" + extcreditId[i]);
                if (creditspolicy_digest != null) {
                    creditspolicy_digest = getTrueString(creditspolicy_digest);
                }
                String creditspolicy_postattach = request
                        .getParameter("creditspolicy_postattach_" + extcreditId[i]);
                if (creditspolicy_postattach != null) {
                    creditspolicy_postattach = getTrueString(creditspolicy_postattach);
                }
                String creditspolicy_getattach = request
                        .getParameter("creditspolicy_getattach_" + extcreditId[i]);
                if (creditspolicy_getattach != null) {
                    creditspolicy_getattach = getTrueString(creditspolicy_getattach);
                }
                String creditspolicy_pm = request.getParameter("creditspolicy_pm_" + extcreditId[i]);
                if (creditspolicy_pm != null) {
                    creditspolicy_pm = getTrueString(creditspolicy_pm);
                }
                String creditspolicy_search = request.getParameter("creditspolicy_search_" + extcreditId[i]);
                if (creditspolicy_search != null) {
                    creditspolicy_search = getTrueString(creditspolicy_search);
                }
                String creditspolicy_promotion_visit = request
                        .getParameter("creditspolicy_promotion_visit_" + extcreditId[i]);
                if (creditspolicy_promotion_visit != null) {
                    creditspolicy_promotion_visit = getTrueString(creditspolicy_promotion_visit);
                }
                String creditspolicy_promotion_register = request
                        .getParameter("creditspolicy_promotion_register_" + extcreditId[i]);
                if (creditspolicy_promotion_register != null) {
                    creditspolicy_promotion_register = getTrueString(creditspolicy_promotion_register);
                }
                String creditspolicy_tradefinished = request
                        .getParameter("creditspolicy_tradefinished_" + extcreditId[i]);
                if (creditspolicy_tradefinished != null) {
                    creditspolicy_tradefinished = getTrueString(creditspolicy_tradefinished);
                }
                String creditspolicy_votepoll = request
                        .getParameter("creditspolicy_votepoll_" + extcreditId[i]);
                if (creditspolicy_votepoll != null) {
                    creditspolicy_votepoll = getTrueString(creditspolicy_votepoll);
                }
                String initcreditString = request.getParameter("initcredits_" + extcreditId[i]);
                initcreditString = FormDataCheck.getNumberFromFormOfDisplayorder(initcreditString);
                try {
                    Integer.valueOf(initcreditString);
                } catch (Exception exception) {
                    if (initcreditString.startsWith("-")) {
                        initcreditString = Integer.valueOf(Integer.MIN_VALUE).toString();
                    } else {
                        initcreditString = Integer.valueOf(Integer.MAX_VALUE).toString();
                    }
                }
                if (i + 1 == extcreditId.length) {
                    initcreditBuffer = initcreditBuffer.append(initcreditString);
                } else {
                    initcreditBuffer = initcreditBuffer.append(initcreditString + ",");
                }
                creditMap.put("extcredits" + extcreditId[i], initcreditString);
                if (creditspolicy_post != null && !"0".equals(creditspolicy_post)) {
                    creditspolicyValue_post.put(extcreditsKey, Integer.valueOf(creditspolicy_post));
                }
                if (creditspolicy_reply != null && !"0".equals(creditspolicy_reply)) {
                    creditspolicyValue_reply.put(extcreditsKey, Integer.valueOf(creditspolicy_reply));
                }
                if (creditspolicy_digest != null && !"0".equals(creditspolicy_digest)) {
                    creditspolicyValue_digest.put(extcreditsKey, Integer.valueOf(creditspolicy_digest));
                }
                if (creditspolicy_postattach != null && !"0".equals(creditspolicy_postattach)) {
                    creditspolicyValue_postattach.put(extcreditsKey, Integer.valueOf(creditspolicy_postattach));
                }
                if (creditspolicy_getattach != null && !"0".equals(creditspolicy_getattach)) {
                    creditspolicyValue_getattach.put(extcreditsKey, Integer.valueOf(creditspolicy_getattach));
                }
                if (creditspolicy_pm != null && !"0".equals(creditspolicy_pm)) {
                    creditspolicyValue_pm.put(extcreditsKey, Integer.valueOf(creditspolicy_pm));
                }
                if (creditspolicy_search != null && !"0".equals(creditspolicy_search)) {
                    creditspolicyValue_search.put(extcreditsKey, Integer.valueOf(creditspolicy_search));
                }
                if (creditspolicy_promotion_visit != null && !"0".equals(creditspolicy_promotion_visit)) {
                    creditspolicyValue_promotion_visit.put(extcreditsKey,
                            Integer.valueOf(creditspolicy_promotion_visit));
                }
                if (creditspolicy_promotion_register != null && !"0".equals(creditspolicy_promotion_register)) {
                    creditspolicyValue_promotion_register.put(extcreditsKey,
                            Integer.valueOf(creditspolicy_promotion_register));
                }
                if (creditspolicy_tradefinished != null && !"0".equals(creditspolicy_tradefinished)) {
                    creditspolicyValue_tradefinished.put(extcreditsKey,
                            Integer.valueOf(creditspolicy_tradefinished));
                }
                if (creditspolicy_votepoll != null && !"0".equals(creditspolicy_votepoll)) {
                    creditspolicyValue_votepoll.put(extcreditsKey, Integer.valueOf(creditspolicy_votepoll));
                }
                if (creditspolicy_lowerlimit != null && !"0".equals(creditspolicy_lowerlimit)) {
                    creditspolicyValue_lowerlimit.put(extcreditsKey, Integer.valueOf(creditspolicy_lowerlimit));
                }
            }
            creditspolicyMap.put("post", creditspolicyValue_post);
            creditspolicyMap.put("reply", creditspolicyValue_reply);
            creditspolicyMap.put("digest", creditspolicyValue_digest);
            creditspolicyMap.put("postattach", creditspolicyValue_postattach);
            creditspolicyMap.put("getattach", creditspolicyValue_getattach);
            creditspolicyMap.put("pm", creditspolicyValue_pm);
            creditspolicyMap.put("search", creditspolicyValue_search);
            creditspolicyMap.put("promotion_visit", creditspolicyValue_promotion_visit);
            creditspolicyMap.put("promotion_register", creditspolicyValue_promotion_register);
            creditspolicyMap.put("tradefinished", creditspolicyValue_tradefinished);
            creditspolicyMap.put("votepoll", creditspolicyValue_votepoll);
            creditspolicyMap.put("lowerlimit", creditspolicyValue_lowerlimit);
            String extcredits_bak = dataParse.combinationChar(extcreditsMap);
            putValue("extcredits", extcredits_bak, oldSettingMap, newSettingMap);
            putValue("creditspolicy", dataParse.combinationChar(creditspolicyMap), oldSettingMap,
                    newSettingMap);
            String creditsformula = request.getParameter("creditsformula");
            if (creditsformula == null || creditsformula.trim().equals("")
                    || !validateExpressions(creditsformula)) {
                request.setAttribute("message", getMessage(request, "a_setting_creditsformula_invalid"));
                request.setAttribute("return", true);
                return mapping.findForward("message");
            }
            putValue("creditsformula", creditsformula, oldSettingMap, newSettingMap);
            PostOperating postOperating = (PostOperating) BeanFactory.getBean("postOperating");
            int totalCredit = postOperating.getTotalCredits(creditsformula, creditMap);
            initcreditBuffer.insert(0, ",");
            initcreditBuffer.insert(0, totalCredit);
            putValue("initcredits", initcreditBuffer.toString(), oldSettingMap, newSettingMap);
            putValue("creditsformulaexp", trunExpression(creditsformula, extcreditsMap, request), oldSettingMap,
                    newSettingMap);
            putValue("creditstrans", creditstrans, oldSettingMap, newSettingMap);
            String creditstax = request.getParameter("creditstax");
            creditstax = FormDataCheck.turnToDoubleString(creditstax);
            Double double1 = Double.valueOf(creditstax);
            if (double1 >= 1) {
                creditstax = "0";
            }
            if (double1 < 0) {
                creditstax = "0";
            }
            putValue("creditstax", creditstax, oldSettingMap, newSettingMap);
            String transfermincredits = request.getParameter("transfermincredits");
            if (!transfermincredits.equals("INF") && !transfermincredits.equals("-INF")) {
                transfermincredits = Double.valueOf(FormDataCheck.getDoubleString(transfermincredits))
                        .toString();
            }
            if (transfermincredits.equals("Infinity")) {
                transfermincredits = "INF";
            }
            if (transfermincredits.equals("-Infinity")) {
                transfermincredits = "-INF";
            }
            if (transfermincredits.endsWith(".0")) {
                transfermincredits = transfermincredits.substring(0, transfermincredits.length() - 2);
            }
            putValue("transfermincredits", transfermincredits, oldSettingMap, newSettingMap);
            String exchangemincredits = request.getParameter("exchangemincredits");
            if (!exchangemincredits.equals("INF") && !exchangemincredits.equals("-INF")) {
                exchangemincredits = Double.valueOf(FormDataCheck.getDoubleString(exchangemincredits))
                        .toString();
            }
            if (exchangemincredits.equals("Infinity")) {
                exchangemincredits = "INF";
            }
            if (exchangemincredits.equals("-Infinity")) {
                exchangemincredits = "-INF";
            }
            if (exchangemincredits.endsWith(".0")) {
                exchangemincredits = exchangemincredits.substring(0, exchangemincredits.length() - 2);
            }
            putValue("exchangemincredits", exchangemincredits, oldSettingMap, newSettingMap);
            String maxincperthread = request.getParameter("maxincperthread");
            if (!maxincperthread.equals("INF") && !maxincperthread.equals("-INF")) {
                maxincperthread = Double.valueOf(FormDataCheck.getDoubleString(maxincperthread)).toString();
            }
            if (maxincperthread.equals("Infinity")) {
                maxincperthread = "INF";
            }
            if (maxincperthread.equals("-Infinity")) {
                maxincperthread = "-INF";
            }
            if (maxincperthread.endsWith(".0")) {
                maxincperthread = maxincperthread.substring(0, maxincperthread.length() - 2);
            }
            putValue("maxincperthread", maxincperthread, oldSettingMap, newSettingMap);
            String maxchargespan = request.getParameter("maxchargespan");
            if (!maxchargespan.equals("INF") && !maxchargespan.equals("-INF")) {
                maxchargespan = Double.valueOf(FormDataCheck.getDoubleString(maxchargespan)).toString();
            }
            if (maxchargespan.equals("Infinity")) {
                maxchargespan = "INF";
            }
            if (maxchargespan.equals("-Infinity")) {
                maxchargespan = "-INF";
            }
            if (maxchargespan.endsWith(".0")) {
                maxchargespan = maxchargespan.substring(0, maxchargespan.length() - 2);
            }
            putValue("maxchargespan", maxchargespan, oldSettingMap, newSettingMap);
            updateSettings(newSettingMap, oldSettingMap);
            oldSettingMap.put("extcredits_bak", extcredits_bak);
            updateExtcredits(oldSettingMap);
            if (newSettingMap.get("creditsformula") != null) {
                String hql = "UPDATE Members SET credits =" + creditsformula;
                memberService.updateMembers(hql);
            }
            if (projectsave.equals("projectsave")) {
                boolean isfounder = (Boolean) request.getAttribute("isfounder");
                if (!isfounder) {
                    request.setAttribute("message", getMessage(request, "noaccess_isfounder"));
                    return mapping.findForward("message");
                }
                if (!projectId.equals("0")) {
                    Short id = new Short(projectId);
                    Projects project = creSetSer.findBuId(id);
                    SaveMethodVO saveMethodVO = new SaveMethodVO();
                    Map map = dataParse.characterParse(project.getValue(), true);
                    Map map2 = (Map) map.get("savemethod");
                    Collection<String> collection = map2.values();
                    Iterator<String> iterator = collection.iterator();
                    while (iterator.hasNext()) {
                        String temp = iterator.next();
                        if (temp.equals("1")) {
                            saveMethodVO.setProjectSetting(1);
                        }
                        if (temp.equals("2")) {
                            saveMethodVO.setExpressionsSetting(1);
                        }
                        if (temp.equals("3")) {
                            saveMethodVO.setUseSetting(1);
                        }
                    }
                    request.setAttribute("saveMethodVO", saveMethodVO);
                    request.setAttribute("project", project);
                }
                return mapping.findForward("saveProject");
            }
            request.setAttribute("message", getMessage(request, "a_setting_baseset_success"));
            request.setAttribute("url_forward",
                    request.getContextPath() + FinalProperty.FROM_BasicSettingsAction_GO_credits);
            return mapping.findForward("message");
        } else if (submitCheck(request, "addsubmit")) {
            String[] savemethod = request.getParameterValues("savemethod");
            Map<String, String> settingMap = ForumInit.settings;
            Map<String, Object> outMap = new TreeMap<String, Object>();
            Map<Integer, String> savemethodMap = new TreeMap<Integer, String>();
            if (savemethod == null) {
                request.setAttribute("message", getMessage(request, "a_setting_project_no_item"));
                request.setAttribute("return", true);
                return mapping.findForward("message");
            } else {
                for (int i = 0; i < savemethod.length; i++) {
                    if (savemethod[i].equals("all")) {
                        savemethodMap.put(0, "1");
                        savemethodMap.put(1, "2");
                        savemethodMap.put(2, "3");
                        String extcredits = settingMap.get("extcredits_bak");
                        outMap.put("extcredits", extcredits);
                        String creditspolicy = settingMap.get("creditspolicy");
                        outMap.put("creditspolicy", creditspolicy);
                        String creditsformula = settingMap.get("creditsformula");
                        outMap.put("creditsformula", creditsformula);
                        String creditstrans = settingMap.get("creditstrans");
                        outMap.put("creditstrans", creditstrans);
                        String creditstax = settingMap.get("creditstax");
                        outMap.put("creditstax", creditstax);
                        String transfermincredits = settingMap.get("transfermincredits");
                        outMap.put("transfermincredits", transfermincredits);
                        String exchangemincredits = settingMap.get("exchangemincredits");
                        outMap.put("exchangemincredits", exchangemincredits);
                        String maxincperthread = settingMap.get("maxincperthread");
                        outMap.put("maxincperthread", maxincperthread);
                        String maxchargespan = settingMap.get("maxchargespan");
                        outMap.put("maxchargespan", maxchargespan);
                        break;
                    } else if (savemethod[i].equals("1")) {
                        savemethodMap.put(i, "1");
                        String extcredits = settingMap.get("extcredits_bak");
                        outMap.put("extcredits", extcredits);
                        String creditspolicy = settingMap.get("creditspolicy");
                        outMap.put("creditspolicy", creditspolicy);
                        if (outMap.get("creditsformula") == null) {
                            outMap.put("creditsformula", null);
                        }
                        if (outMap.get("creditstrans") == null) {
                            outMap.put("creditstrans", null);
                        }
                        if (outMap.get("creditstax") == null) {
                            outMap.put("creditstax", null);
                        }
                        if (outMap.get("transfermincredits") == null) {
                            outMap.put("transfermincredits", null);
                        }
                        if (outMap.get("exchangemincredits") == null) {
                            outMap.put("exchangemincredits", null);
                        }
                        if (outMap.get("maxincperthread") == null) {
                            outMap.put("maxincperthread", null);
                        }
                        if (outMap.get("maxchargespan") == null) {
                            outMap.put("maxchargespan", null);
                        }
                    } else if (savemethod[i].equals("2")) {
                        savemethodMap.put(i, "2");
                        String creditsformula = settingMap.get("creditsformula");
                        outMap.put("creditsformula", creditsformula);
                        if (outMap.get("extcredits") == null) {
                            String extcredits = settingMap.get("extcredits_bak");
                            extcredits = clearMap(extcredits);
                            outMap.put("extcredits", extcredits);
                        }
                        if (outMap.get("creditspolicy") == null) {
                            String creditspolicy = settingMap.get("creditspolicy");
                            creditspolicy = clearMap(creditspolicy);
                            outMap.put("creditspolicy", creditspolicy);
                        }
                        if (outMap.get("creditstrans") == null) {
                            outMap.put("creditstrans", null);
                        }
                        if (outMap.get("creditstax") == null) {
                            outMap.put("creditstax", null);
                        }
                        if (outMap.get("transfermincredits") == null) {
                            outMap.put("transfermincredits", null);
                        }
                        if (outMap.get("exchangemincredits") == null) {
                            outMap.put("exchangemincredits", null);
                        }
                        if (outMap.get("maxincperthread") == null) {
                            outMap.put("maxincperthread", null);
                        }
                        if (outMap.get("maxchargespan") == null) {
                            outMap.put("maxchargespan", null);
                        }
                    } else if (savemethod[i].equals("3")) {
                        savemethodMap.put(i, "3");
                        String creditstrans = settingMap.get("creditstrans");
                        outMap.put("creditstrans", creditstrans);
                        String creditstax = settingMap.get("creditstax");
                        outMap.put("creditstax", creditstax);
                        String transfermincredits = settingMap.get("transfermincredits");
                        outMap.put("transfermincredits", transfermincredits);
                        String exchangemincredits = settingMap.get("exchangemincredits");
                        outMap.put("exchangemincredits", exchangemincredits);
                        String maxincperthread = settingMap.get("maxincperthread");
                        outMap.put("maxincperthread", maxincperthread);
                        String maxchargespan = settingMap.get("maxchargespan");
                        outMap.put("maxchargespan", maxchargespan);
                        if (outMap.get("creditsformula") == null) {
                            outMap.put("creditsformula", null);
                        }
                        if (outMap.get("extcredits") == null) {
                            String extcredits = settingMap.get("extcredits_bak");
                            extcredits = clearMap(extcredits);
                            outMap.put("extcredits", extcredits);
                        }
                        if (outMap.get("creditspolicy") == null) {
                            String creditspolicy = settingMap.get("creditspolicy");
                            creditspolicy = clearMap(creditspolicy);
                            outMap.put("creditspolicy", creditspolicy);
                        }
                    }
                }
                outMap.put("savemethod", savemethodMap);
            }
            String value = dataParse.combinationChar(outMap);
            String name = request.getParameter("name");
            if (name == null || name.equals("")) {
                request.setAttribute("message", getMessage(request, "project_no_title"));
                request.setAttribute("return", true);
                return mapping.findForward("message");
            }
            if (name.length() > 50) {
                name = name.substring(0, 50);
            }
            String projectid = request.getParameter("projectid");
            String coverwith = request.getParameter("coverwith");
            String description = request.getParameter("description");
            if (projectid != null && coverwith.equals("1")) {
                dataBaseService
                        .execute("UPDATE " + tablePrefix + "projects SET name='" + Common.addslashes(name)
                                + "',type='extcredit',description='" + Common.addslashes(description)
                                + "',value='" + Common.addslashes(value) + "' WHERE id=" + projectid);
            } else {
                dataBaseService.execute("INSERT INTO " + tablePrefix + "projects VALUES(DEFAULT,'"
                        + Common.addslashes(name) + "','extcredit','" + Common.addslashes(description) + "','"
                        + Common.addslashes(value) + "')");
            }
            request.setAttribute("message", getMessage(request, "project_sava_succeed"));
            request.setAttribute("url_forward",
                    request.getContextPath() + FinalProperty.FROM_BasicSettingsAction_GO_credits);
            return mapping.findForward("message");
        }
    } catch (Exception e) {
        request.setAttribute("message", e.getMessage());
        return mapping.findForward("message");
    }
    String projectId = request.getParameter("projectid");
    Map extcredits = null;
    Map creditspolicy = null;
    String creditsformula = null;
    String creditstrans = null;
    String creditstax = null;
    String transfermincredits = null;
    String exchangemincredits = null;
    String maxincperthread = null;
    String maxchargespan = null;
    if (projectId == null || projectId.equals("0")) {
        Map<String, String> settingMap = ForumInit.settings;
        extcredits = dataParse.characterParse(settingMap.get("extcredits_bak"), true);
        creditspolicy = dataParse.characterParse(settingMap.get("creditspolicy"), true);
        creditsformula = settingMap.get("creditsformula");
        creditstrans = settingMap.get("creditstrans");
        creditstax = settingMap.get("creditstax");
        transfermincredits = settingMap.get("transfermincredits");
        exchangemincredits = settingMap.get("exchangemincredits");
        maxincperthread = settingMap.get("maxincperthread");
        maxchargespan = settingMap.get("maxchargespan");
    } else {
        Short id = new Short(projectId);
        Projects project = creSetSer.findBuId(id);
        if (project != null) {
            String str = project.getValue();
            Map temp = dataParse.characterParse(str, true);
            extcredits = dataParse.characterParse((String) temp.get("extcredits"), true);
            creditspolicy = dataParse.characterParse((String) temp.get("creditspolicy"), true);
            creditstrans = (String) temp.get("creditstrans");
            creditsformula = (String) temp.get("creditsformula");
            creditstax = (String) temp.get("creditstax");
            transfermincredits = (String) temp.get("transfermincredits");
            exchangemincredits = (String) temp.get("exchangemincredits");
            maxincperthread = (String) temp.get("maxincperthread");
            maxchargespan = (String) temp.get("maxchargespan");
        }
    }
    request.setAttribute("projectId", projectId);
    request.setAttribute("extcredits", extcredits);
    request.setAttribute("creditspolicy", creditspolicy);
    request.setAttribute("creditstrans", creditstrans);
    request.setAttribute("creditsformula", creditsformula);
    request.setAttribute("creditstax", creditstax);
    request.setAttribute("transfermincredits", transfermincredits);
    request.setAttribute("exchangemincredits", exchangemincredits);
    request.setAttribute("maxincperthread", maxincperthread);
    request.setAttribute("maxchargespan", maxchargespan);
    request.setAttribute("projects", dataBaseService
            .executeQuery("SELECT id,name FROM " + tablePrefix + "projects WHERE type='extcredit'"));
    request.setAttribute("initcredits", ForumInit.settings.get("initcredits").split(","));
    return mapping.findForward("credit");
}