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.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttp(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("") && !your_session_id.equals("none")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }// ww w  .  j  a v a  2s. co m
    con.setRequestProperty("Content-Type", contentType);
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("appmSamlSsoTokenId")) {
            return con.getHeaderField("Set-Cookie").split(";")[0].split("=")[1];
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie").split("=")[1].split(";")[0];
        } else {
            return response.toString();
        }
    }
    return null;
}

From source file:org.wso2.carbon.appmgt.sampledeployer.http.HttpHandler.java

public String doPostHttps(String backEnd, String payload, String your_session_id, String contentType)
        throws IOException {
    URL obj = new URL(backEnd);

    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    if (!your_session_id.equals("")) {
        con.setRequestProperty("Cookie", "JSESSIONID=" + your_session_id);
    }/*from w w  w  . j a va  2s . c  o  m*/
    if (!contentType.equals("")) {
        con.setRequestProperty("Content-Type", contentType);
    }
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(payload);
    wr.flush();
    wr.close();
    int responseCode = con.getResponseCode();
    if (responseCode == 200) {
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        if (your_session_id.equals("")) {
            String session_id = response.substring((response.lastIndexOf(":") + 3),
                    (response.lastIndexOf("}") - 2));
            return session_id;
        } else if (your_session_id.equals("header")) {
            return con.getHeaderField("Set-Cookie");
        }

        return response.toString();
    }
    return null;
}

From source file:org.latticesoft.util.common.ConvertUtil.java

/**
 * Parse an input string from a specified format and populate the
 * result into the object./*from   w  w w .j  a va 2  s .  c o  m*/
 * The specified format is in the following structure
 * ${name}<somechars>${name}...
 * E.g. ${volume,java.lang.Integer},${date,java.util.Date,yyyyMMdd}...
 * @param source the source input string
 * @param format the format of the input string
 * @param o the object to be populated
 * @param start the start tag
 * @param end the end tag
 * @return the List of params parsed
 */
public static Collection parse(String source, String format, Object o, String start, String end) {
    Map map = new HashMap();
    ArrayList a = new ArrayList();
    try {
        StringBuffer sb = new StringBuffer(format);
        int index1 = -1;
        int index2 = -1;
        int index3 = -1;
        String param = null;
        String text = null;
        do {
            param = null;
            text = null;
            index1 = sb.toString().indexOf(start, index2);
            if (index1 >= 0) {
                index2 = sb.toString().indexOf(end, index1 + start.length());
            }
            if (index1 < index2 && index1 > -1 && index2 > -1) {
                int from = index1 + start.length();
                int to = -1;
                if (index2 > sb.length()) {
                    to = sb.length();
                } else {
                    to = index2;// - end.length();
                }
                param = sb.substring(from, to);
            }
            if (index1 > index3 + 1) {
                text = sb.substring(index3 + 1, index1);
            }
            if (text != null) {
                Param p = Param.fromString(text);
                a.add(p);
            }
            if (index2 > 0) {
                index3 = index2;
            }
            if (param != null) {
                index2 += end.length();
                Param p = Param.fromString(param);
                a.add(p);
            }
        } while (param != null);
        if (sb.length() > index3) {
            text = sb.substring(index3, sb.length());
            Param p = Param.fromString(text);
            a.add(p);
        }
        // now parse the source string
        index1 = 0;
        index2 = 0;
        index3 = -1;
        for (int i = 0; i < a.size(); i++) {
            Param p = (Param) a.get(i);
            if (p.isParam()) {
                if (i + 1 < a.size()) {
                    Param nextP = (Param) a.get(i + 1);
                    index3 = source.indexOf(nextP.getValue(), index2);
                } else {
                    index3 = source.length();
                }
                if (index3 > index2) {
                    String s = source.substring(index2, index3);
                    p.setValue(s);
                    Object value = ClassUtil.newInstance(p.getType(), p.getValue(), p.getFormat());
                    map.put(p.getName(), value);
                }
            } else {
                index1 = source.indexOf(p.getValue(), index2);
                index2 = index1 + p.getValue().length();
            }
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    }
    try {
        BeanUtils.populate(o, map);
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    }
    return a;
}

From source file:org.apache.airavata.registry.tool.DBMigrator.java

private static void executeSQLScript(Connection conn, InputStream inputStream) throws Exception {
    StringBuffer sql = new StringBuffer();
    BufferedReader reader = null;
    try {/*from w w  w .  j a  v a2s. c o m*/
        reader = new BufferedReader(new InputStreamReader(inputStream));
        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.indexOf("--") >= 0) {
                sql.append("\n");
            }
            if ((checkStringBufferEndsWith(sql, delimiter))) {
                String sqlString = sql.substring(0, sql.length() - delimiter.length());
                executeSQL(sqlString, conn);
                sql.replace(0, sql.length(), "");
            }
        }
        System.out.println(sql.toString());
        // Catch any statements not followed by ;
        if (sql.length() > 0) {
            executeSQL(sql.toString(), conn);
        }
    } catch (IOException e) {
        logger.error("Error occurred while executing SQL script for creating Airavata database", e);
        throw new Exception("Error occurred while executing SQL script for creating Airavata database", e);
    } finally {
        if (reader != null) {
            reader.close();
        }

    }
}

From source file:com.clustercontrol.repository.factory.SearchNodeBySNMP.java

/**
 * SNMP???????16????????/*w  w  w .  ja v a  2 s.c o m*/
 */
private static String convStringFilessystem(String str) {
    if (str.matches("([0-9A-Fa-f]{2}\\s{0,1})+")) {
        try {
            //str????ASCII?16????
            //???????????
            char[] chars;
            short first;
            short second;
            chars = str.toCharArray();
            StringBuffer ret = new StringBuffer();

            for (int i = 0; i < chars.length;) {

                first = (short) (chars[i] - 48); //48?"0"????"1"1??
                second = (short) (chars[i + 1] - 48);

                if (second > 10) {
                    //16?A-F???????7??
                    //10  A(16)???("A"65)10??? 10 = "A"(65) - "0"(48) - 7
                    second -= 7;
                }

                ret.append((char) (first * 16 + second));

                i += 3;//1?"56 "?????????2??" "
            }

            m_log.info("DeviceSearch : Filesystem Name str = " + str + " convert to " + ret.substring(0, 3));
            return ret.substring(0, 3);
        } catch (Exception e) {
            m_log.warn("DeviceSearch : " + e.getMessage());
            return str;
        }
    } else {
        return str;
    }
}

From source file:org.etudes.component.app.melete.SpecialAccessDB.java

public void deleteSpecialAccess(List saList) throws Exception {
    Transaction tx = null;/*from   w  w w  . j  av  a2s  . c o  m*/
    SpecialAccess sa = null;
    String delAccessIds = null;
    StringBuffer allAccessIds = new StringBuffer("(");
    for (Iterator saIter = saList.iterator(); saIter.hasNext();) {
        Integer accessId = (Integer) saIter.next();
        allAccessIds.append(accessId.toString() + ",");
    }
    if (allAccessIds.lastIndexOf(",") != -1)
        delAccessIds = allAccessIds.substring(0, allAccessIds.lastIndexOf(",")) + " )";
    String delSpecialAccessStr = "delete SpecialAccess sa where sa.accessId in " + delAccessIds;
    try {
        Session session = getHibernateUtil().currentSession();
        tx = session.beginTransaction();
        int deletedEntities = session.createQuery(delSpecialAccessStr).executeUpdate();
        tx.commit();
    } catch (HibernateException he) {
        if (tx != null)
            tx.rollback();
        logger.error(he.toString());
        throw he;
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        logger.error(e.toString());
        throw e;
    } finally {
        try {
            hibernateUtil.closeSession();
        } catch (HibernateException he) {
            logger.error(he.toString());
            throw he;
        }
    }
}

From source file:com.hyron.poscafe.service.action.RecallAction.java

@Override
public boolean parseParams(List<VirtualKey> params) {
    StringBuffer tmpBuf = new StringBuffer();
    for (VirtualKey vk : params) {
        tmpBuf.append(vk.getValue().isEmpty() ? vk.getKeyType().getType() : vk.getValue());
    }//from w  w  w. ja va2 s .  c  o m

    Pattern pattern = Pattern.compile(regexp);
    Matcher matcher = pattern.matcher(tmpBuf);
    if (!matcher.matches()) {
        return false;
    }

    int pos = tmpBuf.indexOf("RECALL");
    String tmpStr = tmpBuf.substring(0, pos);
    recallTransNo = Long.valueOf(tmpStr);
    return true;
}

From source file:no.sesat.search.http.servlet.BoomerangServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse res)
        throws ServletException, IOException {

    // clients must not cache these requests
    res.setHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0");
    res.setHeader("Pragma", "no-cache"); // for old browsers
    res.setDateHeader("Expires", 0); // to be double-safe

    // entrails is the map of logging information
    final Map<String, Object> entrails = new HashMap<String, Object>();

    // request attribute to keep
    entrails.put("referer", req.getHeader("Referer"));
    entrails.put("method", req.getMethod());
    entrails.put("ipaddress", req.getRemoteAddr());
    entrails.put("user-agent", req.getHeader("User-Agent"));
    entrails.put("user-id", SearchServlet.getCookieValue(req, "SesamID"));
    entrails.put("user", SearchServlet.getCookieValue(req, "SesamUser"));

    if (req.getRequestURI().startsWith(CEREMONIAL)) {

        // ceremonial boomerang
        final StringBuffer url = req.getRequestURL();
        if (null != req.getQueryString()) {
            url.append('?' + req.getQueryString());
        }/*from  w  ww  .  j  ava2s. com*/

        // pick out the entrails
        final int boomerangStart = url.indexOf(CEREMONIAL) + CEREMONIAL.length();

        try {
            final String grub = url.substring(boomerangStart, url.indexOf("/", boomerangStart));
            LOG.debug(grub);

            // the url to return to
            final String destination = url
                    .substring(url.indexOf("/", url.indexOf(CEREMONIAL) + CEREMONIAL.length() + 1) + 1);

            // the grub details to add
            if (0 < grub.length()) {
                final StringTokenizer tokeniser = new StringTokenizer(grub, ";");
                while (tokeniser.hasMoreTokens()) {
                    final String[] entry = tokeniser.nextToken().split("=");
                    entrails.put(entry[0], 1 < entry.length ? entry[1] : entry[0]);
                }
            }
            entrails.put("boomerang", destination);
            kangerooGrub(entrails);

            LOG.debug("Ceremonial boomerang to " + destination.toString());

            if (ROBOTS.matcher(req.getHeader("User-agent")).find()) {
                // robots like permanent redirects. and we're not interested in their clicks so ok to cache.
                res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                res.setHeader("Location", destination.toString());
                res.setHeader("Connection", "close");

            } else {
                // default behaviour for users.
                res.sendRedirect(destination.toString());
            }

        } catch (StringIndexOutOfBoundsException sioobe) {
            // SEARCH-4668
            LOG.error("Boomerang url not to standard --> " + url);
            LOG.debug(sioobe.getMessage(), sioobe);
        }

    } else {

        // hunting boomerang, just grub, and the grub comes as clean parameters.
        final DataModel datamodel = (DataModel) req.getSession().getAttribute(DataModel.KEY);
        entrails.putAll(datamodel.getParameters().getValues());
        kangerooGrub(entrails);

    }

}

From source file:org.millr.slick.utils.TrimString.java

public TrimString(String input, int length, boolean soft) {

    LOGGER.info(">>>> Trimming String");

    // Replace basic HTML. Will break if HTML is malformed.
    String contentString = input.replaceAll("<[^>]*>", "");

    if (contentString == null || contentString.trim().isEmpty()) {
        LOGGER.info("String is empty");
        trimmedString = contentString;//from   w w  w.  j a va2 s  .  c o  m
    }

    try {
        StringBuffer sb = new StringBuffer(contentString);

        int desiredLength = length;
        int endIndex = sb.indexOf(" ", desiredLength);

        //If soft, remove three characters to make room for elipsis.
        if (soft) {
            desiredLength = length - 3;
            endIndex = sb.indexOf(" ", desiredLength);
            contentString = escapeHtml(sb.insert(endIndex, "...").substring(0, endIndex + 3));
        } else {
            contentString = escapeHtml(sb.substring(0, endIndex));
        }
    } catch (Exception e) {
        LOGGER.error("Exception: " + e.getMessage(), e);
    }
    trimmedString = contentString;
}

From source file:edu.stanford.junction.Junction.java

public URI getInvitationURI(String role) {
    URI uri = getBaseInvitationURI();

    Map<String, String> params = new HashMap<String, String>();
    if (role != null) {
        params.put("role", role);
    }//from w w  w  .  j a va2  s  .c o m
    mExtrasDirector.updateInvitationParameters(params);

    StringBuffer queryBuf = new StringBuffer("?");
    Set<String> keys = params.keySet();
    for (String key : keys) {
        try {
            queryBuf.append(
                    URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(params.get(key), "UTF-8") + "&");
        } catch (Exception e) {
        }
    }
    String queryStr = queryBuf.substring(0, queryBuf.length() - 1);

    try {
        uri = new URI(uri.toString() + queryStr);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return uri;
}