Example usage for java.lang StringBuffer substring

List of usage examples for java.lang StringBuffer substring

Introduction

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

Prototype

@Override
public synchronized String substring(int start, int end) 

Source Link

Usage

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DataBaseInitializer.java

/**
 * To execute the table creation script depending on the datasource user using
 *
 * @throws DashboardPortalException/*ww  w.j  a va2  s  .  com*/
 */
private void executeSQLScript() throws DashboardPortalException {
    String databaseType;
    try {
        databaseType = getDatabaseType(getDBConnection());
    } catch (DashboardPortalException e) {
        throw new DashboardPortalException("Error occurred while getting database type", e);
    }
    if ("oracle".equals(databaseType)) {
        delimiter = "/";
    }

    String dbScriptLocation = getDbScriptLocation(databaseType);
    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbScriptLocation);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.startsWith("//")) {
                continue;
            }
            if (line.startsWith("--")) {
                continue;
            }
            StringTokenizer st = new StringTokenizer(line);
            if (st.hasMoreTokens()) {
                String token = st.nextToken();
                if ("REM".equalsIgnoreCase(token)) {
                    continue;
                }
            }

            sql.append(" ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (line.contains("--")) {
                sql.append("\n");
            }
            if ((checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } catch (IOException e) {
        throw new DashboardPortalException(
                "Error occurred while executing SQL script for creating Dashboard Server database", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                log.error("Error occurred while closing stream for Identity SQL script", e);
            }
        }
    }
}

From source file:ca.uhn.fhir.rest.server.IncomingRequestAddressStrategy.java

@Override
public String determineServerBase(ServletContext theServletContext, HttpServletRequest theRequest) {
    String requestFullPath = StringUtils.defaultString(theRequest.getRequestURI());

    String servletPath;//w w w. j a va  2 s.c  o  m
    if (myServletPath != null) {
        servletPath = myServletPath;
    } else {
        servletPath = StringUtils.defaultString(theRequest.getServletPath());
    }

    StringBuffer requestUrl = theRequest.getRequestURL();
    String servletContextPath = StringUtils.defaultString(theRequest.getContextPath());

    String requestPath = requestFullPath.substring(servletContextPath.length() + servletPath.length());
    if (requestPath.length() > 0 && requestPath.charAt(0) == '/') {
        requestPath = requestPath.substring(1);
    }

    int startOfPath = requestUrl.indexOf("//");
    int requestUrlLength = requestUrl.length();

    if (startOfPath != -1 && (startOfPath + 2) < requestUrlLength) {
        startOfPath = requestUrl.indexOf("/", startOfPath + 2);
    }
    if (startOfPath == -1) {
        startOfPath = 0;
    }

    int contextIndex;
    if (servletPath.length() == 0 || servletPath.equals("/")) {
        if (requestPath.length() == 0) {
            contextIndex = requestUrlLength;
        } else {
            contextIndex = requestUrl.indexOf(requestPath, startOfPath);
        }
    } else {
        //servletContextPath can start with servletPath 
        contextIndex = requestUrl.indexOf(servletPath + "/", startOfPath);
        if (contextIndex == -1) {
            contextIndex = requestUrl.indexOf(servletPath, startOfPath);
        }
    }

    String fhirServerBase;
    int length = contextIndex + servletPath.length();
    if (length > requestUrlLength) {
        length = requestUrlLength;
    }
    fhirServerBase = requestUrl.substring(0, length);
    return fhirServerBase;
}

From source file:org.apache.james.mime4j.MimeStreamParser.java

/**
 * Parses a header.// w ww.j av a  2  s . c o m
 * 
 * @param is the stream to parse.
 * @return a <code>BodyDescriptor</code> describing the body following 
 *         the header.
 */
private BodyDescriptor parseHeader(InputStream is) throws IOException {
    BodyDescriptor bd = new BodyDescriptor(
            bodyDescriptors.isEmpty() ? null : (BodyDescriptor) bodyDescriptors.getFirst());

    handler.startHeader();

    int lineNumber = rootStream.getLineNumber();

    StringBuffer sb = new StringBuffer();
    int curr = 0;
    int prev = 0;
    while ((curr = is.read()) != -1) {
        if (curr == '\n' && (prev == '\n' || prev == 0)) {
            /*
             * [\r]\n[\r]\n or an immediate \r\n have been seen.
             */
            sb.deleteCharAt(sb.length() - 1);
            break;
        }
        sb.append((char) curr);
        prev = curr == '\r' ? prev : curr;
    }

    if (curr == -1 && log.isWarnEnabled()) {
        log.warn("Line " + rootStream.getLineNumber() + ": Unexpected end of headers detected. "
                + "Boundary detected in header or EOF reached.");
    }

    int start = 0;
    int pos = 0;
    int startLineNumber = lineNumber;
    while (pos < sb.length()) {
        while (pos < sb.length() && sb.charAt(pos) != '\r') {
            pos++;
        }
        if (pos < sb.length() - 1 && sb.charAt(pos + 1) != '\n') {
            pos++;
            continue;
        }

        if (pos >= sb.length() - 2 || fieldChars.get(sb.charAt(pos + 2))) {

            /*
             * field should be the complete field data excluding the 
             * trailing \r\n.
             */
            String field = sb.substring(start, pos);
            start = pos + 2;

            /*
             * Check for a valid field.
             */
            int index = field.indexOf(':');
            boolean valid = false;
            if (index != -1 && fieldChars.get(field.charAt(0))) {
                valid = true;
                String fieldName = field.substring(0, index).trim();
                for (int i = 0; i < fieldName.length(); i++) {
                    if (!fieldChars.get(fieldName.charAt(i))) {
                        valid = false;
                        break;
                    }
                }

                if (valid) {
                    handler.field(field);
                    bd.addField(fieldName, field.substring(index + 1));
                }
            }

            if (!valid && log.isWarnEnabled()) {
                log.warn("Line " + startLineNumber + ": Ignoring invalid field: '" + field.trim() + "'");
            }

            startLineNumber = lineNumber;
        }

        pos += 2;
        lineNumber++;
    }

    handler.endHeader();

    return bd;
}

From source file:org.apache.phoenix.pherf.util.GoogleChartGenerator.java

/**
 * Render results as Google charts/*w  w  w.j  a v  a  2  s. co m*/
 * @throws FileNotFoundException
 * @throws UnsupportedEncodingException
 */
private void renderAsGoogleChartsHTML() throws FileNotFoundException, UnsupportedEncodingException {
    String lastKeyPrefix = "";
    StringBuffer sb = new StringBuffer();
    for (String label : labels) {
        sb.append("dataTable.addColumn('number', '" + label + "');\n");
        sb.append("dataTable.addColumn({type: 'string', role: 'tooltip', 'p': {'html': true}});\n");
    }
    sb.append("dataTable.addRows([\n");
    for (Map.Entry<String, DataNode> dn : datanodes.entrySet()) {
        String currentKeyPrefix = dn.getKey().substring(0, dn.getKey().indexOf('|'));
        if (!lastKeyPrefix.equalsIgnoreCase(currentKeyPrefix) && lastKeyPrefix != "") {
            sb.append(getBlankRow());
        }
        lastKeyPrefix = currentKeyPrefix;
        sb.append("['" + dn.getKey() + "'");
        for (Map.Entry<String, Node> nodeSet : dn.getValue().getDataSet().entrySet()) {
            sb.append(", " + nodeSet.getValue().getMinTime());
            sb.append(",'" + getToolTipAsHTML(dn.getValue().getDataSet()) + "'");
        }
        sb.append("],\n");
    }
    String summaryFile = PherfConstants.create().getProperty("pherf.default.summary.file");
    String title = labels[0];
    PrintWriter writer = new PrintWriter(summaryFile, "UTF-8");

    writer.println(StaticGoogleChartsRenderingData.HEADER.replace("[title]", title));
    writer.println(sb.substring(0, sb.length() - 2) + "\n]);");
    String thresholdString = Math.round((threshold * 100)) + "%";
    String footer = StaticGoogleChartsRenderingData.FOOTER.replace("[summary]",
            ((verifyWithinThreshold(threshold) == true ? "<font color=green>PASSED | Results are within "
                    : "<font color=red>FAILED | Results are outside ")) + "set threshold of " + thresholdString
                    + "</font><br>" + new SimpleDateFormat("yyyy/MM/dd ha z").format(new Date()));
    footer = footer.replace("[title]", title);
    writer.println(footer);
    writer.close();
}

From source file:org.sakaiproject.signup.tool.downloadEvents.EventWorksheet.java

private String getIds(List<SignupAttendee> attendees) {
    if (attendees == null)
        return "";

    StringBuffer sb = new StringBuffer();
    for (SignupAttendee att : attendees) {
        sb.append(sakaiFacade.getUser(att.getAttendeeUserId()).getDisplayId());
        sb.append("\n");
    }/*w  ww  .j av a2  s . c  o m*/
    /* remove the last'\n' one */
    return sb.length() > 1 ? sb.substring(0, sb.length() - 1) : "";
}

From source file:org.wso2.mobile.utils.persistence.EMMDBInitializer.java

private void executeSQLScript() throws Exception {
    String databaseType = EMMDBInitializer.getDatabaseType(dataSource.getConnection());
    boolean keepFormat = false;
    if ("oracle".equals(databaseType)) {
        delimiter = "/";
    } else if ("db2".equals(databaseType)) {
        delimiter = "/";
    } else if ("openedge".equals(databaseType)) {
        delimiter = "/";
        keepFormat = true;//from ww  w.j  a v a  2 s  . c  o  m
    }

    String dbScriptLocation = getDbScriptLocation(databaseType);

    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbScriptLocation);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!keepFormat) {
                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("--")) {
                    continue;
                }
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    if ("REM".equalsIgnoreCase(token)) {
                        continue;
                    }
                }
            }
            sql.append(keepFormat ? "\n" : " ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (!keepFormat && line.contains("--")) {
                sql.append("\n");
            }
            if ((checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } catch (IOException e) {
        log.error("Error occurred while executing SQL script for creating emm database", e);
        throw new Exception("Error occurred while executing SQL script for creating emm database", e);

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:org.wso2.carbon.social.sql.SocialDBInitilizer.java

private void executeSQLScript() throws Exception {
    String databaseType = SocialDBInitilizer.getDatabaseType(dataSource.getConnection());
    log.info("Executing DB script for :" + databaseType);
    boolean keepFormat = false;
    if ("oracle".equals(databaseType)) {
        delimiter = "/";
    } else if ("db2".equals(databaseType)) {
        delimiter = "/";
    } else if ("openedge".equals(databaseType)) {
        delimiter = "/";
        keepFormat = true;/*from  w w w.  j a va 2 s .  c  o  m*/
    }

    String dbScriptLocation = getDbScriptLocation(databaseType);

    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbScriptLocation);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!keepFormat) {
                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("--")) {
                    continue;
                }
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    if ("REM".equalsIgnoreCase(token)) {
                        continue;
                    }
                }
            }
            sql.append(keepFormat ? "\n" : " ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (!keepFormat && line.contains("--")) {
                sql.append("\n");
            }
            if ((checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } catch (IOException e) {
        log.error("Error occurred while executing SQL script for creating SOCIAL database", e);
        throw new Exception("Error occurred while executing SQL script for creating SOCIAL database", e);

    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String[] splitCommaSeparatedString(String toSeparate) {

    if (toSeparate == null || toSeparate == "")
        return null;

    List list = new ArrayList();
    String[] strArr = new String[1]; //just do determine the type of the array in list.toArray(Object[] o)

    StringBuffer sb = new StringBuffer(toSeparate);
    for (int i = 0; i < sb.length(); i++) {
        if (sb.charAt(i) == ' ')
            sb.deleteCharAt(i);/*from ww w  .j a  v  a2s. co  m*/
    }
    int start = 0;
    for (int i = 0; i < sb.length(); i++) {
        if (sb.charAt(i) == ',' || i == sb.length() - 1) {
            list.add(sb.substring(start, i == sb.length() - 1 ? i + 1 : i));
            start = i + 1;
        }
    }

    Object[] objArr = null;
    objArr = list.toArray(strArr);
    return (String[]) objArr;
}

From source file:org.wso2.carbon.identity.application.common.persistence.IdentityApplicationDBInitializer.java

private void executeSQLScript() throws IdentityApplicationManagementException, SQLException, IOException {

    String databaseType = getDatabaseType(dataSource.getConnection());
    if (databaseType == null) {
        String msg = "Unsupported database: Database will not be created automatically by the Carbon Server. "
                + "Please create the database using appropriate database scripts for the database.";
        log.warn(msg);/*from  w ww .  j  a v  a2 s.  c o m*/
    }

    boolean keepFormat = false;

    if ("oracle".equals(databaseType)) {
        delimiter = "/";
    } else if ("db2".equals(databaseType)) {
        delimiter = "/";
    }

    String dbScriptLocation = getDbScriptLocation(databaseType);
    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbScriptLocation);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (!keepFormat) {
                if (line.startsWith("//")) {
                    continue;
                }
                if (line.startsWith("--")) {
                    continue;
                }
                StringTokenizer st = new StringTokenizer(line);
                if (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    if ("REM".equalsIgnoreCase(token)) {
                        continue;
                    }
                }
            }
            sql.append(keepFormat ? "\n" : " ").append(line);

            // SQL defines "--" as a comment to EOL
            // and in Oracle it may contain a hint
            // so we cannot just remove it, instead we must end it
            if (!keepFormat && line.contains("--")) {
                sql.append("\n");
            }
            if ((checkStringBufferEndsWith(sql, delimiter))) {
                executeSQL(sql.substring(0, sql.length() - delimiter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString());
        }
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

From source file:org.wso2.carbon.dashboard.portal.core.datasource.DSDataSourceManager.java

/**
 * To execute the table creation script depending on the datasource user using
 *
 * @throws DashboardPortalException//from w ww. ja v  a2s  .c o m
 */
private void executeScript() throws DashboardPortalException {
    String databaseType;
    try {
        databaseType = dataSource.getConnection().getMetaData().getDatabaseProductName().toLowerCase();
    } catch (SQLException e) {
        throw new DashboardPortalException("Error occurred while getting database type", e);
    }
    if (databaseType.equalsIgnoreCase(DataSourceConstants.MSSQL_PRODUCT_NAME)) {
        databaseType = DataSourceConstants.MSSQL_SCRIPT_NAME;
    }
    if (databaseType.equalsIgnoreCase(DataSourceConstants.ORACLE_SCRIPT_NAME)
            || databaseType.equalsIgnoreCase(DataSourceConstants.DB2_SCRIPT_NAME)
            || databaseType.equalsIgnoreCase(DataSourceConstants.ORACLE_RAC_SCRIPT_NAME)) {
        delimeter = "/";
    }
    String dbScriptLocation = getDbScriptLocation(databaseType);
    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;

    try {
        InputStream is = new FileInputStream(dbScriptLocation);
        reader = new BufferedReader(new InputStreamReader(is));
        String line;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.startsWith("//")) {
                continue;
            }
            if (line.startsWith("--")) {
                continue;
            }
            StringTokenizer st = new StringTokenizer(line);
            if (st.hasMoreTokens()) {
                String token = st.nextToken();
                if ("REM".equalsIgnoreCase(token)) {
                    continue;
                }
            }
            sql.append(" ").append(line);
            if (line.contains("--")) {
                sql.append("\n");
            }
            if (sql.toString().endsWith(delimeter)) {
                executeQuery(sql.substring(0, sql.length() - delimeter.length()));
                sql.replace(0, sql.length(), "");
            }
        }
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeQuery(sql.toString());
        }
    } catch (IOException e) {
        throw new DashboardPortalException(
                "Error occurred while executing SQL script for creating Dashboard Server database", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                log.error("Error occurred while closing stream for Identity SQL script", e);
            }
        }
    }
}