Example usage for java.lang StringBuilder insert

List of usage examples for java.lang StringBuilder insert

Introduction

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

Prototype

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

Source Link

Usage

From source file:com.portmods.handlers.crackers.dictionary.Wordlist.java

@Override
public void run() {

    try {/* w w w  .j  a va 2 s.co m*/

        System.out.println("Loading Dictionary");

        InputStream fileStream = null;

        if (config.getUseCustomDictionary()) {

            try {

                fileStream = new FileInputStream(config.getCustomDictionary());

            } catch (Exception e) {

                JOptionPane.showMessageDialog(null, e, "Error with Dictonary File.", JOptionPane.ERROR_MESSAGE);
                System.exit(1);

            }

        } else {

            fileStream = Main.class.getResourceAsStream("/com/portmods/files/words.txt");

        }

        BufferedReader reader = new BufferedReader(new InputStreamReader(fileStream, "UTF-8"));

        /* declaring storage list */
        wordlist = new ArrayList<String>();
        String text = "";

        String line = reader.readLine();

        while (line != null) //wait for ever
        {
            text = line;
            line = reader.readLine();
            if (text.length() < 9 && text.length() > 2) {
                wordlist.add(text);
            }

        }

    } catch (UnsupportedEncodingException e) {

        System.out.println("Error Loading Dictionary");

    } catch (IOException e) {

        System.out.println("Error Loading Dictionary");

    }

    System.out.println("Finished Loading Dictionary");
    System.out.println("Rule 1 : Do nothing to word");

    for (String s : wordlist) {

        String hash = UnixCrypt.crypt(s, "aa");

        for (User u : pw.getUsers()) {

            if (u.getHash().equals(hash)) {

                System.out.println("Found password " + s + " for user " + u.getUserName());
                fp.addPassword(u.getUserName(), s);

            }

        }

    }

    System.out.println("Rule 2 : Toggle case of every character");
    /* Chaning word characters one at time lowerecase to Uppercase and vice Veser. */
    for (String s : wordlist) {
        for (int i = 0; i < s.length(); i++) {
            char C = s.charAt(i); //take character from the word
            StringBuilder sbuilder = new StringBuilder(s); //word we want to inject the character into
            if (Character.isUpperCase(C)) {
                sbuilder.setCharAt(i, Character.toLowerCase(C)); //changing the character to lowercase

            } else if (Character.isLowerCase(C)) {
                sbuilder.setCharAt(i, Character.toUpperCase(C)); // change to uppercase
            }

            String hash = UnixCrypt.crypt(sbuilder.toString(), "aa");

            for (User u : pw.getUsers()) {

                if (u.getHash().equals(hash)) {

                    System.out
                            .println("Found password " + sbuilder.toString() + " for user " + u.getUserName());
                    fp.addPassword(u.getUserName(), sbuilder.toString());

                }

            }

        }

    }

    System.out.println("Rule 3 : adding random numbers and leters into the word");
    /* generating number and adding to the words*/
    for (String s : wordlist) {
        for (int i = 0; i < 10; i++) {
            StringBuilder sb = new StringBuilder(s);
            sb.append(i); //add an integer to each word.

            String out = sb.toString();

            if (out.length() <= 8) {

                String hash = UnixCrypt.crypt(out, "aa");

                for (User u : pw.getUsers()) {

                    if (u.getHash().equals(hash)) {

                        System.out.println("Found password " + sb.toString() + " for user " + u.getUserName());
                        fp.addPassword(u.getUserName(), sb.toString());

                    }

                }

            }

        }

    }

    System.out.println("Rule 4: Toggle one charater at a time and replace a number");
    /* trying to toggle one charater at a time and replace a number*/
    for (String s : wordlist) {
        for (int j = 0; j < s.length(); j++) {
            for (int i = 0; i < 10; i++) {
                char C = s.charAt(j); //take character from the word
                StringBuilder sbuilder = new StringBuilder(s); //word we want to inject the character into
                if (Character.isAlphabetic(C)) {
                    sbuilder.deleteCharAt(j); //remove character
                    sbuilder.insert(j, i); // add digit

                    String hash = UnixCrypt.crypt(sbuilder.toString(), "aa");

                    for (User u : pw.getUsers()) {

                        if (u.getHash().equals(hash)) {

                            System.out.println(
                                    "Found password " + sbuilder.toString() + " for user " + u.getUserName());
                            fp.addPassword(u.getUserName(), sbuilder.toString());

                        }

                    }
                }

            }

            for (int x = 65; x < 123; x++) {
                char C1 = (char) x;

                char C = s.charAt(j); //take character from the word
                StringBuilder sbuilder = new StringBuilder(s); //word we want to inject the character into
                if (Character.isDigit(C)) {
                    sbuilder.setCharAt(j, C1);

                    String hash = UnixCrypt.crypt(sbuilder.toString(), "aa");

                    for (User u : pw.getUsers()) {

                        if (u.getHash().equals(hash)) {

                            System.out.println(
                                    "Found password " + sbuilder.toString() + " for user " + u.getUserName());
                            fp.addPassword(u.getUserName(), sbuilder.toString());

                        }

                    }

                }

            }

        }

    }

    System.out.println("Rule 5 : Adding random letters and numbers to the end");
    /* adding ascii values to a text string */

    for (String s : wordlist) {
        int x = 1;
        StringBuilder sb = new StringBuilder(s);
        for (int i = 33; i < 123; i++) {
            char L1 = (char) i;
            String out = sb.toString();

            String out1 = out + L1;

            if (out1.length() > 8) {

                break;

            } else {

                String hash = UnixCrypt.crypt(out1, "aa");

                for (User u : pw.getUsers()) {

                    if (u.getHash().equals(hash)) {

                        System.out.println("Found password " + out1 + " for user " + u.getUserName());
                        fp.addPassword(u.getUserName(), out1);

                    }

                }

            }

            for (int j = 33; j < 123; j++) {
                char L2 = (char) j;

                String out2 = out + L1 + L2;

                if (out2.length() > 8) {

                    break;

                } else {

                    String hash = UnixCrypt.crypt(out2, "aa");

                    for (User u : pw.getUsers()) {

                        if (u.getHash().equals(hash)) {

                            System.out.println("Found password " + out2 + " for user " + u.getUserName());
                            fp.addPassword(u.getUserName(), out2);

                        }

                    }

                }

                for (int k = 33; k < 123; k++) {
                    char L3 = (char) k;

                    String out3 = out + L1 + L2 + L3;

                    if (out3.length() > 8) {

                        break;

                    } else {

                        String hash = UnixCrypt.crypt(out3, "aa");

                        for (User u : pw.getUsers()) {

                            if (u.getHash().equals(hash)) {

                                System.out.println("Found password " + out3 + " for user " + u.getUserName());
                                fp.addPassword(u.getUserName(), out3);

                            }

                        }

                    }
                    for (int l = 33; l < 123; l++) {
                        char L4 = (char) l;

                        String out4 = out + L1 + L2 + L3 + L4;

                        if (out4.length() > 8) {

                            break;

                        } else {

                            String hash = UnixCrypt.crypt(out4, "aa");

                            for (User u : pw.getUsers()) {

                                if (u.getHash().equals(hash)) {

                                    System.out
                                            .println("Found password " + out4 + " for user " + u.getUserName());
                                    fp.addPassword(u.getUserName(), out4);

                                }

                            }

                        }
                    }
                }
            }
            if (out.length() < 8) {

            } else {

                System.out.println(out);
                break;
            }
        }
    }

    config.setDicModeFin(true);

}

From source file:net.triptech.metahive.model.Record.java

/**
 * Builds the where statement./*w  w  w  . ja v  a2s .  c o m*/
 *
 * @param filter the filter
 * @return the string
 */
private static Map<String, Map<String, Object>> buildWhere(final RecordFilter filter) {

    Map<String, Map<String, Object>> whereParameters = new HashMap<String, Map<String, Object>>();

    StringBuilder where = new StringBuilder();
    HashMap<String, Object> variables = new HashMap<String, Object>();

    if (filter.getFilterVectors() != null) {
        for (int i = 0; i < filter.getFilterVectors().size(); i++) {
            FilterVector vector = filter.getFilterVectors().get(i);

            StringBuilder vectorWhere = new StringBuilder();
            StringBuilder description = new StringBuilder();

            Map<Long, RecordFilterVector> rVectors = buildRecordVectors(vector);

            for (Long id : rVectors.keySet()) {
                RecordFilterVector rVector = rVectors.get(id);

                Map<String, Map<String, Object>> searchOperation = getSearchOperation(rVector, i);
                String operation = "";

                if (searchOperation.size() > 0) {
                    operation = searchOperation.keySet().iterator().next();
                }

                if (StringUtils.isNotBlank(operation)) {
                    Map<String, Object> params = searchOperation.get(operation);

                    if (vectorWhere.length() > 0) {
                        vectorWhere.append(" AND");
                    }

                    vectorWhere.append(" r.id IN (SELECT kv.record from KeyValue kv");
                    vectorWhere.append(" WHERE kv.definition = ");
                    vectorWhere.append(id);
                    vectorWhere.append(" AND ");
                    vectorWhere.append(operation);
                    vectorWhere.append(")");

                    for (String key : params.keySet()) {
                        Object parameter = params.get(key);

                        DataType dataType = rVector.getDefinition().getDataType();

                        variables.put(key, parseParameter(parameter, dataType));
                    }
                }
                if (description.length() > 0) {
                    description.append(" and ");
                }
                description.append(rVector.getDescription());
            }

            // The default where condition if no parameters have been supplied
            if (vectorWhere.length() == 0) {
                vectorWhere.append("r.id > 0");
                description = new StringBuilder("All records");
            }
            vector.setDescription(description.toString());

            logger.info("Filter action: " + vector.getAction());

            if (where.length() > 0) {
                if (vector.getAction() == FilterAction.ADD) {
                    where.append(" OR ");
                }
                if (vector.getAction() == FilterAction.REMOVE) {
                    where.append(" AND NOT ");
                }
                if (vector.getAction() == FilterAction.SUBSEARCH) {
                    where.append(" AND ");
                }
            }
            where.insert(0, "(");
            where.append(vectorWhere.toString().trim());
            where.append(")");
        }
    }

    if (StringUtils.isNotBlank(filter.getRecordId())) {
        if (where.length() > 0) {
            where.append(" AND ");
        }
        where.append("LOWER(r.recordId) LIKE LOWER(:recordId)");
        variables.put("recordId", filter.getRecordId());
    }

    where.insert(0, " WHERE ");
    whereParameters.put(where.toString(), variables);
    logger.info("SQL WHERE: " + where.toString());

    return whereParameters;
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.java

/**
 * Sets the specified color attribute to the specified value.
 * @param name the color attribute's name
 * @param value the color attribute's value
 *//*from   www  .j  a  v  a2 s. co  m*/
protected void setColorAttribute(final String name, final String value) {
    String s = value;
    if (!s.isEmpty()) {
        final boolean restrict = getBrowserVersion().hasFeature(HTML_COLOR_RESTRICT);

        boolean isName = false;
        if (restrict) {
            for (final String key : COLORS_MAP_IE.keySet()) {
                if (key.equalsIgnoreCase(value)) {
                    isName = true;
                    break;
                }
            }
        }
        if (!isName) {
            if (restrict) {
                if (s.charAt(0) == '#') {
                    s = s.substring(1);
                }
                final StringBuilder builder = new StringBuilder(7);
                for (int x = 0; x < 6 && x < s.length(); x++) {
                    final char ch = s.charAt(x);
                    if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')) {
                        builder.append(ch);
                    } else {
                        builder.append('0');
                    }
                }
                builder.insert(0, '#');
                s = builder.toString();
            }
        }
        if (getBrowserVersion().hasFeature(HTML_COLOR_TO_LOWER)) {
            s = s.toLowerCase(Locale.ROOT);
        }
    }
    getDomNodeOrDie().setAttribute(name, s);
}

From source file:de.juwimm.cms.util.Communication.java

@SuppressWarnings("unchecked")
public boolean removeViewComponent(int intViewComponentId, String viewComponentName, byte onlineState) {
    boolean retVal = false;

    try {//from   w ww.  ja  va 2  s  .c o  m
        // CHECK IF THIS NODE CONTAINS SUBNODES
        ViewIdAndInfoTextValue[] str = getAllChildrenNamesWithUnit(intViewComponentId);
        String units = "";
        if (str != null && str.length > 0) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < str.length; i++) {
                sb.append(str[i].getInfoText().trim()).append("\n");
            }
            units = sb.toString();
        }
        if (!units.equalsIgnoreCase("")) {
            if (!isUserInRole(UserRights.SITE_ROOT)) {
                // dazwischen, damit sparen wir uns das zweite...
                String msg = Messages.getString("comm.removevc.containsunitsandcannotremove", units);
                JOptionPane.showMessageDialog(UIConstants.getMainFrame(), msg, rb.getString("dialog.title"),
                        JOptionPane.ERROR_MESSAGE);
                return false;
            }
            units = Messages.getString("comm.removevc.header_units", units);
        }

        String refVcs = "";
        ViewComponentValue[] refDao = getViewComponentsWithReferenceToViewComponentId(intViewComponentId);
        if (refDao != null && refDao.length > 0) {
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < refDao.length; j++) {
                if (refDao[j].getViewType() == Constants.VIEW_TYPE_INTERNAL_LINK) {
                    // InternalLink in the Tree
                    sb.append(Messages.getString("comm.removevc.refvc.internallink",
                            ("\"" + refDao[j].getDisplayLinkName() + "\""),
                            ("\"" + refDao[j].getMetaData().trim() + "\""))).append("\n");
                } else if (refDao[j].getViewType() == Constants.VIEW_TYPE_SYMLINK) {
                    // reference though Symlink in the Tree
                    sb.append(Messages.getString("comm.removevc.refvc.symlink",
                            ("\"" + refDao[j].getDisplayLinkName() + "\""),
                            ("\"" + refDao[j].getMetaData().trim() + "\""))).append("\n");
                } else {
                    // reference through links in the content
                    sb.append(Messages.getString("comm.removevc.refvc.content",
                            ("\"" + refDao[j].getDisplayLinkName() + "\""),
                            ("\"" + refDao[j].getMetaData().trim() + "\""))).append("\n");
                }
            }
            refVcs = sb.toString();
        }

        if (!refVcs.equals("")) {
            refVcs = Messages.getString("comm.removevc.header_refvcs", refVcs);
        }

        String teaserText = "";
        boolean teaserReferenced = false;
        try {
            StringBuilder refTeaser = new StringBuilder("");
            XmlSearchValue[] xmlSearchValues = this.searchXml(getSiteId(), "//teaserRef");
            if (xmlSearchValues != null && xmlSearchValues.length > 0) {
                // herausfinden, ob es sich um DIESEN Teaser handelt
                String resultRootStartElement = "<searchTeaserResult>";
                String resultRootEndElement = "</searchTeaserResult>";
                for (int i = 0; i < xmlSearchValues.length; i++) {
                    StringBuilder stringBuilder = new StringBuilder(xmlSearchValues[i].getContent());
                    stringBuilder.insert(0, resultRootStartElement);
                    stringBuilder.append(resultRootEndElement);
                    Document doc = XercesHelper.string2Dom(stringBuilder.toString());
                    Iterator<Element> teaserIterator = XercesHelper.findNodes(doc,
                            "searchTeaserResult/teaserRef");
                    while (teaserIterator.hasNext()) {
                        Element element = teaserIterator.next();
                        String viewComponentIdValue = element.getAttribute("viewComponentId");
                        if (viewComponentIdValue != null && viewComponentIdValue.trim().length() > 0) {
                            if (intViewComponentId == (new Integer(viewComponentIdValue)).intValue()) {
                                teaserReferenced = true;
                                refTeaser.append(this.getPathForViewComponentId(
                                        xmlSearchValues[i].getViewComponentId().intValue()) + "\n");
                            }
                        }
                    }
                }
                if (teaserReferenced) {
                    teaserText = Messages.getString("comm.removevc.header.teaser", refTeaser.toString());
                }
            }
        } catch (Exception exception) {
            log.error(exception.getMessage(), exception);
        }
        String msgHeader = "";
        if (onlineState == Constants.ONLINE_STATUS_UNDEF || onlineState == Constants.ONLINE_STATUS_OFFLINE) {
            msgHeader = rb.getString("comm.removevc.header_offline");
        } else {
            msgHeader = rb.getString("comm.removevc.header_online");
        }

        String msgstr = msgHeader + units + refVcs + teaserText;

        int i = JOptionPane.showConfirmDialog(UIConstants.getMainFrame(), msgstr, rb.getString("dialog.title"),
                JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

        if (i == JOptionPane.YES_OPTION) {
            if (onlineState == Constants.ONLINE_STATUS_UNDEF
                    || onlineState == Constants.ONLINE_STATUS_OFFLINE) {
                getClientService().removeViewComponent(Integer.valueOf(intViewComponentId), true);
                /*
                 * } else { // nothing at the moment, the code for here is
                 * currently in PanTree actionViewComponentPerformed
                 */
            }
            retVal = true;
        }
    } catch (Exception exe) {
        log.error("Error removing vc", exe);
    }

    if (retVal) {
        try {
            checkOutPages.remove(new Integer(getViewComponent(intViewComponentId).getReference()));
        } catch (Exception exe) {
        }
        UIConstants.setStatusInfo(rb.getString("comm.removevc.statusinfo"));
    }
    return retVal;
}

From source file:hydrograph.engine.core.xmlparser.parametersubstitution.ParameterSubstitutor.java

private void substituteMutable(StringBuilder mutable, Stack<String> unresolvedParameters) {

    int startIndex = mutable.indexOf(VARIABLE_PREFIX);
    int endIndex = mutable.indexOf(VARIABLE_SUFFIX, startIndex);

    // return if nothing to substitute
    if (startIndex == -1 || endIndex == -1) {
        return;/*from   ww  w.j av  a2s.  c o m*/
    }

    // get parameter name
    String parameterName = mutable.substring(startIndex + VARIABLE_PREFIX.length(), endIndex);

    // raise exception if parameter name is blank
    if (parameterName == null || parameterName.trim().length() == 0) {
        throw new ParameterSubstitutorException("Parameter name can not be blank. Please correct.");
    }

    parameterName = parameterName.trim();

    String parameterValue = null;

    if (resolvedParameterCache.containsKey(parameterName)) {
        // obtain value from cache if already present
        parameterValue = resolvedParameterCache.get(parameterName);
        LOG.info("cache used for " + parameterName);
    } else {

        // check if the parameter is already on the stack then raise
        // exception
        // that it is circular substitution
        if (unresolvedParameters.search(parameterName) != -1) {
            throw new ParameterSubstitutorException("Found a circular depencency between parameter "
                    + parameterName + " and " + unresolvedParameters.peek()
                    + ". Both are referencing each other and cannot be resolved. Please correct.");
        }

        // get parameter value
        parameterValue = parameterBank.getParameter(parameterName);

        // if value is null then raise exception
        if (parameterValue == null) {
            throw new ParameterSubstitutorException(
                    "No value is found for the parameter " + parameterName + " to substitute");
        }

        // if parameter key to be substituted is in quotes("") then escape
        // special characters from its value
        if (isParameterPresentInQuotes(mutable, startIndex, endIndex)) {
            parameterValue = StringEscapeUtils.escapeXml(parameterValue);
        }

        // add current parameter to stack to check for circular loop later
        unresolvedParameters.push(parameterName);

        // check of substitution if there is a parameter reference in
        // parameter
        // value(internal substitution)
        parameterValue = substitute(parameterValue, unresolvedParameters);

        // remove parameter from stack as soon as it is resolved
        unresolvedParameters.pop();

        // add resolved value to cache
        resolvedParameterCache.put(parameterName, parameterValue);
    }
    // delete parameter syntax
    mutable.delete(startIndex, endIndex + VARIABLE_SUFFIX.length());

    // insert parameter value
    mutable.insert(startIndex, parameterValue);

    // check for next substitution and do it if available
    substituteMutable(mutable, unresolvedParameters);

}

From source file:com.multimedia.service.wallpaper.CmsWallpaperService.java

@Override
public void optimizeWallpaperCategories(Long[] id_pages) {
    HashMap<Long, Pages> page_ids = new HashMap<Long, Pages>();
    List<Wallpaper> wallpapers;
    StringBuilder title;
    String name;/*from w w  w . java  2  s  .c o  m*/
    StringBuilder tags;
    Random r = new Random();
    Pages page;
    int layer;

    for (int i = 0; i < id_pages.length; i++) {
        wallpapers = wallpaper_service.getByPropertiesValueOrdered(null, WALLPAPER_OPTIMIZED_CATEGORY_WHERE,
                new Object[] { id_pages[i], Boolean.FALSE, Boolean.FALSE }, null, null);
        if (wallpapers.size() > 0) {
            //getting all parents with optimization
            Long id_pages_tmp = id_pages[i];
            while (id_pages_tmp != null && !page_ids.containsKey(id_pages_tmp)) {
                Object[] page_a = (Object[]) pages_service.getSinglePropertyU("id, id_pages, name", "id",
                        id_pages_tmp);
                Pages page_o = new Pages();
                page_o.setId((Long) page_a[0]);
                page_o.setId_pages((Long) page_a[1]);
                page_o.setName((String) page_a[2]);
                page_o.setPseudonyms(pages_pseudo_service.getByPropertiesValueOrdered(null, PAGES_PSEDO_WHERE,
                        new Object[] { page_o.getId(), Boolean.TRUE }, null, null));
                page_ids.put(page_o.getId(), page_o);
                id_pages_tmp = page_o.getId_pages();
            }

            boolean rop_set = false;
            for (Wallpaper p : wallpapers) {
                //System.out.println("id="+p.getId()+"; optimized");
                title = new StringBuilder();
                name = null;
                tags = new StringBuilder();
                layer = 0;
                rop_set = false;
                id_pages_tmp = id_pages[i];
                while (id_pages_tmp != null) {
                    page = page_ids.get(id_pages_tmp);
                    if (!page.getPseudonyms().isEmpty()) {
                        int num = r.nextInt(page.getPseudonyms().size());
                        String ROP = page.getPseudonyms().get(num).getText();
                        if (ROP != null && !ROP.equals("")) {
                            if (!rop_set) {
                                name = ROP;
                                rop_set = true;
                            } else {
                                title.insert(0, " - ");
                            }
                            title.insert(0, ROP);
                        } else if (layer == 0) {
                            name = page.getName();
                        }

                        if (layer != 0) {
                            tags.insert(0, ", ");
                        }
                        tags.insert(0, page.getName());
                        layer++;
                    }

                    id_pages_tmp = page.getId_pages();
                }

                p.setDescription(name);
                p.setTags(tags.toString());
                p.setTitle(title.toString());
                p.setOptimized(Boolean.TRUE);
            }
        }
    }
}

From source file:org.sakaiproject.reports.logic.impl.ReportsManagerImpl.java

public StringBuilder replaceForMultiSet(StringBuilder inQuery, List reportParams) {
    if (reportParams == null) {
        return inQuery;
    }//from  w w w  . j  a v  a2  s . c  o m
    Iterator iter = reportParams.iterator();
    //   loop through all the parameters and find in query for replacement
    while (iter.hasNext()) {

        //   get the paremeter and associated parameter definition
        ReportParam rp = (ReportParam) iter.next();
        ReportDefinitionParam rdp = rp.getReportDefinitionParam();
        if (ReportDefinitionParam.VALUE_TYPE_MULTI_OF_SET.equals(rdp.getValueType())
                || ReportDefinitionParam.VALUE_TYPE_MULTI_OF_QUERY.equals(rdp.getValueType())) {

            if (rp.getListValue().size() > 1) {
                int index = inQuery.indexOf("(?)");
                inQuery.delete(index, index + 3);
                StringBuilder tempString = new StringBuilder("(");
                for (int i = 0; i < rp.getListValue().size(); i++) {
                    tempString.append("?,");
                }
                tempString.delete(tempString.length() - 1, tempString.length());
                tempString.append(") ");
                inQuery.insert(index, tempString);
            }
        }
    }
    return inQuery;
}

From source file:com.pari.nm.utils.db.ReportDBHelper.java

private static Map<String, String> createQualifiedMap(Map<String, String> mapOfConditions, String qualifier) {
    // Create new map and return it (if we update this map and its used some where else, things might break..)
    Map<String, String> qualifiedMap = new HashMap<>();
    if (mapOfConditions != null) {
        for (Entry<String, String> entry : mapOfConditions.entrySet()) {
            String value = entry.getValue();
            if (value.startsWith("UPPER(")) {
                StringBuilder sb = new StringBuilder(value);
                sb.insert("UPPER(".length(), qualifier + ".");
                qualifiedMap.put(entry.getKey(), sb.toString());
            } else if (value.startsWith("REGEXP_LIKE(")) {
                StringBuilder sb = new StringBuilder(value);
                sb.insert("REGEXP_LIKE(".length(), qualifier + ".");
                qualifiedMap.put(entry.getKey(), sb.toString());
            }/*from   www  . ja  v  a  2  s  .  com*/
        }
    }
    return qualifiedMap;
}

From source file:ca.nengo.model.impl.ProjectionImpl.java

public String toScript(HashMap<String, Object> scriptData) throws ScriptGenException {

    StringBuilder py = new StringBuilder();

    String pythonNetworkName = scriptData.get("prefix") + getNetwork().getName()
            .replaceAll("\\p{Blank}|\\p{Punct}", ((Character) scriptData.get("spaceDelim")).toString());

    py.append(String.format("%1s.connect(", pythonNetworkName));

    StringBuilder originNodeFullName = new StringBuilder();
    Origin tempOrigin = myOrigin;/*  w  w w .j  ava2s. c  om*/

    while (tempOrigin instanceof OriginWrapper) {
        originNodeFullName.append(tempOrigin.getNode().getName() + ".");
        tempOrigin = ((OriginWrapper) tempOrigin).getWrappedOrigin();
    }

    originNodeFullName.append(tempOrigin.getNode().getName());

    py.append("\'" + originNodeFullName + "\'");

    StringBuilder terminationNodeFullName = new StringBuilder();
    Termination tempTermination = myTermination;

    while (tempTermination instanceof TerminationWrapper) {
        terminationNodeFullName.append(tempTermination.getNode().getName() + ".");
        tempTermination = ((TerminationWrapper) tempTermination).getWrappedTermination();
    }

    terminationNodeFullName.append(tempTermination.getNode().getName());

    py.append(", \'" + terminationNodeFullName + "\'");

    DecodedTermination dTermination;
    StringBuilder transformString = new StringBuilder();

    transformString.append('[');
    if (tempTermination instanceof DecodedTermination) {
        dTermination = (DecodedTermination) tempTermination;
        transformString.append(getTransformScript(dTermination, "transform = ".length()));
    } else if (tempTermination instanceof EnsembleTermination && tempTermination.getNode().getClass()
            .getCanonicalName() == "org.python.proxies.nef.array$NetworkArray$6") {
        boolean first = true;
        for (Node node : tempTermination.getNode().getChildren()) {
            if (first) {
                first = false;
            } else {
                transformString.append(",\n" + StringUtils.repeat(" ", "transform = ".length() + 1));
            }

            // this relies on the decoded terminations in the child nodes having the 
            // same name as the ensemble termination that contains them
            try {
                dTermination = (DecodedTermination) node.getTermination(tempTermination.getName());
            } catch (Exception e) {
                dTermination = null;
            }

            transformString.append(getTransformScript(dTermination, "transform = ".length() + 1));
        }
    } else {
        throw new ScriptGenException(
                "Trying to generate script of non decoded termination which is not supported.");
    }

    transformString.append("]\n");

    py.insert(0, "transform = " + transformString.toString());
    py.append(", transform=transform");

    // Now handle origin function if there is one

    if (!(tempOrigin.getNode() instanceof FunctionInput)) {
        DecodedOrigin dOrigin;
        if (tempOrigin instanceof DecodedOrigin) {
            dOrigin = (DecodedOrigin) tempOrigin;
        } else if (tempOrigin.getClass().getCanonicalName() == "org.python.proxies.nef.array$ArrayOrigin$5"
                && tempOrigin.getNode().getClass()
                        .getCanonicalName() == "org.python.proxies.nef.array$NetworkArray$6") {
            Node node = tempOrigin.getNode().getChildren()[0];
            try {
                dOrigin = (DecodedOrigin) node.getOrigin(tempOrigin.getName());
            } catch (StructuralException e) {
                dOrigin = null;
            }
        } else {
            throw new ScriptGenException(
                    "Trying to generate script of non decoded origin which is not supported.");
        }

        String funcString = getFunctionScript(dOrigin);

        if (!funcString.isEmpty()) {
            py.insert(0, "    return [" + funcString + "]\n\n");
            py.insert(0, "def function(x):\n");

            py.append(", func=function");
        }
    }

    py.append(")\n\n");

    return py.toString();
}

From source file:com.sciaps.view.SpectrumShotPanel.java

private void doSpectrumNormalization() {

    BackgroundTask.runBackgroundTask(new BackgroundTask() {

        private JDialog mDialog;
        private JProgressBar mProgress;

        @Override/*w  w w. jav  a  2  s. c om*/
        public void onBefore() {
            mProgress = new JProgressBar();
            mProgress.setIndeterminate(true);

            mDialog = new JDialog(Constants.MAIN_FRAME);
            mDialog.setLocationRelativeTo(Constants.MAIN_FRAME);
            mDialog.setAlwaysOnTop(true);
            mDialog.setResizable(false);
            mDialog.setContentPane(mProgress);
            mDialog.setSize(400, 100);
            mDialog.setVisible(true);
        }

        @Override
        public void onBackground() {

            int[] selectedRow = getSelectedRows();
            if (selectedRow == null || selectedRow.length == 0) {
                return;
            }

            final ArrayList<SpectrumShotItem> tmpList = new ArrayList<SpectrumShotItem>();
            final StringBuilder errMsg = new StringBuilder();

            SpectrumNormalization spectrumNormalization = new SpectrumNormalization();
            for (int rowIndex = 0; rowIndex < selectedRow.length; rowIndex++) {
                SpectrumShotItem selectedItem = shotListTableModel_.getRow(selectedRow[rowIndex]);

                String name = selectedItem.getName();
                name = name + "N";

                if (selectedItem.getSeriesDataType() != SpectrumShotItem.NORMALIZED) {

                    Spectrum normalizedSpectrum = null;
                    if (selectedItem.getSeriesDataType() == SpectrumShotItem.BG_REMOVED) {
                        normalizedSpectrum = spectrumNormalization
                                .normalize((RawDataSpectrum) selectedItem.getShot());
                    } else {
                        RawDataSpectrum tempSpectrum = doBackgroundRemoval(selectedItem.getShot());
                        normalizedSpectrum = doSpectrumNormalization(tempSpectrum);
                    }

                    if (normalizedSpectrum != null) {
                        SpectrumShotItem shotItem = new SpectrumShotItem(name);
                        shotItem.setShot(normalizedSpectrum, SpectrumShotItem.NORMALIZED);
                        tmpList.add(shotItem);
                    } else {
                        errMsg.append(name).append("\n");
                    }

                } else {
                    errMsg.append(name).append("\n");
                }
            }

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    for (SpectrumShotItem shot : tmpList) {
                        shotListTableModel_.addRow(0, shot);
                    }

                    if (tmpList.isEmpty() == false) {
                        shotListTableModel_.showSeries(0);
                    }

                    if (errMsg.length() > 0) {
                        errMsg.insert(0, "The following shot(s) already exist, skipped:\n");
                        showErrorDialog(errMsg.toString());
                    }

                }
            });

        }

        @Override
        public void onAfter() {
            mDialog.setVisible(false);
        }
    });
}