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:de.escalon.hypermedia.spring.Affordance.java

public String asHeader() {
    StringBuilder result = new StringBuilder();
    for (Map.Entry<String, List<String>> linkParamEntry : linkParams.entrySet()) {
        if (result.length() != 0) {
            result.append("; ");
        }/*from   www  .  ja  va2s  .  co m*/
        if ("rel".equals(linkParamEntry.getKey())) {
            result.append(linkParamEntry.getKey()).append("=");
            result.append("\"").append(StringUtils.collectionToDelimitedString(linkParamEntry.getValue(), " "))
                    .append("\"");
        } else {
            StringBuilder linkParams = new StringBuilder();
            for (String value : linkParamEntry.getValue()) {
                if (linkParams.length() != 0) {
                    linkParams.append("; ");
                }
                linkParams.append(linkParamEntry.getKey()).append("=");
                linkParams.append("\"").append(value).append("\"");
            }
            result.append(linkParams);

        }

    }

    String linkHeader = "<" + getHref() + ">; ";

    return result.insert(0, linkHeader).toString();
}

From source file:de.iteratec.iteraplan.businesslogic.service.SearchServiceImpl.java

private String modifyQueryString(String queryString) {
    StringBuilder modQueryString = new StringBuilder(queryString);
    // if whitespace included, don't modify
    if (!queryString.contains(" ")) {

        // if the String contains quotes, remove them if they are at the beginning or end
        if (queryString.contains("\"")) {
            if (queryString.endsWith("\"")) {
                modQueryString.deleteCharAt(queryString.length() - 1);
            }//from   w  ww  .j a v  a  2 s  .co  m
            if (queryString.charAt(0) == '"') {
                modQueryString.deleteCharAt(0);
            }
            // no further modification, return the string
            return modQueryString.toString();
        }

        // if the String contains no "*" surround it with "*"
        if (!queryString.contains("*")) {
            modQueryString.insert(0, '*');
            modQueryString.append('*');
        }
    }
    return modQueryString.toString();
}

From source file:com.hangum.tadpole.sql.util.sqlscripts.scripts.PostgreSQLDDLScript.java

@Override
public String getTriggerScript(TriggerDAO triggerDAO) throws Exception {
    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
    String objectName = triggerDAO.getTrigger();

    logger.debug("\n Trigger DDL Generation...");

    StringBuilder result = new StringBuilder("");

    HashMap<String, String> srcScriptList = (HashMap<String, String>) client.queryForObject("getTriggerScript",
            objectName);//  ww  w .  ja va 2  s .  co  m

    result.append("DROP TRIGGER IF EXISTS " + objectName + " ON " + srcScriptList.get("event_table") + ";\n\n");

    result.append("CREATE TRIGGER " + objectName + "\n");
    result.append(srcScriptList.get("action_timing") + " ");
    result.append(srcScriptList.get("event_name") + " ON ");
    result.append(srcScriptList.get("event_table") + " \n ");
    result.append("FOR EACH " + srcScriptList.get("action_orientation") + " ");

    String action_statement = srcScriptList.get("action_statement");

    result.append(action_statement + " \n ");

    if (action_statement.trim().toUpperCase().startsWith("EXECUTE PROCEDURE")) {
        // trigger function script

        String funcName = action_statement.replace("EXECUTE PROCEDURE", "").trim();
        funcName = funcName.substring(0, funcName.lastIndexOf('('));

        result.insert(0, getFunctionScript(funcName.trim().toLowerCase()) + "\n\n");

    }

    return result.toString();
}

From source file:nl.strohalm.cyclos.controls.reports.statistics.graphs.StatisticalDataProducer.java

/**
 * gets the y-axis label. The label is adjusted for automatic scaling: if scaling was applied, the scalefactor is appended between parenthesis
 * (like "(x 1000)"). If units were used, the units are placed behind the scale factor number, inside the parenthesis, so like "(x 1000 units)".
 * @return the y-axis label for the graph.
 *///ww w  .  j  a v a2s.  c  o m
public String getY_axis() {
    if (scaleFactor == 0) {
        final StringBuilder sb = new StringBuilder();
        sb.append(y_axis);
        if (resultObject.getYAxisUnits().length() > 0) {
            sb.append("  ").append("(").append(resultObject.getYAxisUnits()).append(")");
        }
        return sb.toString();
    }
    // apply scaling suffix
    final String factorSign = (scaleFactor < 0) ? resultObject.getYAxisUnits() + "/" : "x";
    final int factor = (int) Math.pow(1000, Math.abs(scaleFactor));
    final StringBuilder sb = new StringBuilder();
    if (settings != null) {
        sb.append(settings.getNumberConverterForPrecision(0).toString(new BigDecimal(factor)));
    } else {
        sb.append(String.valueOf(factor));
    }
    sb.insert(0, factorSign).insert(0, "   (");
    if (scaleFactor > 0 && resultObject.getYAxisUnits().length() > 0) {
        sb.append(" ").append(resultObject.getYAxisUnits());
    }
    sb.append(")");
    sb.insert(0, y_axis);
    return sb.toString();
}

From source file:nl.mindef.c2sc.nbs.olsr.pud.uplink.server.logger.impl.DatabaseLoggerImpl.java

private void warnOnDuplicateNames(Map<String, List<Node>> nodeName2Nodes) {
    if (nodeName2Nodes == null) {
        return;//w  w w  .  ja  va 2  s. c o  m
    }

    for (Map.Entry<String, List<Node>> entry : nodeName2Nodes.entrySet()) {
        List<Node> mapping = entry.getValue();
        if (mapping.size() <= 1) {
            continue;
        }

        Collections.sort(mapping, new NodeNameComparatorOnIp());

        boolean warn = false;
        StringBuilder sb = new StringBuilder();
        for (Node node : mapping) {
            if (this.reportOnce.add(ReportSubject.DUPLICATE_NODE_NAME, entry.getKey(),
                    node.getMainIp().getHostAddress().toString())) {
                warn = true;
                sb.append("  ");
                sb.append(node.getMainIp().getHostAddress().toString());
                Sender sender = node.getSender();
                if (sender != null) {
                    sb.append(", received from ");
                    sb.append(sender.getIp().getHostAddress().toString());
                    sb.append(":");
                    sb.append(sender.getPort());
                }
                sb.append("\n");
            }
        }
        if (warn) {
            sb.insert(0, "\nDetected node(s) using existing name \"" + entry.getKey() + "\":\n");
            this.logger.warn(sb.toString());
        }
    }
}

From source file:com.alu.e3.logger.LogCollector.java

/**
 * Gets a specified number of most-recent log lines from the localhost's
 * rotated logs.//from w ww . ja v  a2s . co m
 * 
 * This method has been supplanted by the other log-collection methods in this class.
 * 
 * @param numLines
 * @return
 * @throws IOException
 */
public static String getLocalLogLines(LogFileSource logSource, int numLines) throws IOException {
    if (!LogFileSource.JAVA.equals(logSource) && !LogFileSource.SMX.equals(logSource)) {
        logger.warn("Unexpected log-source value: {}", logSource == null ? "(null)" : logSource);
        return null;
    }

    StringBuilder logLines = null;
    String logFilePath = LoggingUtil.getLocalLogFilePath(logSource);
    int lineCount = 0;

    File logDir = (new File(logFilePath)).getParentFile();
    if (!logDir.exists() || !logDir.isDirectory()) {
        return null;
    }

    // Try getting lines from the current log file(s) ...
    logLines = new StringBuilder();
    int logGen = 1;
    try {
        while (lineCount < numLines) {
            File logFile = new File(logFilePath + "." + String.valueOf(logGen));
            if (!logFile.exists()) {
                break;
            }
            String logContent = getTailOfFile(logFile, numLines - lineCount);
            logLines.insert(0, logContent);
            lineCount += lineCount(logContent);
            logGen++;
        }
    } catch (IOException ex) {
        logger.warn("Couldn't read from log file {}", logFilePath);
    }

    return LoggingResponseBuilder.logLinesToXml(LogFileSource.JAVA, E3Constant.localhost, logLines.toString());
}

From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java

/**
 * Search datasets containg param text in the metadata
 *
 * @param query The query object/*from   w w  w  .j  av  a 2s .c o m*/
 * @param limit maximum results to return
 * @param offset search begins from offset
 * @throws JackanException on error
 */
public synchronized SearchResults<CkanDataset> searchDatasets(CkanQuery query, int limit, int offset) {

    StringBuilder params = new StringBuilder();

    params.append("rows=").append(limit).append("&start=").append(offset);

    if (query.getText().length() > 0) {
        params.append("&q=");
        params.append(urlEncode(query.getText()));
    }

    StringBuilder fq = new StringBuilder();
    String fqPrefix = "";

    fqPrefix = appendNamesList(fqPrefix, "groups", query.getGroupNames(), fq);
    fqPrefix = appendNamesList(fqPrefix, "organization", query.getOrganizationNames(), fq);
    fqPrefix = appendNamesList(fqPrefix, "tags", query.getTagNames(), fq);
    fqPrefix = appendNamesList(fqPrefix, "license_id", query.getLicenseIds(), fq);

    if (fq.length() > 0) {
        params.append("&fq=").append(urlEncode(fq.insert(0, "(").append(")").toString()));
    }

    DatasetSearchResponse dsr;
    dsr = getHttp(DatasetSearchResponse.class, "/api/3/action/package_search?" + params.toString());

    if (dsr.success) {
        for (CkanDataset ds : dsr.result.getResults()) {
            for (CkanResource cr : ds.getResources()) {
                cr.setPackageId(ds.getId());
            }
        }
    }

    return dsr.result;
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

public static String encodeAmpersands(String htmlString) {
    StringBuilder htmlBuffer = new StringBuilder(htmlString);
    int ampLoc = -1;
    while ((ampLoc = htmlBuffer.indexOf("&", ampLoc + 1)) != -1) {
        //NOTE: this should work fine, but if it doesn't could try making sure all characters between & and ; are letters, that would qualify as an entity

        // found ampersand, is it already and entity? if not change it to &amp;
        int semiLoc = htmlBuffer.indexOf(";", ampLoc);
        if (semiLoc != -1) {
            // found a semi colon, if it has another & or an = before it, don't count it as an entity, otherwise it may be an entity, so skip it
            int eqLoc = htmlBuffer.indexOf("=", ampLoc);
            int amp2Loc = htmlBuffer.indexOf("&", ampLoc + 1);
            if ((eqLoc == -1 || eqLoc > semiLoc) && (amp2Loc == -1 || amp2Loc > semiLoc)) {
                continue;
            }/*from  w w  w  .j  a  va 2 s .  co  m*/
        }

        // at this point not an entity, no substitute with a &amp;
        htmlBuffer.insert(ampLoc + 1, "amp;");
    }
    return htmlBuffer.toString();
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.xmi.XmiContextProvider.java

@Override
public ItemContext getContext(EvaluationItem aItem, int aLeftSize, int aRightSize) throws IOException {
    Timer timer = new Timer();

    File base = new File(new File(corpusService.getRepositoryPath(), aItem.getCollectionId().toUpperCase()),
            XMI);/*from ww w . j av a 2 s . c  o m*/
    String docId = aItem.getDocumentId();
    JCasState state = jcasThreadLocal.get();
    // FIXME sometimes cas is not being reused (because of state.documentId==null - is this only
    // available for a limited timed?)
    if ((state.documentId == null) || (state.collectionId == null)
            || !StringUtils.equals(state.documentId, docId)
            || !StringUtils.equals(state.collectionId, aItem.getCollectionId())) {
        timer.start();

        InputStream is = null;
        try {
            // No need to reset the CAS - the XmiCasDeserializer does that
            is = new GZIPInputStream(new FileInputStream(new File(base, docId + ".xmi.gz")));
            XmiCasDeserializer.deserialize(is, state.jcas.getCas());
            state.documentId = aItem.getDocumentId();
            state.collectionId = aItem.getCollectionId();
        } catch (IllegalStateException e) {
            throw new IOException(e);
        } catch (SAXException e) {
            throw new IOException(e);
        } finally {
            closeQuietly(is);
        }

        timer.stop();
        log.debug("Reading the XMI took " + timer.getTime() + "ms");
    } else {
        log.debug("Reusing CAS");
    }

    timer.reset();
    timer.start();

    // text offset based
    String text = state.jcas.getDocumentText();

    // Absolute offsets
    int windowBegin = Math.max(0, (int) aItem.getBeginOffset() - aLeftSize);
    int windowEnd = Math.min(text.length(), (int) aItem.getEndOffset() + aRightSize);

    // Relative offsets
    int unitBegin = (int) aItem.getBeginOffset() - windowBegin;
    int unitEnd = (int) aItem.getEndOffset() - windowBegin;

    StringBuilder windowText = new StringBuilder(text.substring(windowBegin, windowEnd));

    List<Token> tokens = JCasUtil.selectCovered(state.jcas, Token.class, (int) aItem.getBeginOffset(),
            (int) aItem.getEndOffset());
    int unitEndDisplacement = 0;
    int matchEndDisplacement = 0;
    int matchBeginDisplacement = 0;

    boolean anyMatchSet = false;
    int matchBeginOffset = aItem.getOriginalTextMatchBegin();
    int matchEndOffset = aItem.getOriginalTextMatchEnd();

    if (aItem.isOriginalMatchSet()) {
        matchBeginOffset = aItem.getOriginalTextMatchBegin();
        matchEndOffset = aItem.getOriginalTextMatchEnd();
        anyMatchSet = true;
    } else if (aItem.isTokenMatchSet()) {
        matchBeginOffset = tokens.get(aItem.getTokenMatchBegin()).getBegin();
        matchEndOffset = tokens.get(aItem.getTokenMatchEnd()).getEnd();
        anyMatchSet = true;
    }

    Collections.reverse(tokens);
    // default: output pos with tokens
    if (outputPos) {
        for (Token t : tokens) {
            if (t.getPos() != null && t.getPos().getPosValue() != null) {
                String postfix = "/" + t.getPos().getPosValue();
                windowText.insert(t.getEnd() - windowBegin, postfix);
                unitEndDisplacement += postfix.length();
                if (anyMatchSet) {
                    if ((t.getEnd() <= matchEndOffset) && (t.getBegin() >= matchBeginOffset)) {
                        matchEndDisplacement += postfix.length();
                    }
                    if (t.getEnd() <= matchBeginOffset) {
                        matchBeginDisplacement += postfix.length();
                    }
                }
            }
        }
    }

    ItemContext ctx = new ItemContext(windowText.toString(), windowBegin, windowEnd, unitBegin,
            unitEnd + unitEndDisplacement);

    if (anyMatchSet) {
        ctx.setMatch(matchBeginOffset - windowBegin + matchBeginDisplacement,
                matchEndOffset - windowBegin + matchBeginDisplacement + matchEndDisplacement);
    }

    ctx.setTextLength(text.length());

    timer.stop();
    log.debug("Extracting the context took " + timer.getTime() + "ms");

    return ctx;
}

From source file:com.google.appinventor.components.runtime.FusiontablesControl.java

/**
 * Parses SQL API Create query into v1.0 a JSon string which is then submitted as a POST request
 * E.g., parses "/*from  w w  w . j a  va 2s .  c o m*/
 *   CREATE TABLE Notes (NoteField: STRING,  NoteLength: NUMBER, Date:DATETIME, Location:LOCATION)"
 * into :
 *  "CREATE TABLE " +
    "{\"columns\": [{\"name\": \"NoteField\",\"type\": \"STRING\"},{\"name\": \"NoteLength\",\"type\": \"NUMBER\"}," +
    "{\"name\": \"Location\",\"type\": \"LOCATION\"},{\"name\": \"Date\",\"type\": \"DATETIME\"}], " +
    "\"isExportable\": \"true\", \"name\": \"Notes\"}"
        
 * @param query
 * @return
 */
private String parseSqlCreateQueryToJson(String query) {
    Log.i(LOG_TAG, "parsetoJSonSqlCreate :" + query);
    StringBuilder jsonContent = new StringBuilder();
    query = query.trim();
    String tableName = query.substring("create table".length(), query.indexOf('(')).trim();
    String columnsList = query.substring(query.indexOf('(') + 1, query.indexOf(')'));
    String[] columnSpecs = columnsList.split(",");
    jsonContent.append("{'columns':[");
    for (int k = 0; k < columnSpecs.length; k++) {
        String[] nameTypePair = columnSpecs[k].split(":");
        jsonContent
                .append("{'name': '" + nameTypePair[0].trim() + "', 'type': '" + nameTypePair[1].trim() + "'}");
        if (k < columnSpecs.length - 1) {
            jsonContent.append(",");
        }
    }
    jsonContent.append("],");
    jsonContent.append("'isExportable':'true',");
    jsonContent.append("'name': '" + tableName + "'");
    jsonContent.append("}");

    jsonContent.insert(0, "CREATE TABLE ");

    Log.i(LOG_TAG, "result = " + jsonContent.toString());
    return jsonContent.toString();
}