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) 

Source Link

Usage

From source file:com.jaspersoft.jasperserver.war.common.HeartbeatBean.java

public void contributeToHttpCall(PostMethod post) {
    post.addParameter("callCount", String.valueOf(callCount));
    post.addParameter("osName", osName);
    post.addParameter("osVersion", osVersion);
    post.addParameter("javaVendor", javaVendor);
    post.addParameter("javaVersion", javaVersion);
    post.addParameter("serverInfo", serverInfo);
    post.addParameter("productName", productName);
    post.addParameter("productVersion", productVersion);
    post.addParameter("dbName", dbName);
    post.addParameter("dbVersion", dbVersion);
    post.addParameter("serverLocale", Locale.getDefault().toString());

    try {/*from  w  ww  .  j  a  va 2 s  .  c  o  m*/
        post.addParameter("tenants", String.valueOf(tenantService.getNumberOfTenants(null)));
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Getting number of tenants failed.", e);
    }

    try {
        UserLocale[] userLocales = localesList.getUserLocales(Locale.getDefault());
        if (userLocales != null && userLocales.length > 0) {
            StringBuffer sbuffer = new StringBuffer();
            for (int i = 0; i < userLocales.length; i++) {
                sbuffer.append(", " + userLocales[i].getCode());
            }
            post.addParameter("userLocales", sbuffer.substring(2));
        }
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Getting user locales failed.", e);
    }

    clientInfoCache.contributeToHttpCall(post);

    databaseInfoCache.contributeToHttpCall(post);
    customDSInfoCache.contributeToHttpCall(post);

    awsEc2Contributor.contributeToHttpCall(post);

    if (optionalContributor != null) {
        optionalContributor.contributeToHttpCall(post);
    }
}

From source file:org.displaytag.model.Column.java

/**
 * Calculates the cell content, cropping or linking the value as needed.
 * /*from   w w w  .  j a v  a2  s . c  o m*/
 * @return String
 * @throws ObjectLookupException for errors in bean property lookup
 * @throws DecoratorException if a column decorator is used and an exception is thrown during value decoration
 */
public String createChoppedAndLinkedValue() throws ObjectLookupException, DecoratorException {

    String fullValue = ObjectUtils.toString(this.getValue(true));
    String choppedValue;

    // are we supposed to set up a link to the data being displayed in this column?
    if (this.header.getAutoLink()) {
        fullValue = AutolinkColumnDecorator.INSTANCE.decorate(fullValue);
    }

    // trim the string if a maxLength or maxWords is defined
    if (this.header.getMaxLength() > 0) {
        choppedValue = HtmlTagUtil.abbreviateHtmlString(fullValue, this.header.getMaxLength(), false);
    } else if (this.header.getMaxWords() > 0) {
        choppedValue = HtmlTagUtil.abbreviateHtmlString(fullValue, this.header.getMaxWords(), true);
    } else {
        choppedValue = fullValue;
    }

    // chopped content? add the full content to the column "title" attribute
    if (choppedValue.length() < fullValue.length()) {
        // clone the attribute map, don't want to add title to all the columns
        this.htmlAttributes = (HtmlAttributeMap) this.htmlAttributes.clone();
        // add title
        this.htmlAttributes.put(TagConstants.ATTRIBUTE_TITLE, HtmlTagUtil.stripHTMLTags(fullValue));
    }

    if (this.header.getHref() != null) {
        // generates the href for the link
        Href colHref = this.getColumnHref(fullValue);
        Anchor anchor = new Anchor(colHref, choppedValue);
        choppedValue = anchor.toString();

        // SIGESP verifica se hrefType = replace
        if (this.header.getHrefType() != null && this.header.getHrefType().equals("replace")) {

            String strTmp = choppedValue;

            Object valor = LookupUtil.getBeanProperty(this.row.getObject(), this.header.getParamProperty());
            String strValor = "";
            if (valor == null) {
                strValor = "NULL";
            } else {
                // Tratar aspas simples (retorno do javascript)
                strValor = Conversao.substituirExpressaoString(valor.toString(), "'", "\\u0027");
            }

            int intPosicao = -1;

            StringBuffer stbNovaString = new StringBuffer(strTmp);

            while ((intPosicao = stbNovaString.indexOf(this.header.getParamName())) >= 0) {
                stbNovaString.replace(intPosicao, intPosicao + this.header.getParamName().length(),
                        strValor.toString());
            }

            int intPosicaoIgual = stbNovaString.indexOf(strValor.toString() + "=");

            if (intPosicaoIgual != -1) {
                stbNovaString.replace(intPosicaoIgual - 1,
                        intPosicaoIgual - 1 + stbNovaString.substring(intPosicaoIgual - 1).indexOf(">") - 1,
                        ";");
                // stbNovaString.replace(stbNovaString.indexOf(valor.toString() + "=" + valor.toString()) - 1,
                // stbNovaString.substring(stbNovaString.indexOf(valor.toString() + "=" + valor.toString()) -
                // 1).indexOf(">"), ";");
            } else {
                throw new RuntimeException("Os parmetros informados na display-tag esto incorretos");
            }

            choppedValue = stbNovaString.toString();
        }
    }

    return choppedValue;
}

From source file:org.apache.nutch.protocol.htmlunit.HttpResponse.java

private void parseHeaders(PushbackInputStream in, StringBuffer line) throws IOException, HttpException {

    while (readLine(in, line, true) != 0) {

        // handle HTTP responses with missing blank line after headers
        int pos;/* ww w.  j  ava  2 s  .  c om*/
        if (((pos = line.indexOf("<!DOCTYPE")) != -1) || ((pos = line.indexOf("<HTML")) != -1)
                || ((pos = line.indexOf("<html")) != -1)) {

            in.unread(line.substring(pos).getBytes("UTF-8"));
            line.setLength(pos);

            try {
                //TODO: (CM) We don't know the header names here
                //since we're just handling them generically. It would
                //be nice to provide some sort of mapping function here
                //for the returned header names to the standard metadata
                //names in the ParseData class
                processHeaderLine(line);
            } catch (Exception e) {
                // fixme:
                Http.LOG.warn("Error: ", e);
            }
            return;
        }

        processHeaderLine(line);
    }
}

From source file:org.apache.nutch.protocol.s2jh.HttpResponse.java

private void parseHeaders(PushbackInputStream in, StringBuffer line) throws IOException, HttpException {

    while (readLine(in, line, true) != 0) {

        // handle HTTP responses with missing blank line after headers
        int pos;/*from   w  ww.j  a  v a  2s.c om*/
        if (((pos = line.indexOf("<!DOCTYPE")) != -1) || ((pos = line.indexOf("<HTML")) != -1)
                || ((pos = line.indexOf("<html")) != -1)) {

            in.unread(line.substring(pos).getBytes("UTF-8"));
            line.setLength(pos);

            try {
                // TODO: (CM) We don't know the header names here
                // since we're just handling them generically. It would
                // be nice to provide some sort of mapping function here
                // for the returned header names to the standard metadata
                // names in the ParseData class
                processHeaderLine(line);
            } catch (Exception e) {
                // fixme:
                Http.LOG.error("Failed with the following exception: ", e);
            }
            return;
        }

        processHeaderLine(line);
    }
}

From source file:de.hero.vertretungsplan.HtmlWork.java

public void extractTable(StringBuffer strHtml) throws IOException {
    SharedPreferences.Editor editor = mySharedPreferences.edit();

    ArrayList<HashMap<String, String>> lstEintraege = new ArrayList<HashMap<String, String>>();

    HashMap<String, String> hmEintrag = new HashMap<String, String>();

    int intIndex = strHtml.indexOf("<table");
    strHtml.delete(0, intIndex - 1);/*from   www. j  a v  a2s  . com*/
    intIndex = strHtml.indexOf("</table");
    strHtml.delete(intIndex, strHtml.length() - 1);
    DateFormat dfm = new SimpleDateFormat("dd.MM.yyyy");
    DateFormat dfm2 = new SimpleDateFormat("dd.MM.yy");
    Date dat = new Date();
    try {
        dat = dfm.parse(strHtml.substring(strHtml.indexOf(":") + 2));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    //      int date = dat.getDate();
    //      int month = dat.getMonth() + 1;

    //String strAktualisierungsText =  ((date < 10) ? "0" + date : date)  + "." + ((month < 10) ? "0" + month : month) + "." + (dat.getYear() + 1900) + " - " + strHtml.substring(strHtml.indexOf("<td>") + 4,strHtml.indexOf("</td"));
    String datumVertretungsplan = dfm2.format(dat);
    String aOderBWoche = strHtml.substring(strHtml.indexOf("<td>") + 4, strHtml.indexOf("</td"));
    Log.d("HtmlWork", "strAktualisierungsText " + datumVertretungsplan);
    editor.putString(context.getString(R.string.datumVertretungsplan), datumVertretungsplan);
    editor.putString("aOderBWoche", aOderBWoche);
    editor.commit();

    intIndex = strHtml.indexOf("<tr>");
    int intIndex2 = strHtml.indexOf("</tr>");
    strHtml.delete(0, intIndex2 + 4);
    intIndex = strHtml.indexOf("<tr>");
    intIndex2 = strHtml.indexOf("</tr>");

    strHtml.delete(0, intIndex2 + 4);
    intIndex2 = strHtml.indexOf("</tr>");
    strHtml.delete(0, intIndex2 + 4);
    intIndex = strHtml.indexOf("<tr>");
    intIndex2 = strHtml.indexOf("</tr>");
    while (intIndex != -1) {
        StringBuffer strZeile = new StringBuffer(strHtml.substring(intIndex + 4, intIndex2));
        int intIndex4 = strZeile.indexOf("</t");
        strZeile.delete(0, intIndex4 + 5);
        int intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");

        String stunde = strZeile.substring(intIndex3 + 4, intIndex4);
        hmEintrag.put("stunde", stunde + ((stunde.endsWith(".")) ? " Stunde" : ". Stunde"));

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("fach1", strZeile.substring(intIndex3 + 4, intIndex4));

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("vertreter", strZeile.substring(intIndex3 + 4, intIndex4));

        /*strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("fach2", strZeile.substring(intIndex3 + 4, intIndex4));*/

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("klassen", strZeile.substring(intIndex3 + 4, intIndex4));

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");
        hmEintrag.put("raum", strZeile.substring(intIndex3 + 4, intIndex4));

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");

        String strTemp = strZeile.substring(intIndex3 + 4, intIndex4);

        strZeile.delete(intIndex3, intIndex4 + 4);
        intIndex3 = strZeile.indexOf("<t");
        intIndex4 = strZeile.indexOf("</t");

        hmEintrag.put("text", strTemp + " " + strZeile.substring(intIndex3 + 4, intIndex4));

        lstEintraege.add(hmEintrag);

        hmEintrag = new HashMap<String, String>();

        strHtml.delete(0, intIndex2 + 2);
        intIndex = strHtml.indexOf("<tr>");
        intIndex2 = strHtml.indexOf("</tr>");
    }
    FileOutputStream fos = context.openFileOutput(context.getString(R.string.filename), Context.MODE_PRIVATE);
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    int oldHash = mySharedPreferences.getInt(context.getString(R.string.v_plan_hash_value), 0);

    oos.writeObject(lstEintraege);
    oos.close();
    fos.close();
    int newHash = lstEintraege.hashCode();
    editor.putInt(context.getString(R.string.v_plan_hash_value), newHash);
    editor.commit();

    Log.d("HtmlWork", "oldHash: " + oldHash + "; newHash: " + newHash);
    if (oldHash != newHash) {
        onDataChange();
    }
}

From source file:org.apache.nutch.protocol.http.HttpResponse.java

private void parseHeaders(PushbackInputStream in, StringBuffer line, StringBuffer httpHeaders)
        throws IOException, HttpException {

    while (readLine(in, line, true) != 0) {

        if (httpHeaders != null)
            httpHeaders.append(line).append("\n");

        // handle HTTP responses with missing blank line after headers
        int pos;/*from   w w w .  j av a2 s  .  c  om*/
        if (((pos = line.indexOf("<!DOCTYPE")) != -1) || ((pos = line.indexOf("<HTML")) != -1)
                || ((pos = line.indexOf("<html")) != -1)) {

            in.unread(line.substring(pos).getBytes("UTF-8"));
            line.setLength(pos);

            try {
                // TODO: (CM) We don't know the header names here
                // since we're just handling them generically. It would
                // be nice to provide some sort of mapping function here
                // for the returned header names to the standard metadata
                // names in the ParseData class
                processHeaderLine(line);
            } catch (Exception e) {
                // fixme:
                Http.LOG.warn("Error: ", e);
            }
            return;
        }

        processHeaderLine(line);
    }
}

From source file:com.nofuturecorp.www.connector.Database.java

/**
 * Make a post request to the PHP URL for process request and get data in JSON format
 * @param json with data to send//from  w w w.ja v  a2 s  .  com
 * @return JSON with data received
 * @throws IOException
 * @throws DatabaseException 
 */
private String makePostRequest(String json) throws IOException, DatabaseException {

    if (json == null) {
        throw new NullPointerException("json cannot be null");
    }
    if (!ignoreSecureProtocol && url.toUpperCase().startsWith("HTTPS")) {
        throw new SecureProtocolException(
                "URL Protocol is not valid. Please use HTTPS or set true ignore secure protocol");
    }

    StringBuffer data = null;
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("POST");
    con.setDoOutput(true);

    OutputStream os = con.getOutputStream();
    os.write(("isTransaction=" + isTransaction + "&data=" + json).getBytes());
    os.flush();
    os.close();

    int response = con.getResponseCode();
    if (response == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String line = null;
        data = new StringBuffer();
        while ((line = reader.readLine()) != null) {
            data.append(line);
        }
        String js = data.substring(data.indexOf("{"));
        return js;
    } else {
        throw new DatabaseException("HTTP connection fails. Response code: " + response);
    }
}

From source file:org.meveo.service.billing.impl.InvoiceService.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void createAgregatesAndInvoice(BillingAccount billingAccount, Long billingRunId, User currentUser)
        throws BusinessException, Exception {
    log.debug("createAgregatesAndInvoice tx status={}", txReg.getTransactionStatus());
    EntityManager em = getEntityManager();
    BillingRun billingRun = em.find(BillingRun.class, billingRunId);
    em.refresh(billingRun);//  w w  w.j av  a2s.  c o  m
    try {
        billingAccount = em.find(billingAccount.getClass(), billingAccount.getId());
        em.refresh(billingAccount);
        currentUser = em.find(currentUser.getClass(), currentUser.getId());
        em.refresh(currentUser);

        Long startDate = System.currentTimeMillis();
        BillingCycle billingCycle = billingRun.getBillingCycle();
        if (billingCycle == null) {
            billingCycle = billingAccount.getBillingCycle();
        }
        if (billingCycle == null) {
            throw new BusinessException("Cant find the billing cycle");
        }
        InvoiceType invoiceType = billingCycle.getInvoiceType();
        if (invoiceType == null) {
            invoiceType = invoiceTypeService.getDefaultCommertial(currentUser);
        }
        Invoice invoice = new Invoice();
        invoice.setInvoiceType(invoiceType);
        invoice.setBillingAccount(billingAccount);
        invoice.setBillingRun(billingRun);
        invoice.setAuditable(billingRun.getAuditable());
        invoice.setProvider(billingRun.getProvider());
        // ticket 680
        Date invoiceDate = billingRun.getInvoiceDate();
        invoice.setInvoiceDate(invoiceDate);

        Integer delay = billingCycle.getDueDateDelay();
        Date dueDate = invoiceDate;
        if (delay != null) {
            dueDate = DateUtils.addDaysToDate(invoiceDate, delay);
        }
        invoice.setDueDate(dueDate);

        PaymentMethodEnum paymentMethod = billingAccount.getPaymentMethod();
        if (paymentMethod == null) {
            paymentMethod = billingAccount.getCustomerAccount().getPaymentMethod();
        }
        invoice.setPaymentMethod(paymentMethod);
        invoice.setProvider(billingRun.getProvider());

        em.persist(invoice);

        // create(invoice, currentUser, currentUser.getProvider());
        log.debug("created invoice entity with id={},  tx status={}, em open={}", invoice.getId(),
                txReg.getTransactionStatus(), em.isOpen());
        ratedTransactionService.createInvoiceAndAgregates(billingAccount, invoice,
                billingRun.getLastTransactionDate(), currentUser);
        log.debug("created aggregates tx status={}, em open={}", txReg.getTransactionStatus(), em.isOpen());
        em.joinTransaction();

        if (billingRun.getProvider().isDisplayFreeTransacInInvoice()) {
            em.createNamedQuery("RatedTransaction.updateInvoicedDisplayFree")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();
        } else {
            em.createNamedQuery("RatedTransaction.updateInvoiced")
                    .setParameter("billingAccount", billingAccount)
                    .setParameter("lastTransactionDate", billingRun.getLastTransactionDate())
                    .setParameter("billingRun", billingRun).setParameter("invoice", invoice).executeUpdate();

        }

        StringBuffer num1 = new StringBuffer("000000000");
        num1.append(invoice.getId() + "");
        String invoiceNumber = num1.substring(num1.length() - 9);
        int key = 0;

        for (int i = 0; i < invoiceNumber.length(); i++) {
            key = key + Integer.parseInt(invoiceNumber.substring(i, i + 1));
        }

        invoice.setTemporaryInvoiceNumber(invoiceNumber + "-" + key % 10);
        // getEntityManager().merge(invoice);
        Long endDate = System.currentTimeMillis();

        log.info("createAgregatesAndInvoice BR_ID=" + billingRun.getId() + ", BA_ID=" + billingAccount.getId()
                + ", Time en ms=" + (endDate - startDate));
    } catch (Exception e) {
        log.error("Error for BA=" + billingAccount.getCode() + " : ", e);

        RejectedBillingAccount rejectedBA = new RejectedBillingAccount(billingAccount, billingRun,
                e.getMessage());
        rejectedBillingAccountService.create(rejectedBA, currentUser);
    }
}

From source file:net.sf.sze.util.VariableUtility.java

/**
 * Erzeugt den Text fr den Druck in dem die Variablen ersetzt werden.
 * @param text der Text// w w w .j  a  v  a  2 s.com
 * @param schueler der Schler
 * @param nachteilsausgleichsDatum das Datum des Nachteilsausgleichs.
 * @param erSieStattNamenRule true wenn er oder sie statt dem Namen
 * genommen werden soll.
 * @param schuljahr das Schuljahr
 * @return der Text fr den Druck.
 */
public static String createPrintText(final String text, Schueler schueler, final Date nachteilsausgleichsDatum,
        final boolean erSieStattNamenRule, final String schuljahr) {
    if (!text.contains("@")) {
        return text;
    }

    final String rufnameNotNull = schueler.getRufnameOrVorname();
    final StringBuffer printText = new StringBuffer();
    boolean erSieStattNamen = erSieStattNamenRule;
    // Der Prfix muss davor, damit der erste Token nie eine Variable ist.
    final String[] tokens = ("Text" + text).split("@");
    for (int i = 0; i < tokens.length; i++) {
        final String token = tokens[i];
        String replacement;
        if (i % 2 != 0) {
            if ("NAME".equals(token)) {
                replacement = rufnameNotNull;
            } else if ("name".equals(token)) {
                replacement = buildName(rufnameNotNull, schueler.getGeschlecht(), erSieStattNamen, true);
                erSieStattNamen = true;
            } else if ("Name".equals(token)) {
                replacement = buildName(rufnameNotNull, schueler.getGeschlecht(), erSieStattNamen, false);
                erSieStattNamen = true;
            } else if ("datum".equals(token)) {
                if (nachteilsausgleichsDatum != null) {
                    final SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
                    replacement = formatter.format(nachteilsausgleichsDatum);
                } else {
                    replacement = "";
                }
            } else if ("schuljahr".equals(token)) {
                replacement = schuljahr;
            } else if ("Vorname".equals(token)) {
                replacement = schueler.getVorname().trim();
            } else if ("Nachname".equals(token)) {
                replacement = schueler.getName().trim();
            } else if (token.contains("|")) {
                replacement = getGenderSpecificText(token, schueler.getGeschlecht());
            } else if ("AT".equals(token)) {
                replacement = "@";
            } else {
                throw new IllegalStateException(token + " is not allowed");
            }

            printText.append(replacement);
        } else {
            printText.append(token);
        }

    }

    return printText.substring(4);

}

From source file:pl.touk.xmlbeansxx.ClassGen.java

public static String javaToCpp(String x) {
    x = x.replace('$', '_');
    StringTokenizer t = new StringTokenizer(x, ".");
    StringBuffer b = new StringBuffer();
    while (t.hasMoreTokens()) {
        b.append("::" + skipKeywords(t.nextToken()));
    }//  w w w  .  ja v  a2 s .com
    return b.substring(2);
}