Example usage for java.lang StringBuffer charAt

List of usage examples for java.lang StringBuffer charAt

Introduction

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

Prototype

@Override
public synchronized char charAt(int index) 

Source Link

Usage

From source file:com.wabacus.system.component.application.report.configbean.crosslist.AbsCrossListReportColAndGroupBean.java

public String[] getSelectColumnsAndOrderbyClause(Map<String, String> mOrderbysInDynColGroupDatasetSql) {
    StringBuffer selectColumnsBuf = new StringBuffer();
    StringBuffer orderbyClauseBuf = null;
    if (getRootCrossColGroupBean() instanceof CrossListReportGroupBean) {
        orderbyClauseBuf = new StringBuffer();
    }/*from  ww  w. ja  v a  2  s.  co  m*/
    this.dynColGroupSpecificBean.getSelectColumnsAndOrderbyClause(selectColumnsBuf, orderbyClauseBuf,
            mOrderbysInDynColGroupDatasetSql);
    if (selectColumnsBuf.charAt(selectColumnsBuf.length() - 1) == ',')
        selectColumnsBuf.deleteCharAt(selectColumnsBuf.length() - 1);
    if (orderbyClauseBuf != null && orderbyClauseBuf.length() > 0
            && orderbyClauseBuf.charAt(orderbyClauseBuf.length() - 1) == ',')
        orderbyClauseBuf.deleteCharAt(orderbyClauseBuf.length() - 1);
    String orderby = "";
    if (orderbyClauseBuf != null)
        orderby = orderbyClauseBuf.toString();
    if (!orderby.trim().equals(""))
        orderby = " order by " + orderby;
    return new String[] { selectColumnsBuf.toString(), orderby };
}

From source file:com.fiorano.openesb.application.application.Route.java

protected void populate(FioranoStaxParser cursor) throws XMLStreamException, FioranoException {
    if (cursor.markCursor(ELEM_ROUTE)) {
        name = cursor.getAttributeValue(null, ATTR_NAME);
        ignoreAbsenceOfTransformation = getBooleanAttribute(cursor, ATTR_IGNORE_ABSENCE_TRANSFORMATION, false);

        if (DmiObject.INVALID_INPUT_CHARS_REGEX.matcher(name).find()) {
            StringBuffer nameBuff = new StringBuffer(name);
            for (int i = 0; i < nameBuff.length(); i++) {
                if (DmiObject.INVALID_INPUT_CHARS_REGEX.matcher(String.valueOf(nameBuff.charAt(i))).find()) {
                    nameBuff.setCharAt(i, '_');
                }/*  w ww . j  a  v a 2s  .  c o  m*/
            }
            name = nameBuff.toString();
        }

        while (cursor.nextElement()) {
            String elemName = cursor.getLocalName();
            if (ELEM_SOURCE.equals(elemName)) {
                sourceServiceInstance = cursor.getAttributeValue(null, ATTR_SOURCE_SERVICE_INSTANCE);
                sourcePortInstance = cursor.getAttributeValue(null, ATTR_SOURCE_PORT_INSTANCE);
            } else if (ELEM_TARGET.equals(elemName)) {
                targetServiceInstance = cursor.getAttributeValue(null, ATTR_SOURCE_SERVICE_INSTANCE);
                targetPortInstance = cursor.getAttributeValue(null, ATTR_TARGET_PORT_INSTANCE);
            } else if (ELEM_SHORT_DESCRIPTION.equals(elemName))
                shortDescription = cursor.getText();
            else if (ELEM_LONG_DESCRIPTION.equals(elemName))
                longDescription = cursor.getText();
            else if (ELEM_MESSAGES.equals(elemName)) {
                populateMessagingConfiguration(cursor);
            } else if (ELEM_MESSAGING_CONFIG_NAME.equals(elemName)) {
                messagingConfigName = cursor.getAttributeValue(null, ATTR_NAME);
            } else if (MessageTransformation.ELEM_MESSAGE_TRANSFORMATION.equals(elemName)) {
                messageTransformation = new MessageTransformation();
                messageTransformation.setFieldValues(cursor);
            } else if (ELEM_SELECTORS.equals(elemName)) {
                populateSelectorsConfiguration(cursor);
            } else if (ELEM_SELECTOR_CONFIG_NAME.equals(elemName)) {
                selectorConfigName = cursor.getAttributeValue(null, ATTR_NAME);
            } else if (LogManager.ELEM_LOG_MANAGER.equals(elemName)) {
                logManager = new LogManager();
                logManager.setFieldValues(cursor);
            } else if (ELEM_LOGMODULES.equals(elemName)) {
                cursor.markCursor(cursor.getLocalName());
                while (cursor.nextElement()) {
                    if (LogModule.ELEM_LOGMODULE.equals(cursor.getLocalName())) {
                        LogModule logModule = new LogModule();
                        logModule.setFieldValues(cursor);
                        logModules.add(logModule);
                    }
                }
                cursor.resetCursor();
            }
        }
    }
}

From source file:com.sonicle.webtop.mail.MultipartIterator.java

/**
 * Retrieves the next element in the iterator if one exists.
 *
 * @throws a ServletException if the post size exceeds the maximum file size
 *         passed in the 3 argument constructor
 * @throws an UnsupportedEncodingException if the "ISO-8859-1" encoding isn't found
 * @return a {@link org.apache.struts.upload.MultipartElement MultipartElement}
 *         representing the next element in the request data
 *
 *//*w w w  . j  av  a 2s.  c o  m*/
public MultipartElement getNextElement() throws ServletException, UnsupportedEncodingException {
    //retrieve the "Content-Disposition" header
    //and parse
    String disposition = readLine();

    if ((disposition != null) && (disposition.startsWith("Content-Disposition"))) {
        String name = parseDispositionName(disposition);
        String filename = parseDispositionFilename(disposition);

        String contentType = null;
        boolean isFile = (filename != null);

        if (isFile) {
            filename = new File(filename).getName();

            //check for windows filenames,
            //from linux jdk's the entire filepath
            //isn't parsed correctly from File.getName()
            int colonIndex = filename.indexOf(":");
            if (colonIndex == -1) {
                //check for Window's SMB server file paths
                colonIndex = filename.indexOf("\\\\");
            }
            int slashIndex = filename.lastIndexOf("\\");

            if ((colonIndex > -1) && (slashIndex > -1)) {
                //then consider this filename to be a full
                //windows filepath, and parse it accordingly
                //to retrieve just the file name
                filename = filename.substring(slashIndex + 1, filename.length());
            }

            //get the content type
            contentType = readLine();
            contentType = parseContentType(contentType);
        }

        //ignore next line (whitespace) (unless it's a file
        //without content-type)
        if (!((isFile) && contentType == null)) {
            readLine();
        }

        MultipartElement element = null;

        //process a file element
        if (isFile) {
            try {
                //create a local file on disk representing the element
                if (fileObjectDir == null) {
                    File elementFile = createLocalFile();
                    element = new MultipartElement(name, filename, contentType, elementFile);
                } else {
                    FileObject elementFile = createVFSFile(filename);
                    filename = elementFile.getName().getBaseName();
                    element = new MultipartElement(name, filename, contentType, elementFile);
                }

            } catch (IOException ioe) {
                Service.logger.error("Exception", ioe);
                throw new ServletException("IOException while reading file element: " + ioe.getMessage(), ioe);
            }
        } else {
            //read data into String form, then convert to bytes
            //for text
            StringBuffer textData = new StringBuffer();
            String line;
            //parse for text data
            line = readLine();

            while ((line != null) && (!line.startsWith(boundary))) {
                textData.append(line);
                line = readLine();
            }

            if (textData.length() > 0) {
                //cut off "\r" from the end if necessary
                if (textData.charAt(textData.length() - 1) == '\r') {
                    textData.setLength(textData.length() - 1);
                }
            }

            //create the element
            element = new MultipartElement(name, textData.toString());
        }
        return element;
    }

    //reset stream
    if (inputStream.markSupported()) {
        try {
            inputStream.reset();
        } catch (IOException ioe) {
            throw new ServletException("IOException while resetting input stream: " + ioe.getMessage());
        }
    }
    return null;
}

From source file:org.jboss.dashboard.commons.text.StringUtil.java

/**
 * Returns the position of the first ocurrence of the substring into
 * the stringbuffer, starting at fromIndex, or -1 if does not ocurr.
 * <br>//from  w  w  w  . j a  va2s  . c  om
 * Returns the smaller i greater than or equals to fromIndex such that
 * <p/>
 * buf.substring(i, str.length()).equals(str),
 * <p/>
 * holds, and -1 if no such i exists.
 * <p/>
 * Assumes str and buf are non-null.
 *
 * @param str       substring to find
 * @param fromIndex the index to start the search from
 * @param buf       buffer to search into
 * @return the position of subStr into buf, or -1 if it does not ocurr
 */
public static int indexOf(String str, int fromIndex, StringBuffer buf) {

    fromIndex = Math.max(fromIndex, 0);

    // begin degenerate cases
    if (fromIndex >= buf.length()) {
        if (fromIndex == 0 && str.length() == 0) {
            return 0;
        }
        return -1;
    }
    if (str.length() == 0) {
        return fromIndex;
    }
    // end degenerate cases

    int max = buf.length() - str.length();
    int i = fromIndex;
    while (true) {
        // look for the next occurrence of str.charAt(0)
        while (i <= max && buf.charAt(i) != str.charAt(0)) {
            ++i;
        }
        if (i > max) {
            return -1;
        }
        // once anchored, check the rest
        int j = i + 1, k = 1;
        while (k < str.length() && buf.charAt(j) == str.charAt(k)) {
            ++j;
            ++k;
        }
        if (k == str.length()) {
            return i; // all of them matched
        }
        ++i; // failed, try again
    }
}

From source file:org.jivesoftware.community.util.StringUtils.java

public static String makeURLSafe(String str, char replacement) {
    if (str == null || !isASCIIURLSafe(String.valueOf(replacement)))
        return null;
    String trimmed = str.trim();/* w w  w.j  ava  2 s  .c  om*/
    boolean ascii = str.trim()
            .replaceAll((new StringBuilder()).append("([\\p{Punct}&&[^\\").append(replacement).append("]]+)")
                    .toString(), "")
            .replaceAll(
                    (new StringBuilder()).append("([^A-Za-z\\").append(replacement).append("]+)").toString(),
                    String.valueOf(replacement))
            .toLowerCase().replaceAll((new StringBuilder()).append("").append(replacement).toString(), "")
            .replaceAll(" ", "").length() > 0;
    if (ascii) {
        trimmed = trimmed
                .replaceAll((new StringBuilder()).append("([\\p{Punct}&&[^\\").append(replacement)
                        .append("]]+)").toString(), "")
                .replaceAll((new StringBuilder()).append("([^0-9A-Za-z\\").append(replacement).append("]+)")
                        .toString(), String.valueOf(replacement))
                .toLowerCase();
        if (trimmed.length() > 1
                && (replacement == trimmed.charAt(0) || replacement == trimmed.charAt(trimmed.length() - 1))) {
            StringBuffer buf = new StringBuffer(trimmed);
            if (replacement == buf.charAt(0))
                buf.deleteCharAt(0);
            if (replacement == buf.charAt(buf.length() - 1))
                buf.deleteCharAt(buf.length() - 1);
            trimmed = buf.toString();
        }
    } else {
        boolean hasLetters = str.trim()
                .replaceAll((new StringBuilder()).append("([\\p{Punct}&&[^\\").append(replacement)
                        .append("]]+)").toString(), "")
                .replaceAll((new StringBuilder()).append("([^\\p{L}\\p{Nd}\\").append(replacement).append("]+)")
                        .toString(), String.valueOf(replacement))
                .replaceAll((new StringBuilder()).append("").append(replacement).toString(), "")
                .replaceAll(" ", "").length() > 0;
        if (hasLetters) {
            trimmed = str.trim();
            boolean cantLowercase = trimmed
                    .replaceAll((new StringBuilder()).append("([\\p{Punct}&&[^\\").append(replacement)
                            .append("]]+)").toString(), "")
                    .replaceAll((new StringBuilder()).append("([^\\p{Lo}\\").append(replacement).append("]+)")
                            .toString(), String.valueOf(replacement))
                    .replaceAll((new StringBuilder()).append("").append(replacement).toString(), "")
                    .replaceAll(" ", "").length() > 0;
            trimmed = trimmed
                    .replaceAll((new StringBuilder()).append("([\\p{Punct}&&[^\\").append(replacement)
                            .append("]]+)").toString(), "")
                    .replaceAll((new StringBuilder()).append("([^\\p{L}\\p{Nd}\\").append(replacement)
                            .append("]+)").toString(), String.valueOf(replacement));
            if (!cantLowercase)
                trimmed = trimmed.toLowerCase();
        } else {
            trimmed = trimmed.toLowerCase();
        }
    }
    return "".equals(trimmed) || "-".equals(trimmed) ? String.valueOf(Math.abs(str.hashCode())) : trimmed;
}

From source file:org.sparkcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator.java

protected void buildMVEL(DataDTO dataDTO, StringBuffer sb, String entityKey, String groupOperator,
        RuleBuilderFieldService fieldService) throws MVELTranslationException {
    SCOperator operator = null;/*  w  ww  .  ja  v a  2  s  . co  m*/
    if (dataDTO instanceof ExpressionDTO) {
        operator = SCOperator.valueOf(((ExpressionDTO) dataDTO).getOperator());
    } else {
        operator = SCOperator.valueOf(dataDTO.getGroupOperator());
    }
    ArrayList<DataDTO> groups = dataDTO.getGroups();
    if (sb.length() != 0 && sb.charAt(sb.length() - 1) != '(' && groupOperator != null) {
        SCOperator groupOp = SCOperator.valueOf(groupOperator);
        switch (groupOp) {
        default:
            sb.append("&&");
            break;
        case OR:
            sb.append("||");
        }
    }
    if (dataDTO instanceof ExpressionDTO) {
        buildExpression((ExpressionDTO) dataDTO, sb, entityKey, operator, fieldService);
    } else {
        boolean includeTopLevelParenthesis = false;
        if (sb.length() != 0 || SCOperator.NOT.equals(operator)
                || (sb.length() == 0 && groupOperator != null)) {
            includeTopLevelParenthesis = true;
        }
        if (SCOperator.NOT.equals(operator)) {
            sb.append("!");
        }
        if (includeTopLevelParenthesis)
            sb.append("(");
        for (DataDTO dto : groups) {
            buildMVEL(dto, sb, entityKey, dataDTO.getGroupOperator(), fieldService);
        }
        if (includeTopLevelParenthesis)
            sb.append(")");
    }
}

From source file:org.broadleafcommerce.openadmin.web.rulebuilder.DataDTOToMVELTranslator.java

protected void buildMVEL(DataDTO dataDTO, StringBuffer sb, String entityKey, String groupOperator,
        RuleBuilderFieldService fieldService) throws MVELTranslationException {
    BLCOperator operator = null;/*from www. jav a  2  s  .  c  o m*/
    if (dataDTO instanceof ExpressionDTO) {
        operator = BLCOperator.valueOf(((ExpressionDTO) dataDTO).getOperator());
    } else {
        operator = BLCOperator.valueOf(dataDTO.getGroupOperator());
    }
    ArrayList<DataDTO> groups = dataDTO.getGroups();
    if (sb.length() != 0 && sb.charAt(sb.length() - 1) != '(' && groupOperator != null) {
        BLCOperator groupOp = BLCOperator.valueOf(groupOperator);
        switch (groupOp) {
        default:
            sb.append("&&");
            break;
        case OR:
            sb.append("||");
        }
    }
    if (dataDTO instanceof ExpressionDTO) {
        buildExpression((ExpressionDTO) dataDTO, sb, entityKey, operator, fieldService);
    } else {
        boolean includeTopLevelParenthesis = false;
        if (sb.length() != 0 || BLCOperator.NOT.equals(operator)
                || (sb.length() == 0 && groupOperator != null)) {
            includeTopLevelParenthesis = true;
        }
        if (BLCOperator.NOT.equals(operator)) {
            sb.append("!");
        }
        if (includeTopLevelParenthesis)
            sb.append("(");
        for (DataDTO dto : groups) {
            buildMVEL(dto, sb, entityKey, dataDTO.getGroupOperator(), fieldService);
        }
        if (includeTopLevelParenthesis)
            sb.append(")");
    }
}

From source file:my.home.model.datasource.AutoCompleteItemDataSourceImpl.java

@Override
public void getAutoCompleteItems(Context context, String currentInput) {
    if (!mLoadSuccess) {
        BusProvider.getRestBusInstance().post(new MGetAutoCompleteItemEvent(new ArrayList()));
        return;//from   www. jav  a2 s .  co  m
    }

    boolean in_msg_or_time_ind_state = false;
    boolean in_msg_or_time_state = false;
    boolean in_if_state = false;
    boolean in_if_then_state = false;
    boolean in_while_state = false;
    String leftString = "";
    String lastString = "";
    String lastPreMsg = "";
    String lastState = "";
    StringBuffer cmdBuffer = new StringBuffer();
    StringBuffer inputBuffer = new StringBuffer(currentInput);
    String curState = mInitState;
    while (inputBuffer.length() > 0) {
        if (in_msg_or_time_ind_state) {
            if (inputBuffer.toString().startsWith(mMessageSeq) || inputBuffer.toString().startsWith(mTimeSeq)) {
                in_msg_or_time_ind_state = false;
            }
            cmdBuffer.append(inputBuffer.charAt(0));
            inputBuffer.deleteCharAt(0);
            continue;
        }
        boolean found = false;
        String tempInput = inputBuffer.toString();
        if (!mLinks.containsKey(curState)) {
            BusProvider.getRestBusInstance().post(new MGetAutoCompleteItemEvent(new ArrayList()));
            return;
        }
        for (String nextState : mLinks.get(curState)) {
            if (!in_if_state && !in_while_state) {
                if (nextState.equals("then") || nextState.equals("compare") || nextState.equals("logical"))
                    continue;
            }
            if (!in_if_then_state) {
                if (nextState.equals("else"))
                    continue;
            }
            for (String val : mNodes.get(nextState)) {
                if (tempInput.startsWith(val)) {
                    leftString = inputBuffer.toString();
                    lastState = nextState;
                    inputBuffer.delete(0, val.length());
                    cmdBuffer.append(val);
                    found = true;
                    in_msg_or_time_state = false;

                    if (nextState.equals("message") || nextState.equals("time")) {
                        in_msg_or_time_ind_state = true;
                        lastPreMsg = lastString;
                    } else if (nextState.equals("if")) {
                        in_if_state = true;
                    } else if (nextState.equals("while")) {
                        in_while_state = true;
                    } else if (nextState.equals("then")) {
                        if (in_if_state)
                            in_if_then_state = true;
                        in_if_state = false;
                        in_while_state = false;
                    } else if (in_if_then_state && nextState.equals("else")) {
                        in_if_then_state = false;
                    }
                    lastString = val;
                    curState = nextState;
                    break;
                } else if (nextState.equals("message") && val.startsWith(tempInput)) {
                    lastState = nextState;
                }
            }
            if (inputBuffer.length() == 0)
                break;
        }
        if (inputBuffer.length() == 0)
            break;
        if (found)
            continue;
        if (curState.equals("message") || mLinks.get(curState).contains("message")) {
            in_msg_or_time_state = true;
            found = true;
            curState = "message";
            cmdBuffer.append(inputBuffer.charAt(0));
            inputBuffer.deleteCharAt(0);
        } else if (curState.equals("time") || mLinks.get(curState).contains("time")) {
            in_msg_or_time_state = true;
            found = true;
            curState = "time";
            cmdBuffer.append(inputBuffer.charAt(0));
            inputBuffer.deleteCharAt(0);
        }
        if (!found)
            break;
    }

    String cmdString = cmdBuffer.toString();
    Set<AutoCompleteItem> resultSet = new HashSet<>();

    if (in_msg_or_time_ind_state) {
        String cmd = cmdString + mMessageSeq;
        if (curState.equals("time")) {
            addTimeToolItemToResult(resultSet);
            addDateToolItemToResult(resultSet);
        }
        // 1
        addFavorToolItemToResult(resultSet);
        // 2
        addMsgHistoryItemToResult(resultSet, context, cmdString, lastPreMsg, curState);
        // 3
        resultSet.add(new AutoCompleteItem(curState, 1.0f, mMessageSeq, cmd));
    } else if (inputBuffer.length() == 0) {
        ArrayList<AutoCompleteItem> unweightItems = new ArrayList<>();
        String tempLeft = new StringBuilder(leftString).delete(0, lastString.length()).toString();
        if (tempLeft.length() != 0) {
            if (curState.equals("message") || curState.equals("time")) {
                for (String nextState : mLinks.get(lastState)) {
                    for (String val : mNodes.get(nextState)) {
                        if (val.startsWith(tempLeft)) {
                            String tempCmd = new StringBuilder(val).delete(0, tempLeft.length()).toString();
                            String cmd = cmdString + tempCmd;
                            //                                resultSet.add(new AutoCompleteItem(nextState, Float.MAX_VALUE, val, cmd));
                            unweightItems.add(
                                    new AutoCompleteItem(nextState, DEFAULT_AUTOCOMPLETE_WEIGHT, val, cmd));
                        }
                    }
                }
            } else {
                for (String val : mNodes.get(curState)) {
                    if (val.startsWith(tempLeft) && !val.equals(tempLeft)) {
                        String tempCmd = new StringBuilder(val).delete(0, lastString.length()).toString();
                        String cmd = cmdString + tempCmd;
                        //                            resultSet.add(new AutoCompleteItem(curState, Float.MAX_VALUE, val, cmd));
                        unweightItems
                                .add(new AutoCompleteItem(curState, DEFAULT_AUTOCOMPLETE_WEIGHT, val, cmd));
                    }
                }
            }
        } else if (leftString.equals(lastString)) {
            for (String val : mNodes.get(curState)) {
                if (val.startsWith(leftString) && val.length() != leftString.length()) {
                    String tempCmd = new StringBuilder(val).delete(0, lastString.length()).toString();
                    String cmd = cmdString + tempCmd;
                    //                        resultSet.add(new AutoCompleteItem(curState, DEFAULT_AUTOCOMPLETE_WEIGHT, val, cmd));
                    unweightItems.add(new AutoCompleteItem(curState, DEFAULT_AUTOCOMPLETE_WEIGHT, val, cmd));
                }
            }
        }

        if (in_msg_or_time_state) {
            addTimeToolItemToResult(resultSet);
            addDateToolItemToResult(resultSet);
            addFavorToolItemToResult(resultSet);
        }
        for (String nextState : mLinks.get(curState)) {
            if (nextState.equals("then")) {
                if (in_if_state || in_while_state) {
                    for (String val : mNodes.get(nextState)) {
                        String cmd = cmdString + val;
                        resultSet.add(new AutoCompleteItem(nextState, 1.0f, val, cmd));
                    }
                }
            } else if (nextState.equals("else")) {
                if (in_if_then_state) {
                    for (String val : mNodes.get(nextState)) {
                        String cmd = cmdString + val;
                        resultSet.add(new AutoCompleteItem(nextState, 1.0f, val, cmd));
                    }
                }
            } else {
                if (nextState.equals("compare") || nextState.equals("logical"))
                    if (!in_if_state && !in_while_state)
                        continue;
                if (nextState.equals("message") || nextState.equals("time")) {
                    addTimeToolItemToResult(resultSet);
                    addDateToolItemToResult(resultSet);
                    addFavorToolItemToResult(resultSet);
                }
                for (String val : mNodes.get(nextState)) {
                    String cmd = cmdString + val;
                    unweightItems.add(new AutoCompleteItem(nextState, DEFAULT_AUTOCOMPLETE_WEIGHT, val, cmd));
                }
            }
        }
        if (unweightItems.size() != 0) {
            setItemWeight(context, unweightItems, lastString);
            resultSet.addAll(unweightItems);
        }
    } else {
        String tempInput = inputBuffer.toString();
        ArrayList<AutoCompleteItem> unweightItems = new ArrayList<>();
        if (tempInput.length() != 0) {
            for (String nextState : mLinks.get(curState)) {
                for (String val : mNodes.get(nextState)) {
                    if (val.startsWith(tempInput)) {
                        String cmd = cmdString + val;
                        unweightItems
                                .add(new AutoCompleteItem(nextState, DEFAULT_AUTOCOMPLETE_WEIGHT, val, cmd));
                    }
                }
            }
        }
        if (unweightItems.size() != 0) {
            setItemWeight(context, unweightItems, tempInput);
            resultSet.addAll(unweightItems);
        }
    }
    List<AutoCompleteItem> resultList = new ArrayList<>(resultSet);
    Collections.sort(resultList, mResultComparator);
    BusProvider.getRestBusInstance().post(new MGetAutoCompleteItemEvent(resultList));
}

From source file:com.netcrest.pado.tools.pado.command.put.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private Map getEntryMap(String fullPath, BufferInfo bufferInfo, List<String> list, boolean keyEnumerated,
        boolean valueEnumerated, int startIndex) throws Exception {
    String pairs = "";
    for (int i = startIndex; i < list.size(); i++) {
        pairs += list.get(i) + " ";
    }/*w  w  w.  j  av  a  2  s  .c o m*/

    Map<String, Method> keySetterMap = ReflectionUtil.getAllSettersMap(padoShell.getKeyClass());
    Map<String, Method> valueSetterMap = ReflectionUtil.getAllSettersMap(padoShell.getValueClass());

    String gridPath = GridUtil.getChildPath(fullPath);
    String gridId = SharedCache.getSharedCache().getGridId(fullPath);
    IGridMapBiz gridMapBiz = SharedCache.getSharedCache().getPado().getCatalog().newInstance(IGridMapBiz.class,
            gridPath);
    gridMapBiz.getBizContext().getGridContextClient().setGridIds(gridId);

    // (x='1,2,3' and y='2',a='hello, world' and b='test')
    HashMap map = new HashMap();
    StringBuffer buffer = new StringBuffer(pairs);
    boolean keySearch = false;
    boolean fieldSearch = false;
    boolean openQuote = false;
    boolean delimiter = false;
    boolean quoted = false;
    String fieldString = "";
    String valueString = "";
    String and = "";

    Object key = null;
    Object value = null;
    for (int i = 0; i < buffer.length(); i++) {
        char c = buffer.charAt(i);
        if (c == '(') {
            if (openQuote == false) {

                String function = null;
                String functionCall = null;
                String functionString = null;
                if (valueString.length() > 0) {
                    functionString = valueString;
                } else if (fieldString.length() > 0) {
                    functionString = fieldString;
                }
                if (functionString != null) {

                    // it's a function

                    // get enclosed parenthesis
                    int enclosedIndex = getEnclosingParenthesis(buffer, i);

                    function = functionString.toLowerCase();
                    if (enclosedIndex == -1) {
                        throw new ParseException("Malformed function call: " + function, i);
                    }

                    functionCall = function + buffer.substring(i, enclosedIndex + 1);
                    Logger.fine("functionCall = |" + functionCall + "|");
                    i = enclosedIndex;
                }
                if (functionCall != null) {
                    if (valueString.length() > 0) {
                        valueString = functionCall;
                    } else if (fieldString.length() > 0) {
                        fieldString = functionCall;
                    }

                } else {
                    key = null;
                    value = null;
                    keySearch = true;
                    fieldSearch = true;
                    fieldString = "";
                    valueString = "";
                }

                quoted = false;

                continue;
            }

        } else if (c == '=') {
            if (keySearch && key == null && keyEnumerated == false) {
                key = padoShell.getKeyClass().newInstance();
            }
            if (keySearch == false && value == null && valueEnumerated == false) {
                if (padoShell.getValueClass() == null) {
                    throw new ClassNotFoundException(
                            "Undefined value class. Use the 'value' command to set the class name");
                }
                value = padoShell.getValueClass().newInstance();
            }
            fieldSearch = false;
            continue;
        } else if (c == ')') {
            if (openQuote == false) {
                Logger.fine("v: field = " + fieldString);
                Logger.fine("v: value = " + valueString);
                Logger.fine("");

                if (valueEnumerated) {
                    Object k = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                    if (k == null) {
                        PadoShell.printlnError(
                                "Error: value not found in the cache for the key number " + fieldString);
                        PadoShell.println("       run 'key -l' to view the enumerated keys.");
                        map.clear();
                        break;
                    }
                    value = gridMapBiz.get(k);
                    if (key == null) {
                        PadoShell.printlnError("Error: value not in the cache - " + fieldString);
                        map.clear();
                        break;
                    }
                    Logger.fine("k = " + k);
                    Logger.fine("key = " + key);
                    Logger.fine("value = " + value);
                } else {
                    if (valueString.length() == 0) {
                        // primitive
                        value = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                    } else {
                        updateObject(valueSetterMap, value, fieldString, valueString);
                    }
                }

                map.put(key, value);

                fieldSearch = true;
                quoted = false;
                fieldString = "";
                valueString = "";
                key = null;
                and = "";
                continue;
            }
        } else if (c == '\\') {
            // ignore and treat the next character as a character
            delimiter = true;
            continue;
        } else if (c == '\'') {
            if (delimiter) {
                delimiter = false;
            } else {
                if (openQuote) {
                    quoted = true;
                }
                openQuote = !openQuote;
                continue;
            }
        } else if (c == ' ') {
            if (openQuote == false) {
                boolean andExpected = false;
                if (keySearch) {
                    Logger.fine("k: field = " + fieldString);
                    Logger.fine("k: value = " + valueString);
                    Logger.fine("");

                    if (fieldString.length() > 0) {
                        updateObject(keySetterMap, key, fieldString, valueString);
                        andExpected = true;
                    }
                } else {
                    Logger.fine("v: field = " + fieldString);
                    Logger.fine("v: value = " + valueString);
                    Logger.fine("");

                    if (fieldString.length() > 0) {
                        updateObject(valueSetterMap, value, fieldString, valueString);
                        andExpected = true;
                    }
                }

                if (andExpected) {
                    and = "";
                    int index = -1;
                    for (int j = i; j < buffer.length(); j++) {
                        and += buffer.charAt(j);
                        and = and.trim().toLowerCase();
                        if (and.equals("and")) {
                            index = j;
                            break;
                        } else if (and.length() > 3) {
                            break;
                        }
                    }
                    if (index != -1) {
                        i = index;
                    }
                }

                fieldSearch = true;
                fieldString = "";
                valueString = "";
                and = "";
                quoted = false;
                continue;
            }
        }

        if (c == ',') {

            // if ',' is not enclosed in quotes...
            if (openQuote == false) {

                fieldString = fieldString.trim();
                valueString = valueString.trim();

                // end of key
                Logger.fine("k: field = " + fieldString);
                Logger.fine("k: value = " + valueString);
                Logger.fine("");

                if (keySearch) {
                    if (keyEnumerated) {
                        key = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                        if (key == null) {
                            PadoShell.printlnError(
                                    "Error: value not found in the cache for the key number " + fieldString);
                            PadoShell.println("       run 'key -l' to view the enumerated keys.");
                            map.clear();
                            break;
                        }
                    } else {
                        if (valueString.length() == 0) {
                            key = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                        } else {
                            updateObject(keySetterMap, key, fieldString, valueString);
                        }
                    }
                } else {

                    if (valueEnumerated) {
                        Object k = bufferInfo.getKey(Integer.parseInt(fieldString) - 1);
                        value = gridMapBiz.get(k);
                        if (value == null) {
                            PadoShell.printlnError("Error: undefined value num " + fieldString);
                            map.clear();
                            break;
                        }
                    } else {
                        if (valueString.length() == 0) {
                            value = ObjectUtil.getPrimitive(padoShell, fieldString, quoted);
                        } else {

                            updateObject(valueSetterMap, value, fieldString, valueString);
                        }
                    }

                }

                fieldSearch = true;
                keySearch = false;
                quoted = false;
                fieldString = "";
                valueString = "";
                and = "";
                continue;
            }
        }

        if (fieldSearch) {
            fieldString += c;
        } else if (quoted == false) {
            valueString += c;
        }
    }

    return map;
}

From source file:org.apache.axis2.deployment.util.Utils.java

/**
 * Normalize a uri containing ../ and ./ paths.
 *
 * @param uri The uri path to normalize//w  w  w .j a va2  s .  c o m
 * @return The normalized uri
 */
public static String normalize(String uri) {
    if ("".equals(uri)) {
        return uri;
    }
    int leadingSlashes;
    for (leadingSlashes = 0; leadingSlashes < uri.length()
            && uri.charAt(leadingSlashes) == '/'; ++leadingSlashes) {
        // FIXME: this block is empty!!
    }
    boolean isDir = (uri.charAt(uri.length() - 1) == '/');
    StringTokenizer st = new StringTokenizer(uri, "/");
    LinkedList clean = new LinkedList();
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if ("..".equals(token)) {
            if (!clean.isEmpty() && !"..".equals(clean.getLast())) {
                clean.removeLast();
                if (!st.hasMoreTokens()) {
                    isDir = true;
                }
            } else {
                clean.add("..");
            }
        } else if (!".".equals(token) && !"".equals(token)) {
            clean.add(token);
        }
    }
    StringBuffer sb = new StringBuffer();
    while (leadingSlashes-- > 0) {
        sb.append('/');
    }
    for (Iterator it = clean.iterator(); it.hasNext();) {
        sb.append(it.next());
        if (it.hasNext()) {
            sb.append('/');
        }
    }
    if (isDir && sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') {
        sb.append('/');
    }
    return sb.toString();
}