Example usage for java.util StringTokenizer countTokens

List of usage examples for java.util StringTokenizer countTokens

Introduction

In this page you can find the example usage for java.util StringTokenizer countTokens.

Prototype

public int countTokens() 

Source Link

Document

Calculates the number of times that this tokenizer's nextToken method can be called before it generates an exception.

Usage

From source file:org.dcache.chimera.JdbcFs.java

private String[] getArgs(byte[] bytes) {

    StringTokenizer st = new StringTokenizer(new String(bytes), "[:]");
    int argc = st.countTokens();
    String[] args = new String[argc];
    for (int i = 0; i < argc; i++) {
        args[i] = st.nextToken();/*from   w ww . j  a v a 2 s.c  o  m*/
    }

    return args;
}

From source file:de.tor.tribes.ui.views.DSWorkbenchReTimerFrame.java

private void copyAttacksToClipboardAsBBCode() {
    jideRetimeTabbedPane.setSelectedIndex(1);
    try {//from w w  w .  j  a  v a 2  s .  c  o  m
        List<Attack> attacks = getSelectedAttacks();
        if (attacks.isEmpty()) {
            showInfo("Keine Angriffe ausgewhlt");
            return;
        }
        boolean extended = (JOptionPaneHelper.showQuestionConfirmBox(this,
                "Erweiterte BB-Codes verwenden (nur fr Forum und Notizen geeignet)?", "Erweiterter BB-Code",
                "Nein", "Ja") == JOptionPane.YES_OPTION);

        StringBuilder buffer = new StringBuilder();
        if (extended) {
            buffer.append("[u][size=12]Angriffsplan[/size][/u]\n\n");
        } else {
            buffer.append("[u]Angriffsplan[/u]\n\n");
        }

        buffer.append(new AttackListFormatter().formatElements(attacks, extended));

        if (extended) {
            buffer.append("\n[size=8]Erstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "[/size]\n");
        } else {
            buffer.append("\nErstellt am ");
            buffer.append(
                    new SimpleDateFormat("dd.MM.yy 'um' HH:mm:ss").format(Calendar.getInstance().getTime()));
            buffer.append(" mit DS Workbench ");
            buffer.append(Constants.VERSION).append(Constants.VERSION_ADDITION + "\n");
        }

        String b = buffer.toString();
        StringTokenizer t = new StringTokenizer(b, "[");
        int cnt = t.countTokens();
        if (cnt > 1000) {
            if (JOptionPaneHelper.showQuestionConfirmBox(this,
                    "Die ausgewhlten Angriffe bentigen mehr als 1000 BB-Codes\n"
                            + "und knnen daher im Spiel (Forum/IGM/Notizen) nicht auf einmal dargestellt werden.\nTrotzdem exportieren?",
                    "Zu viele BB-Codes", "Nein", "Ja") == JOptionPane.NO_OPTION) {
                return;
            }
        }

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(b), null);
        String result = "Daten in Zwischenablage kopiert.";
        showSuccess(result);
    } catch (Exception e) {
        logger.error("Failed to copy data to clipboard", e);
        String result = "Fehler beim Kopieren in die Zwischenablage.";
        showError(result);
    }
}

From source file:edu.tsinghua.lumaqq.ui.debug.Debugger.java

private void initTextMenu() {
    MenuItem mi;// w  w  w  .  j  a  v a  2  s .  c o m
    // body????
    textMenu = new Menu(getShell());
    // copy
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Copy");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            byte[] b = Util.convertHexStringToByte(getSelectionText());
            if (b != null) {
                Clipboard clipboard = new Clipboard(display);
                clipboard.setContents(new Object[] { textBytes.getSelectionText() },
                        new Transfer[] { TextTransfer.getInstance() });
                clipboard.dispose();
            }
        }
    });
    // copy as string
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Copy As String");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            byte[] b = Util.convertHexStringToByte(getSelectionText());
            if (b != null) {
                Clipboard clipboard = new Clipboard(display);
                clipboard.setContents(new Object[] { Util.getString(b) },
                        new Transfer[] { TextTransfer.getInstance() });
                clipboard.dispose();
            }
        }
    });
    // separator
    mi = new MenuItem(textMenu, SWT.SEPARATOR);
    // As Text
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Show as Text");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            byte[] b = Util.convertHexStringToByte(getSelectionText());
            if (b != null) {
                String msg = Util.getString(b);
                showMessage(msg);
            }
        }
    });
    // get ip
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Show as IP");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            StringTokenizer st = new StringTokenizer(getSelectionText(), " ");
            int len = st.countTokens();
            if (len != 4)
                showWarning("To show an IP, you should selected 4 bytes.");
            else {
                byte[] ip = Util.convertHexStringToByte(getSelectionText());
                showMessage(edu.tsinghua.lumaqq.qq.Util.getIpStringFromBytes(ip));
            }
        }
    });
    // get port
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Show as Port");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            StringTokenizer st = new StringTokenizer(getSelectionText(), " ");
            int len = st.countTokens();
            if (len != 2)
                showWarning("To show a port, you should selected 2 bytes.");
            else {
                byte[] ip = Util.convertHexStringToByte(getSelectionText());
                int port = (ip[0] << 8) & 0xFF00 | ip[1] & 0xFF;
                showMessage(String.valueOf(port));
            }
        }
    });
    // get integer
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Show as Integer");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            StringTokenizer st = new StringTokenizer(getSelectionText(), " ");
            int len = st.countTokens();
            if (len > 4)
                showWarning("To show a integer, you should selected no more than 4 bytes.");
            else {
                String s = getSelectionText().replaceAll(" ", "");
                int i = Util.getInt(s, 16, 0);
                showMessage(String.valueOf(i));
            }
        }
    });
    // get long
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Show as Long");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            StringTokenizer st = new StringTokenizer(getSelectionText(), " ");
            int len = st.countTokens();
            if (len > 8)
                showWarning("To show a integer, you should selected no more than 8 bytes.");
            else {
                String s = getSelectionText().replaceAll(" ", "");
                long l = Util.getLong(s, 16, 0);
                showMessage(String.valueOf(l));
            }
        }
    });
    // get time
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Show as Time");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            StringTokenizer st = new StringTokenizer(getSelectionText(), " ");
            int len = st.countTokens();
            if (len > 4)
                showWarning("To show a integer, you should selected no more than 4 bytes.");
            else {
                String s = getSelectionText().replaceAll(" ", "");
                long t = Util.getLong(s, 16, 0) * 1000L;
                showMessage(new Date(t).toString());
            }
        }
    });
    // separator
    mi = new MenuItem(textMenu, SWT.SEPARATOR);
    // Go to
    mi = new MenuItem(textMenu, SWT.PUSH);
    mi.setText("Go To...");
    mi.addSelectionListener(new SelectionAdapter() {
        public void widgetSelected(SelectionEvent e) {
            String s = getInput("Which byte you want to locate");
            if (s == null)
                showWarning("You Should Input a Integer");
            else {
                int index = Util.getInt(s, -1);
                if (index == -1)
                    return;
                textBytes.setSelection(index * 3, index * 3 + 2);
            }
        }
    });
    // menu listener
    textMenu.addMenuListener(new MenuAdapter() {
        public void menuShown(MenuEvent e) {
            textMenu.getItem(0).setEnabled(getSelectionText().length() > 0);
        }
    });
}

From source file:com.mobicage.rogerthat.MainService.java

private void readVersion() {
    T.UI();//from   ww w  .  j a  v a 2s.co  m
    try {
        // versionName = "1.0.950.A" or "1.0.950.AD"
        final StringTokenizer st = new StringTokenizer(getVersion(this), ".");
        if (st.countTokens() == 4) {
            st.nextToken();
            mMajorVersion = Integer.valueOf(st.nextToken());
            mMinorVersion = Integer.valueOf(st.nextToken());
        }
        L.d("Major version is " + mMajorVersion + " / Minor version is " + mMinorVersion);
        return;
    } catch (Exception e) {
        L.d(e);
    }
    L.d("Could not retrieve package version");
    mMajorVersion = 1;
    mMinorVersion = 1;
}

From source file:it.classhidra.core.controller.bean.java

public void initNormal(HttpServletRequest request) throws bsControllerException {
    xmloutput = false;// w ww.j  a v a  2s  .  c om
    jsonoutput = false;
    boolean inputBase64 = (request.getParameter(bsController.CONST_ID_INPUTBASE64) != null
            && (request.getParameter(bsController.CONST_ID_INPUTBASE64).equalsIgnoreCase("true")
                    || request.getParameter(bsController.CONST_ID_INPUTBASE64)
                            .equalsIgnoreCase(Base64.encodeBase64String("true".getBytes()))));

    Enumeration en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        String value = request.getParameter(key);
        String format = request.getParameter("$format_" + key);
        String replaceOnBlank = request.getParameter("$replaceOnBlank_" + key);
        String replaceOnErrorFormat = request.getParameter("$replaceOnErrorFormat_" + key);

        if (inputBase64) {
            String charset = (request.getCharacterEncoding() == null
                    || request.getCharacterEncoding().equals("")) ? "UTF-8" : request.getCharacterEncoding();
            try {
                if (value != null)
                    value = new String(Base64.decodeBase64(value), charset);
            } catch (Exception e) {
            }
            try {
                if (format != null)
                    format = new String(Base64.decodeBase64(format), charset);
            } catch (Exception e) {
            }
            try {
                if (replaceOnBlank != null)
                    replaceOnBlank = new String(Base64.decodeBase64(replaceOnBlank), charset);
            } catch (Exception e) {
            }
            try {
                if (replaceOnErrorFormat != null)
                    replaceOnErrorFormat = new String(Base64.decodeBase64(replaceOnErrorFormat), charset);
            } catch (Exception e) {
            }
        }

        if (key.indexOf(".") == -1) {
            try {
                Object makedValue = null;
                if (format != null) {
                    if (delegated != null) {
                        makedValue = util_makeValue.makeFormatedValue1(delegated, format, value, key,
                                replaceOnBlank, replaceOnErrorFormat);
                        if (makedValue == null)
                            makedValue = util_makeValue.makeFormatedValue1(this, format, value, key,
                                    replaceOnBlank, replaceOnErrorFormat);
                    } else {
                        makedValue = util_makeValue.makeFormatedValue1(this, format, value, key, replaceOnBlank,
                                replaceOnErrorFormat);
                    }
                } else {
                    if (delegated != null) {
                        makedValue = util_makeValue.makeValue1(delegated, value, key);
                        if (makedValue == null)
                            makedValue = util_makeValue.makeValue1(this, value, key);
                    } else {
                        makedValue = util_makeValue.makeValue1(this, value, key);
                    }
                }
                setCampoValueWithPoint(key, makedValue);
            } catch (Exception e) {
                try {
                    Object makedValue = null;
                    if (format != null) {
                        if (delegated != null) {
                            makedValue = util_makeValue.makeFormatedValue(delegated, format, value,
                                    getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                            if (makedValue == null)
                                makedValue = util_makeValue.makeFormatedValue(this, format, value,
                                        getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                        } else {
                            makedValue = util_makeValue.makeFormatedValue(this, format, value,
                                    getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                        }
                    } else
                        makedValue = util_makeValue.makeValue(value, getCampoValue(key));
                    setCampoValueWithPoint(key, makedValue);
                } catch (Exception ex) {
                    if (parametersFly == null)
                        parametersFly = new HashMap();
                    if (key != null && key.length() > 0 && key.indexOf(0) != '$')
                        parametersFly.put(key, value);
                }
            }
        } else {

            Object writeValue = null;
            Object current_requested = (delegated == null) ? this : delegated;

            String last_field_name = null;
            StringTokenizer st = new StringTokenizer(key, ".");
            while (st.hasMoreTokens()) {
                if (st.countTokens() > 1) {
                    String current_field_name = st.nextToken();
                    try {
                        if (writeValue == null && current_requested instanceof HashMap)
                            writeValue = ((HashMap) current_requested).get(current_field_name);
                        if (writeValue == null)
                            writeValue = util_reflect.getValue(current_requested,
                                    "get" + util_reflect.adaptMethodName(current_field_name), null);
                        if (writeValue == null)
                            writeValue = util_reflect.getValue(current_requested, current_field_name, null);
                        if (writeValue == null && current_requested instanceof i_bean)
                            writeValue = ((i_bean) current_requested).get(current_field_name);
                    } catch (Exception e) {
                    }
                    current_requested = writeValue;
                } else {
                    last_field_name = st.nextToken();
                }
                writeValue = null;
            }

            if (current_requested != null) {
                try {
                    if (format != null)
                        setCampoValuePoint(current_requested, last_field_name,
                                util_makeValue.makeFormatedValue1(current_requested, format, value,
                                        last_field_name, replaceOnBlank, replaceOnErrorFormat));
                    else
                        setCampoValuePoint(current_requested, last_field_name,
                                util_makeValue.makeValue1(current_requested, value, last_field_name));
                } catch (Exception e) {
                    try {
                        if (format != null)
                            setCampoValuePoint(current_requested, key,
                                    util_makeValue.makeFormatedValue((delegated == null) ? this : delegated,
                                            format, value, getCampoValue(key), replaceOnBlank,
                                            replaceOnErrorFormat));
                        else
                            setCampoValuePoint(current_requested, key,
                                    util_makeValue.makeValue(value, getCampoValue(key)));
                    } catch (Exception ex) {
                    }
                }
            }

        }
    }
}

From source file:com.impetus.client.oraclenosql.OracleNoSQLClient.java

/**
 * On index search./*  w ww  .  j  a v  a2s .c o  m*/
 * 
 * @param <E>
 *            the element type
 * @param interpreter
 *            the interpreter
 * @param entityMetadata
 *            the entity metadata
 * @param metamodel
 *            the metamodel
 * @param results
 *            the results
 * @param columnsToSelect
 *            the columns to select
 * @return the list
 */
private <E> List<E> onIndexSearch(OracleNoSQLQueryInterpreter interpreter, EntityMetadata entityMetadata,
        MetamodelImpl metamodel, List<E> results, List<String> columnsToSelect) {
    Map<String, List> indexes = new HashMap<String, List>();
    StringBuilder indexNamebuilder = new StringBuilder();

    for (Object clause : interpreter.getClauseQueue()) {
        if (clause.getClass().isAssignableFrom(FilterClause.class)) {
            String fieldName = null;

            String clauseName = ((FilterClause) clause).getProperty();
            StringTokenizer stringTokenizer = new StringTokenizer(clauseName, ".");
            // if need to select embedded columns
            if (stringTokenizer.countTokens() > 1) {
                fieldName = stringTokenizer.nextToken();
            }

            fieldName = stringTokenizer.nextToken();
            Object value = ((FilterClause) clause).getValue();
            if (!indexes.containsKey(fieldName)) {
                indexNamebuilder.append(fieldName);
                indexNamebuilder.append(",");
            }
            indexes.put(fieldName, (List) value);
        } else {
            if (clause.toString().equalsIgnoreCase("OR")) {
                throw new QueryHandlerException("OR clause is not supported with oracle nosql db");
            }
        }
    }

    // prepare index name and value.
    Table schemaTable = tableAPI.getTable(entityMetadata.getTableName());
    String indexKeyName = indexNamebuilder.deleteCharAt(indexNamebuilder.length() - 1).toString();
    Index index = schemaTable.getIndex(entityMetadata.getIndexProperties().get(indexKeyName).getName());
    IndexKey indexKey = index.createIndexKey();

    // StringBuilder indexNamebuilder = new StringBuilder();
    for (String indexName : indexes.keySet()) {
        NoSqlDBUtils.add(schemaTable.getField(indexName), indexKey, indexes.get(indexName).get(0), indexName);
    }

    Iterator<Row> rowsIter = tableAPI.tableIterator(indexKey, null, null);

    Map<String, Object> relationMap = initialize(entityMetadata);

    try {
        results = scrollAndPopulate(null, entityMetadata, metamodel, schemaTable, rowsIter, relationMap,
                columnsToSelect);
        KunderaCoreUtils.printQueryWithFilterClause(interpreter.getClauseQueue(),
                entityMetadata.getTableName());
    } catch (Exception e) {
        log.error("Error while finding records , Caused By :" + e + ".");
        throw new PersistenceException(e);
    }

    return results;
}

From source file:com.stratelia.silverpeas.versioningPeas.servlets.VersioningRequestRouter.java

@Override
public String getDestination(String function, VersioningSessionController versioningSC,
        HttpServletRequest request) {/*ww  w  .  j a  va 2 s  .  c  om*/
    String destination = "";
    SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
            "User=" + versioningSC.getUserId() + " Function=" + function);
    String rootDestination = "/versioningPeas/jsp/";
    ResourceLocator messages = new ResourceLocator(
            "com.stratelia.silverpeas.versioningPeas.multilang.versioning", versioningSC.getLanguage());
    try {
        String flag = versioningSC.getProfile();

        request.setAttribute("Profile", flag);
        if (function.startsWith("ViewReadersList")) {
            List<Group> groups = new ArrayList<Group>();
            List<String> users = new ArrayList<String>();
            ProfileInst profile = versioningSC.getCurrentProfile(VersioningSessionController.READER);
            if (profile != null) {
                groups = versioningSC.groupIds2Groups(profile.getAllGroups());
                users = versioningSC.userIds2Users(profile.getAllUsers());
            }
            request.setAttribute("Groups", groups);
            request.setAttribute("Users", users);
            destination = rootDestination + "ReadList.jsp";
        } else if (function.startsWith("ViewWritersList")) {
            Document document = versioningSC.getEditingDocument();

            ProfileInst profile = versioningSC.getCurrentProfile(VersioningSessionController.WRITER);
            ArrayList<Worker> workers = new ArrayList<Worker>();
            if (profile != null) {
                workers = document.getWorkList();
                if (document.getCurrentWorkListOrder() == Integer
                        .parseInt(VersioningSessionController.WRITERS_LIST_ORDERED)
                        && !versioningSC.isAlreadyMerged() && !profile.getAllGroups().isEmpty()) {
                    // Need to merge users from groups with other users
                    workers = versioningSC.mergeUsersFromGroupsWithWorkers(profile.getAllGroups(), workers);
                }
            }
            request.setAttribute("Workers", workers);
            destination = rootDestination + "WorkList.jsp";
        } else if (function.startsWith("ChangeOrder")) {
            String lines = request.getParameter("lines");
            Document document = versioningSC.getEditingDocument();
            ArrayList<Worker> users = document.getWorkList();
            if (lines != null) {
                int users_count = Integer.parseInt(lines);
                if (users_count == users.size()) {
                    ArrayList<Worker> new_users = new ArrayList<Worker>(users_count);

                    for (int i = 0; i < users_count; i++) {
                        Worker user = users.get(i);
                        boolean v_value = false;

                        // Validator
                        String chvi = request.getParameter("chv" + i);
                        if (chvi != null) {
                            v_value = true;
                        }
                        user.setApproval(v_value);
                        new_users.add(user);
                    }

                    // Sorting begin
                    int upIndex = Integer.parseInt(request.getParameter("up"));
                    int downIndex = Integer.parseInt(request.getParameter("down"));
                    int addIndex = Integer.parseInt(request.getParameter("add"));

                    // Remove user to change order
                    if (upIndex > 0 && upIndex < users_count) {
                        Worker user = new_users.remove(upIndex);
                        new_users.add(upIndex - 1, user);
                    }
                    if (downIndex >= 0 && downIndex < users_count - 1) {
                        Worker user = new_users.remove(downIndex);
                        new_users.add(downIndex + 1, user);
                    }

                    if (addIndex >= 0 && addIndex < users_count) {
                        Worker user = new_users.get(addIndex);
                        Worker new_user = new Worker(user.getUserId(),
                                Integer.parseInt(versioningSC.getEditingDocument().getPk().getId()), 0,
                                user.isApproval(), true, versioningSC.getComponentId(), user.getType(),
                                user.isSaved(), user.isUsed(), user.getListType());
                        new_users.add(addIndex + 1, new_user);
                        users_count++;
                    }

                    for (int i = 0; i < users_count; i++) {
                        new_users.get(i).setOrder(i);
                    }
                    document.setWorkList(new_users);
                }
            }
            destination = getDestination("ViewWritersList", versioningSC, request);
        } else if (function.startsWith("ChangeListType")) {
            Document document = versioningSC.getEditingDocument();
            String listType = request.getParameter("ListType");
            if (!StringUtil.isDefined(listType)) {
                listType = VersioningSessionController.WRITERS_LIST_SIMPLE;
            }
            document.setCurrentWorkListOrder(Integer.parseInt(listType));
            ProfileInst profile = versioningSC.getProfile(VersioningSessionController.WRITER);
            ArrayList<Worker> workers = new ArrayList<Worker>();
            if (profile != null) {
                if (listType.equals(VersioningSessionController.WRITERS_LIST_ORDERED)) {
                    // Need to merge users from groups with other users
                    workers = document.getWorkList();
                    workers = versioningSC.mergeUsersFromGroupsWithWorkers(profile.getAllGroups(), workers);
                    versioningSC.setAlreadyMerged(true);
                } else {
                    ArrayList<Worker> workersUsers = new ArrayList<Worker>();
                    ArrayList<Worker> workersGroups = new ArrayList<Worker>();

                    workersGroups = versioningSC.convertGroupsToWorkers(workers, profile.getAllGroups());
                    workers.addAll(workersGroups);

                    workersUsers = versioningSC.convertUsersToWorkers(workers, profile.getAllUsers());
                    workers.addAll(workersUsers);
                }
            }
            document.setWorkList(workers);
            versioningSC.updateWorkList(document);
            versioningSC.updateDocument(document);
            destination = getDestination("ViewWritersList", versioningSC, request);
        } else if (function.startsWith("SaveListType")) {
            Document document = versioningSC.getEditingDocument();
            ArrayList<Worker> users = document.getWorkList();
            ArrayList<Worker> updateUsers = new ArrayList<Worker>();
            for (int i = 0; i < users.size(); i++) {
                Worker user = users.get(i);
                // Set approval rights to users
                String chvi = request.getParameter("chv" + i);
                boolean v_value = false;
                if (chvi != null) {
                    v_value = true;
                }
                user.setApproval(v_value);
                updateUsers.add(user);
            }
            versioningSC.updateWorkList(document);
            versioningSC.updateDocument(document);
            destination = getDestination("ViewWritersList", versioningSC, request);
        } else if (function.startsWith("ViewVersions")) {
            request.setAttribute("Document", versioningSC.getEditingDocument());
            destination = rootDestination + "versions.jsp";
        } else if (function.equals("SelectUsersGroupsProfileInstance")) {
            String role = request.getParameter("Role");
            String listType = request.getParameter("ListType");
            if (StringUtil.isDefined(listType)) {
                versioningSC.getEditingDocument().setCurrentWorkListOrder(Integer.parseInt(listType));
            }
            versioningSC.initUserPanelInstanceForGroupsUsers(role);
            destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS);
        } else if (function.startsWith("DocumentProfileSetUsersAndGroups")) {
            String role = request.getParameter("Role");
            ProfileInst profile = versioningSC.getProfile(role);
            versioningSC.updateDocumentProfile(profile);
            if (role.equals(VersioningSessionController.WRITER)) {

                ArrayList<Worker> oldWorkers = versioningSC.getEditingDocument().getWorkList();
                ArrayList<Worker> workers = new ArrayList<Worker>();
                ArrayList<Worker> workersUsers = new ArrayList<Worker>();
                ArrayList<Worker> workersGroups = new ArrayList<Worker>();

                workersGroups = versioningSC.convertGroupsToWorkers(oldWorkers, profile.getAllGroups());
                workers.addAll(workersGroups);

                workersUsers = versioningSC.convertUsersToWorkers(oldWorkers, profile.getAllUsers());
                workers.addAll(workersUsers);
                ArrayList<Worker> sortedWorkers = new ArrayList<Worker>();
                if (workers != null) {
                    for (int i = 0; i < workers.size(); i++) {
                        Worker sortedWorker = workers.get(i);
                        sortedWorker.setOrder(i);
                        sortedWorkers.add(sortedWorker);
                    }
                    workers = sortedWorkers;
                }

                versioningSC.getEditingDocument().setWorkList(workers);
                versioningSC.updateWorkList(versioningSC.getEditingDocument());
                request.setAttribute("urlToReload", "ViewWritersList");
            } else {
                request.setAttribute("urlToReload", "ViewReadersList");
            }
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.startsWith("SaveList")) {
            String role = request.getParameter("Role");
            String fromFunction = request.getParameter("From");
            if (versioningSC.isAccessListExist(role)) {
                versioningSC.removeAccessList(role);
            }
            versioningSC.saveAccessList(role);
            request.setAttribute("Message", messages.getString("versioning.ListSaved", ""));
            destination = getDestination(fromFunction, versioningSC, request);
        } else if (function.startsWith("DeleteReaderProfile")) {
            ProfileInst profile = versioningSC.getDocumentProfile(VersioningSessionController.READER);
            if (profile != null) {
                profile.removeAllGroups();
                profile.removeAllUsers();
                versioningSC.updateProfileInst(profile);
            }
            destination = getDestination("ViewReadersList", versioningSC, request);
        } else if (function.startsWith("DeleteWriterProfile")) {
            ProfileInst profile = versioningSC.getDocumentProfile(VersioningSessionController.WRITER);
            if (profile != null) {
                profile.removeAllGroups();
                profile.removeAllUsers();
                versioningSC.updateProfileInst(profile);
            }
            versioningSC.deleteWorkers(true);
            versioningSC.setAlreadyMerged(false);
            destination = getDestination("ViewWritersList", versioningSC, request);
        } else if (function.startsWith("Update")) {
            String docId = request.getParameter("DocId");
            String name = request.getParameter("name");
            String description = request.getParameter("description");
            String comments = request.getParameter("comments");
            Document document = versioningSC
                    .getDocument(new DocumentPK(Integer.parseInt(docId), versioningSC.getComponentId()));
            document.setDescription(description);
            document.setName(name);
            document.setAdditionalInfo(comments);
            versioningSC.updateDocument(document);
            versioningSC.setEditingDocument(document);
            destination = getDestination("ViewVersions", versioningSC, request);
        } else if (function.equals("CloseWindow")) {
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.equals("AddNewVersion")) {

            // Display xmlForm if used
            if (StringUtil.isDefined(versioningSC.getXmlForm())) {
                setXMLFormIntoRequest(request.getParameter("documentId"), versioningSC, request);
            }

            destination = rootDestination + "newVersion.jsp";
        } else if (function.equals("AddNewOnlineVersion")) {
            String documentId = request.getParameter("documentId");

            request.setAttribute("DocumentId", documentId);
            // Display xmlForm if used
            if (StringUtil.isDefined(versioningSC.getXmlForm())) {
                setXMLFormIntoRequest(documentId, versioningSC, request);
            }

            destination = rootDestination + "newOnlineVersion.jsp";
        } else if (function.equals("ChangeValidator")) {
            String setTypeId = request.getParameter("VV");
            String setType = request.getParameter("SetType"); // 'U'for users or 'G'
            // for groups
            versioningSC.setWorkerValidator(versioningSC.getEditingDocument().getWorkList(),
                    Integer.parseInt(setTypeId), setType);
            destination = getDestination("ViewWritersList", versioningSC, request);
        } else if (function.equals("ListPublicVersionsOfDocument")) {
            String documentId = request.getParameter("DocId");
            String isAlias = request.getParameter("Alias");
            DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(),
                    versioningSC.getComponentId());

            Document document = versioningSC.getDocument(documentPK);
            List<DocumentVersion> publicVersions = versioningSC.getPublicDocumentVersions(documentPK);

            request.setAttribute("Document", document);
            request.setAttribute("PublicVersions", publicVersions);
            request.setAttribute("Alias", isAlias);
            destination = "/versioningPeas/jsp/publicVersions.jsp";
        } else if ("ViewAllVersions".equals(function)) {
            return viewVersions(request, versioningSC);
        } else if ("saveOnline".equals(function)) {
            if (!StringUtil.isDefined(request.getCharacterEncoding())) {
                request.setCharacterEncoding("UTF-8");
            }
            String encoding = request.getCharacterEncoding();
            List<FileItem> items = FileUploadUtil.parseRequest(request);

            String documentId = FileUploadUtil.getParameter(items, "documentId", "-1", encoding);
            DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(),
                    versioningSC.getComponentId());
            Document document = versioningSC.getDocument(documentPK);
            String userId = versioningSC.getUserId();
            String radio = FileUploadUtil.getParameter(items, "radio", "", encoding);
            String comments = FileUploadUtil.getParameter(items, "comments", "", encoding);
            boolean force = "true".equalsIgnoreCase(request.getParameter("force_release"));

            String callback = FileUploadUtil.getParameter(items, "Callback");
            request.setAttribute("Callback", callback);
            destination = "/versioningPeas/jsp/documentSaved.jsp";

            boolean addXmlForm = !isXMLFormEmpty(versioningSC, items);

            DocumentVersionPK newVersionPK = versioningSC.saveOnline(document, comments, radio,
                    Integer.parseInt(userId), force, addXmlForm);
            if (newVersionPK != null) {
                request.setAttribute("DocumentId", documentId);
                DocumentVersion version = versioningSC.getLastVersion(documentPK);
                request.setAttribute("Version", version);
                if (addXmlForm) {
                    saveXMLData(versioningSC, newVersionPK, items);
                }
            } else {
                if ("admin".equals(versioningSC.getUserRoleLevel())) {
                    // TODO MANU ecrire la page pour ressoumettre en forcant
                    destination = "/versioningPeas/jsp/forceDocumentLocked.jsp";
                } else {
                    destination = "/versioningPeas/jsp/documentLocked.jsp";
                }
            }
        } else if ("Checkout".equals(function)) {
            String documentId = request.getParameter("DocId");
            DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(),
                    versioningSC.getComponentId());
            Document document = versioningSC.getDocument(documentPK);
            document.setStatus(1);
            document.setLastCheckOutDate(new Date());
            versioningSC.checkDocumentOut(documentPK, Integer.parseInt(versioningSC.getUserId()), new Date());
            document = versioningSC.getDocument(documentPK);
            versioningSC.setEditingDocument(document);
            request.setAttribute("Document", document);
            destination = rootDestination + "versions.jsp";
        } else if ("DeleteDocumentRequest".equals(function)) {
            String documentId = request.getParameter("DocId");
            String url = request.getParameter("Url");
            request.setAttribute("DocId", documentId);
            request.setAttribute("Url", url);
            destination = rootDestination + "deleteDocument.jsp";
        } else if (function.equals("DeleteDocument")) {
            String documentId = request.getParameter("DocId");
            String url = request.getParameter("Url");
            DocumentPK documentPK = new DocumentPK(Integer.parseInt(documentId), versioningSC.getSpaceId(),
                    versioningSC.getComponentId());
            versioningSC.deleteDocument(documentPK);
            SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()",
                    "root.MSG_GEN_PARAM_VALUE", "url=" + url);
            request.setAttribute("urlToReload", url);
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.equals("AddNewDocument")) {
            String pubId = request.getParameter("PubId");
            request.setAttribute("PubId", pubId);

            if (StringUtil.isDefined(versioningSC.getXmlForm())) {
                setXMLFormIntoRequest(null, versioningSC, request);
            }

            destination = rootDestination + "newDocument.jsp";
        } else if (function.equals("SaveNewDocument")) {
            saveNewDocument(request, versioningSC);
            destination = getDestination("ViewVersions", versioningSC, request);
        } else if (function.equals("SaveNewVersion")) {
            if (!StringUtil.isDefined(request.getCharacterEncoding())) {
                request.setCharacterEncoding("UTF-8");
            }
            String encoding = request.getCharacterEncoding();
            List<FileItem> items = FileUploadUtil.parseRequest(request);

            String type = FileUploadUtil.getParameter(items, "type", "", encoding);
            String comments = FileUploadUtil.getParameter(items, "comments", "", encoding);
            String radio = FileUploadUtil.getParameter(items, "radio", "", encoding);
            String documentId = FileUploadUtil.getParameter(items, "documentId", "-1", encoding);

            // Save file on disk
            FileItem fileItem = FileUploadUtil.getFile(items, "file_upload");
            boolean runOnUnix = !FileUtil.isWindows();
            String logicalName = fileItem.getName();
            String physicalName = "dummy";
            String mimeType = "dummy";
            File dir = null;
            int size = 0;
            if (logicalName != null) {

                if (runOnUnix) {
                    logicalName = logicalName.replace('\\', File.separatorChar);
                }

                logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1,
                        logicalName.length());
                type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length());
                physicalName = new Long(new Date().getTime()).toString() + "." + type;
                mimeType = FileUtil.getMimeType(logicalName);
                if (!StringUtil.isDefined(mimeType)) {
                    mimeType = "unknown";
                }
                dir = new File(versioningSC.createPath(versioningSC.getComponentId(), null) + physicalName);
                size = new Long(fileItem.getSize()).intValue();
                fileItem.write(dir);
            }

            // create DocumentVersion
            String componentId = versioningSC.getComponentId();
            DocumentPK docPK = new DocumentPK(Integer.parseInt(documentId), "useless", componentId);
            int userId = Integer.parseInt(versioningSC.getUserId());

            DocumentVersion documentVersion = null;
            DocumentVersion lastVersion = versioningSC.getLastVersion(docPK);
            if (com.stratelia.silverpeas.versioning.ejb.RepositoryHelper.getJcrDocumentService()
                    .isNodeLocked(lastVersion)) {
                destination = rootDestination + "documentLocked.jsp";
            } else {

                List<DocumentVersion> versions = versioningSC.getDocumentVersions(docPK);
                int majorNumber = 0;
                int minorNumber = 1;
                if (versions != null && versions.size() > 0) {
                    documentVersion = versions.get(0);
                    majorNumber = documentVersion.getMajorNumber();
                    minorNumber = documentVersion.getMinorNumber();
                    DocumentVersion newVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber,
                            userId, new Date(), comments, Integer.parseInt(radio), documentVersion.getStatus(),
                            physicalName, logicalName, mimeType, size, componentId);

                    boolean addXmlForm = !isXMLFormEmpty(versioningSC, items);
                    if (addXmlForm) {
                        newVersion.setXmlForm(versioningSC.getXmlForm());
                    }

                    newVersion = versioningSC.addNewDocumentVersion(newVersion);
                    ResourceLocator settings = new ResourceLocator(
                            "com.stratelia.webactiv.util.attachment.Attachment", "");
                    boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false);
                    // Specific case: 3d file to convert by Actify Publisher
                    if (actifyPublisherEnable) {
                        String extensions = settings.getString("Actify3dFiles");
                        StringTokenizer tokenizer = new StringTokenizer(extensions, ",");
                        // 3d native file ?
                        boolean fileForActify = false;
                        SilverTrace.info("versioningPeas", "saveFile.jsp", "root.MSG_GEN_PARAM_VALUE",
                                "nb tokenizer =" + tokenizer.countTokens());
                        while (tokenizer.hasMoreTokens() && !fileForActify) {
                            String extension = tokenizer.nextToken();
                            if (type.equalsIgnoreCase(extension)) {
                                fileForActify = true;
                            }
                        }
                        if (fileForActify) {
                            String dirDestName = "v_" + componentId + "_" + documentId;
                            String actifyWorkingPath = settings.getString("ActifyPathSource") + File.separator
                                    + dirDestName;

                            String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath;
                            if (!new File(destPath).exists()) {
                                FileRepositoryManager.createGlobalTempPath(actifyWorkingPath);
                            }

                            String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath
                                    + File.separator + logicalName;
                            FileRepositoryManager.copyFile(
                                    versioningSC.createPath(componentId, null) + File.separator + physicalName,
                                    destFile);
                        }
                    }
                    if (addXmlForm) {
                        saveXMLData(versioningSC, newVersion.getPk(), items);
                    }
                }

                String returnURL = FileUploadUtil.getParameter(items, "ReturnURL");
                if (!StringUtil.isDefined(returnURL)) {
                    destination = getDestination("ViewVersions", versioningSC, request);
                } else {
                    request.setAttribute("urlToReload", returnURL);
                    destination = rootDestination + "closeWindow.jsp";
                }
            }
        } else {
            destination = rootDestination + function;
        }
    } catch (Exception e) {
        SilverTrace.error("versioning", "VersioningRequestRouter.getDestination",
                "root.EX_CANT_GET_REQUEST_DESTINATION", e);
        request.setAttribute("javax.servlet.jsp.jspException", e);
        destination = "/admin/jsp/errorpageMain.jsp";
    }
    SilverTrace.info("versioningPeas", "VersioningRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
            "Destination=" + destination);
    return destination;
}

From source file:it.classhidra.core.controller.bean.java

public void init(HashMap _content) throws bsControllerException {
    if (_content == null)
        return;/* ww  w .ja  v a 2 s  .co m*/

    xmloutput = false;
    jsonoutput = false;
    boolean inputBase64 = (_content.get(bsController.CONST_ID_INPUTBASE64) != null
            && (_content.get(bsController.CONST_ID_INPUTBASE64).toString().equalsIgnoreCase("true")
                    || _content.get(bsController.CONST_ID_INPUTBASE64).toString()
                            .equalsIgnoreCase(Base64.encodeBase64String("true".getBytes()))));

    //   Object[] keys = _content.keySet().toArray();
    //   for (int ii = 0; ii < keys.length; ii++){
    for (Object elem : _content.keySet()) {
        String key = (String) elem;

        //      String key = (String)keys[ii];
        String value = (String) _content.get(key);
        String format = (String) _content.get("$format_" + key);
        String replaceOnBlank = (String) _content.get("$replaceOnBlank_" + key);
        String replaceOnErrorFormat = (String) _content.get("$replaceOnErrorFormat_" + key);

        if (inputBase64) {
            String charset = (_content.get("$REQUEST_CHARSET") == null
                    || _content.get("$REQUEST_CHARSET").toString().equals("")) ? "UTF-8"
                            : _content.get("$REQUEST_CHARSET").toString();

            try {
                if (value != null)
                    value = new String(Base64.decodeBase64(value), charset);
            } catch (Exception e) {
            }
            try {
                if (format != null)
                    format = new String(Base64.decodeBase64(format), charset);
            } catch (Exception e) {
            }
            try {
                if (replaceOnBlank != null)
                    replaceOnBlank = new String(Base64.decodeBase64(replaceOnBlank), charset);
            } catch (Exception e) {
            }
            try {
                if (replaceOnErrorFormat != null)
                    replaceOnErrorFormat = new String(Base64.decodeBase64(replaceOnErrorFormat), charset);
            } catch (Exception e) {
            }
        }

        if (key.indexOf(".") == -1) {
            try {

                Object makedValue = null;
                if (format != null) {
                    if (delegated != null) {
                        makedValue = util_makeValue.makeFormatedValue1(delegated, format, value, key,
                                replaceOnBlank, replaceOnErrorFormat);
                        if (makedValue == null)
                            makedValue = util_makeValue.makeFormatedValue1(this, format, value, key,
                                    replaceOnBlank, replaceOnErrorFormat);
                    } else {
                        makedValue = util_makeValue.makeFormatedValue1(this, format, value, key, replaceOnBlank,
                                replaceOnErrorFormat);
                    }
                } else {
                    if (delegated != null) {
                        makedValue = util_makeValue.makeValue1(delegated, value, key);
                        if (makedValue == null)
                            makedValue = util_makeValue.makeValue1(this, value, key);
                    } else {
                        makedValue = util_makeValue.makeValue1(this, value, key);
                    }
                }
                setCampoValueWithPoint(key, makedValue);
            } catch (Exception e) {
                try {
                    Object makedValue = null;

                    if (format != null) {
                        if (delegated != null) {
                            makedValue = util_makeValue.makeFormatedValue(delegated, format, value,
                                    getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                            if (makedValue == null)
                                makedValue = util_makeValue.makeFormatedValue(this, format, value,
                                        getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                        } else {
                            makedValue = util_makeValue.makeFormatedValue(this, format, value,
                                    getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                        }
                    } else
                        makedValue = util_makeValue.makeValue(value, getCampoValue(key));

                    setCampoValueWithPoint(key, makedValue);
                } catch (Exception ex) {
                    if (parametersFly == null)
                        parametersFly = new HashMap();
                    if (key != null && key.length() > 0 && key.indexOf(0) != '$')
                        parametersFly.put(key, value);
                }
            }
        } else {
            Object writeValue = null;
            Object current_requested = (delegated == null) ? this : delegated;

            String last_field_name = null;
            StringTokenizer st = new StringTokenizer(key, ".");
            while (st.hasMoreTokens()) {
                if (st.countTokens() > 1) {
                    String current_field_name = st.nextToken();
                    try {
                        writeValue = util_reflect.getValue(current_requested,
                                "get" + util_reflect.adaptMethodName(current_field_name), null);
                        if (writeValue == null)
                            writeValue = util_reflect.getValue(current_requested, current_field_name, null);
                        if (writeValue == null && current_requested instanceof HashMap) {
                            writeValue = ((HashMap) current_requested).get(current_field_name);
                        }
                    } catch (Exception e) {
                    }
                    current_requested = writeValue;
                } else {
                    last_field_name = st.nextToken();
                }
                writeValue = null;
            }

            if (current_requested != null) {
                try {
                    if (format != null)
                        setCampoValuePoint(current_requested, last_field_name,
                                util_makeValue.makeFormatedValue1(current_requested, format, value,
                                        last_field_name, replaceOnBlank, replaceOnErrorFormat));
                    else
                        setCampoValuePoint(current_requested, last_field_name,
                                util_makeValue.makeValue1(current_requested, value, last_field_name));
                } catch (Exception e) {
                    try {
                        if (format != null)
                            setCampoValuePoint(current_requested, key,
                                    util_makeValue.makeFormatedValue((delegated == null) ? this : delegated,
                                            format, value, getCampoValue(key), replaceOnBlank,
                                            replaceOnErrorFormat));
                        else
                            setCampoValuePoint(current_requested, key,
                                    util_makeValue.makeValue(value, getCampoValue(key)));
                    } catch (Exception ex) {
                    }
                }
            }
        }

    }
}

From source file:it.classhidra.core.controller.bean.java

private void initPartFromMap(HashMap parameters) throws bsControllerException {
    if (parameters == null)
        parameters = new HashMap();
    parametersMP = parameters;//w ww.ja  v  a  2  s.c  om

    xmloutput = false;
    jsonoutput = false;
    boolean inputBase64 = (parameters.get(bsController.CONST_ID_INPUTBASE64) != null
            && (parameters.get(bsController.CONST_ID_INPUTBASE64).toString().equalsIgnoreCase("true")
                    || parameters.get(bsController.CONST_ID_INPUTBASE64).toString()
                            .equalsIgnoreCase(Base64.encodeBase64String("true".getBytes()))));

    //      Vector en = new Vector(parameters.keySet());
    //      for(int k=0;k<parameters.keySet().size();k++){
    for (Object elem : parameters.keySet()) {
        String key = (String) elem;

        if (parameters.get(key) instanceof String) {
            String value = (String) parameters.get(key);
            String format = (String) parameters.get("$format_" + key);
            String replaceOnBlank = (String) parameters.get("$replaceOnBlank_" + key);
            String replaceOnErrorFormat = (String) parameters.get("$replaceOnErrorFormat_" + key);

            if (inputBase64) {
                String charset = (parameters.get("$REQUEST_CHARSET") == null
                        || parameters.get("$REQUEST_CHARSET").toString().equals("")) ? "UTF-8"
                                : parameters.get("$REQUEST_CHARSET").toString();

                try {
                    if (value != null)
                        value = new String(Base64.decodeBase64(value), charset);
                } catch (Exception e) {
                }
                try {
                    if (format != null)
                        format = new String(Base64.decodeBase64(format), charset);
                } catch (Exception e) {
                }
                try {
                    if (replaceOnBlank != null)
                        replaceOnBlank = new String(Base64.decodeBase64(replaceOnBlank), charset);
                } catch (Exception e) {
                }
                try {
                    if (replaceOnErrorFormat != null)
                        replaceOnErrorFormat = new String(Base64.decodeBase64(replaceOnErrorFormat), charset);
                } catch (Exception e) {
                }
            }

            if (key.indexOf(".") == -1) {
                try {
                    Object makedValue = null;
                    if (format != null) {
                        if (delegated != null) {
                            makedValue = util_makeValue.makeFormatedValue1(delegated, format, value, key,
                                    replaceOnBlank, replaceOnErrorFormat);
                            if (makedValue == null)
                                makedValue = util_makeValue.makeFormatedValue1(this, format, value, key,
                                        replaceOnBlank, replaceOnErrorFormat);
                        } else {
                            makedValue = util_makeValue.makeFormatedValue1(this, format, value, key,
                                    replaceOnBlank, replaceOnErrorFormat);
                        }
                    } else {
                        if (delegated != null) {
                            makedValue = util_makeValue.makeValue1(delegated, value, key);
                            if (makedValue == null)
                                makedValue = util_makeValue.makeValue1(this, value, key);
                        } else {
                            makedValue = util_makeValue.makeValue1(this, value, key);
                        }
                    }
                    setCampoValueWithPoint(key, makedValue);
                } catch (Exception e) {
                    try {
                        Object makedValue = null;

                        if (format != null) {
                            if (delegated != null) {
                                makedValue = util_makeValue.makeFormatedValue(delegated, format, value,
                                        getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                                if (makedValue == null)
                                    makedValue = util_makeValue.makeFormatedValue(this, format, value,
                                            getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                            } else {
                                makedValue = util_makeValue.makeFormatedValue(this, format, value,
                                        getCampoValue(key), replaceOnBlank, replaceOnErrorFormat);
                            }
                        } else
                            makedValue = util_makeValue.makeValue(value, getCampoValue(key));

                        setCampoValueWithPoint(key, makedValue);
                    } catch (Exception ex) {
                        if (parametersFly == null)
                            parametersFly = new HashMap();
                        if (key != null && key.length() > 0 && key.indexOf(0) != '$')
                            parametersFly.put(key, value);
                    }
                }

            } else {
                Object writeValue = null;
                Object current_requested = (delegated == null) ? this : delegated;

                String last_field_name = null;
                StringTokenizer st = new StringTokenizer(key, ".");
                while (st.hasMoreTokens()) {
                    if (st.countTokens() > 1) {
                        String current_field_name = st.nextToken();
                        try {
                            writeValue = util_reflect.getValue(current_requested,
                                    "get" + util_reflect.adaptMethodName(current_field_name), null);
                            if (writeValue == null)
                                writeValue = util_reflect.getValue(current_requested, current_field_name, null);
                            if (writeValue == null && current_requested instanceof i_bean)
                                writeValue = ((i_bean) current_requested).get(current_field_name);
                            if (writeValue == null && current_requested instanceof HashMap)
                                writeValue = ((HashMap) current_requested).get(current_field_name);
                        } catch (Exception e) {
                        }
                        current_requested = writeValue;
                    } else {
                        last_field_name = st.nextToken();
                    }
                    writeValue = null;
                }

                if (current_requested != null) {
                    try {
                        if (format != null)
                            setCampoValuePoint(current_requested, last_field_name,
                                    util_makeValue.makeFormatedValue1(current_requested, format, value,
                                            last_field_name, replaceOnBlank, replaceOnErrorFormat));
                        else
                            setCampoValuePoint(current_requested, last_field_name,
                                    util_makeValue.makeValue1(current_requested, value, last_field_name));
                    } catch (Exception e) {
                        try {
                            if (format != null)
                                setCampoValuePoint(current_requested, key,
                                        util_makeValue.makeFormatedValue((delegated == null) ? this : delegated,
                                                format, value, getCampoValue(key), replaceOnBlank,
                                                replaceOnErrorFormat));
                            else
                                setCampoValuePoint(current_requested, key,
                                        util_makeValue.makeValue(value, getCampoValue(key)));
                        } catch (Exception ex) {
                        }
                    }
                }

            }
        }
    }

}

From source file:net.wastl.webmail.plugins.SendMessage.java

public HTMLDocument handleURL(String suburl, HTTPSession sess1, HTTPRequestHeader head)
        throws WebMailException, ServletException {
    if (sess1 == null) {
        throw new WebMailException(
                "No session was given. If you feel this is incorrect, please contact your system administrator");
    }//from   w  w  w  . ja va 2s  . c om
    WebMailSession session = (WebMailSession) sess1;
    UserData user = session.getUser();
    HTMLDocument content;

    Locale locale = user.getPreferredLocale();

    /* Save message in case there is an error */
    session.storeMessage(head);

    if (head.isContentSet("SEND")) {
        /* The form was submitted, now we will send it ... */
        try {
            MimeMessage msg = new MimeMessage(mailsession);

            Address from[] = new Address[1];
            try {
                /**
                 * Why we need
                 * org.bulbul.util.TranscodeUtil.transcodeThenEncodeByLocale()?
                 *
                 * Because we specify client browser's encoding to UTF-8, IE seems
                 * to send all data encoded in UTF-8. We have to transcode all byte
                 * sequences we received to UTF-8, and next we encode those strings
                 * using MimeUtility.encodeText() depending on user's locale. Since
                 * MimeUtility.encodeText() is used to convert the strings into its
                 * transmission format, finally we can use the strings in the
                 * outgoing e-mail which relies on receiver's email agent to decode
                 * the strings.
                 *
                 * As described in JavaMail document, MimeUtility.encodeText() conforms
                 * to RFC2047 and as a result, we'll get strings like "=?Big5?B......".
                 */
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // from[0]=new InternetAddress(MimeUtility.encodeText(session.getUser().getEmail()),
                //                  MimeUtility.encodeText(session.getUser().getFullName()));
                from[0] = new InternetAddress(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("FROM"), null, locale),
                        TranscodeUtil.transcodeThenEncodeByLocale(session.getUser().getFullName(), null,
                                locale));
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                from[0] = new InternetAddress(head.getContent("FROM"), session.getUser().getFullName());
            }

            StringTokenizer t;
            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("TO")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("TO"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("TO").trim(), ",;");
            }

            /* Check To: field, when empty, throw an exception */
            if (t.countTokens() < 1) {
                throw new MessagingException("The recipient field must not be empty!");
            }
            Address to[] = new Address[t.countTokens()];
            int i = 0;
            while (t.hasMoreTokens()) {
                to[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("CC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("CC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("CC").trim(), ",;");
            }
            Address cc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                cc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            try {
                /**
                 * Since data in session.getUser() is read from file, the encoding
                 * should be default encoding.
                 */
                // t=new StringTokenizer(MimeUtility.encodeText(head.getContent("BCC")).trim(),",");
                t = new StringTokenizer(
                        TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("BCC"), null, locale).trim(),
                        ",");
            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                t = new StringTokenizer(head.getContent("BCC").trim(), ",;");
            }
            Address bcc[] = new Address[t.countTokens()];
            i = 0;
            while (t.hasMoreTokens()) {
                bcc[i] = new InternetAddress(t.nextToken().trim());
                i++;
            }

            session.setSent(false);

            msg.addFrom(from);
            if (to.length > 0) {
                msg.addRecipients(Message.RecipientType.TO, to);
            }
            if (cc.length > 0) {
                msg.addRecipients(Message.RecipientType.CC, cc);
            }
            if (bcc.length > 0) {
                msg.addRecipients(Message.RecipientType.BCC, bcc);
            }
            msg.addHeader("X-Mailer",
                    WebMailServer.getVersion() + ", " + getName() + " plugin v" + getVersion());

            String subject = null;

            if (!head.isContentSet("SUBJECT")) {
                subject = "no subject";
            } else {
                try {
                    // subject=MimeUtility.encodeText(head.getContent("SUBJECT"));
                    subject = TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("SUBJECT"), "ISO8859_1",
                            locale);
                } catch (UnsupportedEncodingException e) {
                    log.warn("Unsupported Encoding while trying to send message: " + e.getMessage());
                    subject = head.getContent("SUBJECT");
                }
            }

            msg.addHeader("Subject", subject);

            if (head.isContentSet("REPLY-TO")) {
                // msg.addHeader("Reply-To",head.getContent("REPLY-TO"));
                msg.addHeader("Reply-To", TranscodeUtil.transcodeThenEncodeByLocale(head.getContent("REPLY-TO"),
                        "ISO8859_1", locale));
            }

            msg.setSentDate(new Date(System.currentTimeMillis()));

            String contnt = head.getContent("BODY");

            //String charset=MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset());
            String charset = "utf-8";

            MimeMultipart cont = new MimeMultipart();
            MimeBodyPart txt = new MimeBodyPart();

            // Transcode to UTF-8
            contnt = new String(contnt.getBytes("ISO8859_1"), "UTF-8");
            // Encode text
            if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                txt.setText(contnt, "Big5");
                txt.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            } else {
                txt.setText(contnt, "utf-8");
                txt.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                txt.setHeader("Content-Transfer-Encoding", "quoted-printable"); // JavaMail defaults to QP?
            }

            /* Add an advertisement if the administrator requested to do so */
            cont.addBodyPart(txt);
            if (store.getConfig("ADVERTISEMENT ATTACH").equals("YES")) {
                MimeBodyPart adv = new MimeBodyPart();
                String file = "";
                if (store.getConfig("ADVERTISEMENT SIGNATURE PATH").startsWith("/")) {
                    file = store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                } else {
                    file = parent.getProperty("webmail.data.path") + System.getProperty("file.separator")
                            + store.getConfig("ADVERTISEMENT SIGNATURE PATH");
                }
                String advcont = "";
                try {
                    BufferedReader fin = new BufferedReader(new FileReader(file));
                    String line = fin.readLine();
                    while (line != null && !line.equals("")) {
                        advcont += line + "\n";
                        line = fin.readLine();
                    }
                    fin.close();
                } catch (IOException ex) {
                }

                /**
                 * Transcode to UTF-8; Since advcont comes from file, we transcode
                 * it from default encoding.
                 */
                // Encode text
                if (locale.getLanguage().equals("zh") && locale.getCountry().equals("TW")) {
                    advcont = new String(advcont.getBytes(), "Big5");
                    adv.setText(advcont, "Big5");
                    adv.setHeader("Content-Type", "text/plain; charset=\"Big5\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                } else {
                    advcont = new String(advcont.getBytes(), "UTF-8");
                    adv.setText(advcont, "utf-8");
                    adv.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
                    adv.setHeader("Content-Transfer-Encoding", "quoted-printable");
                }

                cont.addBodyPart(adv);
            }
            for (String attachmentKey : session.getAttachments().keySet()) {
                ByteStore bs = session.getAttachment(attachmentKey);
                InternetHeaders ih = new InternetHeaders();
                ih.addHeader("Content-Transfer-Encoding", "BASE64");

                PipedInputStream pin = new PipedInputStream();
                PipedOutputStream pout = new PipedOutputStream(pin);

                /* This is used to write to the Pipe asynchronously to avoid blocking */
                StreamConnector sconn = new StreamConnector(pin, (int) (bs.getSize() * 1.6) + 1000);
                BufferedOutputStream encoder = new BufferedOutputStream(MimeUtility.encode(pout, "BASE64"));
                encoder.write(bs.getBytes());
                encoder.flush();
                encoder.close();
                //MimeBodyPart att1=sconn.getResult();
                MimeBodyPart att1 = new MimeBodyPart(ih, sconn.getResult().getBytes());

                if (bs.getDescription() != "") {
                    att1.setDescription(bs.getDescription(), "utf-8");
                }
                /**
                 * As described in FileAttacher.java line #95, now we need to
                 * encode the attachment file name.
                 */
                // att1.setFileName(bs.getName());
                String fileName = bs.getName();
                String localeCharset = getLocaleCharset(locale.getLanguage(), locale.getCountry());
                String encodedFileName = MimeUtility.encodeText(fileName, localeCharset, null);
                if (encodedFileName.equals(fileName)) {
                    att1.addHeader("Content-Type", bs.getContentType());
                    att1.setFileName(fileName);
                } else {
                    att1.addHeader("Content-Type", bs.getContentType() + "; charset=" + localeCharset);
                    encodedFileName = encodedFileName.substring(localeCharset.length() + 5,
                            encodedFileName.length() - 2);
                    encodedFileName = encodedFileName.replace('=', '%');
                    att1.addHeaderLine("Content-Disposition: attachment; filename*=" + localeCharset + "''"
                            + encodedFileName);
                }
                cont.addBodyPart(att1);
            }
            msg.setContent(cont);
            //              }

            msg.saveChanges();

            boolean savesuccess = true;

            msg.setHeader("Message-ID", session.getUserModel().getWorkMessage().getAttribute("msgid"));
            if (session.getUser().wantsSaveSent()) {
                String folderhash = session.getUser().getSentFolder();
                try {
                    Folder folder = session.getFolder(folderhash);
                    Message[] m = new Message[1];
                    m[0] = msg;
                    folder.appendMessages(m);
                } catch (MessagingException e) {
                    savesuccess = false;
                } catch (NullPointerException e) {
                    // Invalid folder:
                    savesuccess = false;
                }
            }

            boolean sendsuccess = false;

            try {
                Transport.send(msg);
                Address sent[] = new Address[to.length + cc.length + bcc.length];
                int c1 = 0;
                int c2 = 0;
                for (c1 = 0; c1 < to.length; c1++) {
                    sent[c1] = to[c1];
                }
                for (c2 = 0; c2 < cc.length; c2++) {
                    sent[c1 + c2] = cc[c2];
                }
                for (int c3 = 0; c3 < bcc.length; c3++) {
                    sent[c1 + c2 + c3] = bcc[c3];
                }
                sendsuccess = true;
                throw new SendFailedException("success", new Exception("success"), sent, null, null);
            } catch (SendFailedException e) {
                session.handleTransportException(e);
            }

            //session.clearMessage();

            content = new XHTMLDocument(session.getModel(),
                    store.getStylesheet("sendresult.xsl", user.getPreferredLocale(), user.getTheme()));
            //              if(sendsuccess) session.clearWork();
        } catch (Exception e) {
            log.error("Could not send messsage", e);
            throw new DocumentNotFoundException("Could not send message. (Reason: " + e.getMessage() + ")");
        }

    } else if (head.isContentSet("ATTACH")) {
        /* Redirect request for attachment (unfortunately HTML forms are not flexible enough to
           have two targets without Javascript) */
        content = parent.getURLHandler().handleURL("/compose/attach", session, head);
    } else {
        throw new DocumentNotFoundException("Could not send message. (Reason: No content given)");
    }
    return content;
}