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:padl.creator.javafile.eclipse.util.PadlParserUtil.java

/**
 * Get or create a ghost entity//from w w  w  . j  a v a  2s.  c  o m
 * 
 * @param isDealingWithExtend
 * @param anEntityTypeBinding
 * @param aPadlModel
 * @param aCurrentPackagePath
 * @return
 */
private static IFirstClassEntity getOrCreateGhostEntity(final boolean isDealingWithExtend,
        final ITypeBinding anEntityTypeBinding, final ICodeLevelModel aPadlModel,
        final String aCurrentPackagePath) {

    final StringBuffer tmpStringBuffer = new StringBuffer();
    String ghostName = null;
    String ghostPackagePath = null;
    String fullyQualifiedName = null;
    final String entityBindingKey = anEntityTypeBinding.getKey();
    final String prefix = "Recovered#currentType";

    if (entityBindingKey.startsWith(prefix)) {
        // ghosts in existing entities
        tmpStringBuffer.append(entityBindingKey.substring(prefix.length()));
        tmpStringBuffer.deleteCharAt(tmpStringBuffer.length() - 1);

        // Yann 2015/03/16: Symbols collision with IConstants!
        // I make sure that the name of the entity does not contain
        // any symbol used in the models, see IConstants, because
        // the entityBindingKey will be of the form:
        //   org.hibernate.envers.entities.mapper.relation.lazy.initializor.Initializor<List<U>>0<Ljava/util/List<Lorg/hibernate/envers/entities/mapper/relation/lazy/proxy/C:\Data\Java Programs\hibernate-orm-3.6.4.Final\hibernate-envers\src\main\java\org\hibernate\envers\entities\mapper\relation\lazy\proxy\ListProxy~ListProxy;:TU;>;>
        if (entityBindingKey.indexOf('/') > -1 || entityBindingKey.indexOf('\\') > -1) {

            ghostName = tmpStringBuffer.substring(0, tmpStringBuffer.indexOf("0"));
        } else {
            ghostName = tmpStringBuffer.toString();
        }
        ghostPackagePath = anEntityTypeBinding.getPackage().getName();
    } else if (isDealingWithExtend && entityBindingKey.startsWith("Recovered#typeBinding")) {

        ghostName = anEntityTypeBinding.getQualifiedName();
        ghostPackagePath = anEntityTypeBinding.getPackage().getName();
    } else {
        // Pure ghosts
        // Fix for eclipse_12-15-2009 (fixed) case of generic types
        // (templates) (fixed)
        final String[] packageComponents;
        if (anEntityTypeBinding.getPackage() == null) {// case of templates
            packageComponents = new String[0];
            // should be deleted (only for debug purpose)
            /*
             * Output .getInstance() .normalOutput() .println(
             * "PadlParserUtil in getOrCreateGhostEntity anEntityTypeBinding.getPackage() == null "
             * + anEntityTypeBinding .getQualifiedName());
             */
        } else {
            packageComponents = anEntityTypeBinding.getPackage().getNameComponents();
        }

        final int numberOfNames = packageComponents.length;

        char firstLetter;
        int i = 0;
        boolean checkPackage = true;

        if (numberOfNames > 0) {
            firstLetter = packageComponents[0].toCharArray()[0];
            if (Character.isLowerCase(firstLetter)) {
                tmpStringBuffer.append(packageComponents[0]);
                i++;
            } else {
                checkPackage = false;
            }

            while (i < numberOfNames && checkPackage) {
                firstLetter = packageComponents[i].toCharArray()[0];
                if (Character.isLowerCase(firstLetter)) {
                    tmpStringBuffer.append('.');
                    tmpStringBuffer.append(packageComponents[i]);
                    i++;
                } else {
                    checkPackage = false;
                }
            }
        }

        ghostPackagePath = tmpStringBuffer.toString();
        // why? aCurrentPackagePath=display path, is it more than the
        // package???
        String packagePath = aCurrentPackagePath;
        if (aCurrentPackagePath.length() > 2) {
            /*
             * Output .getInstance() .normalOutput() .println(
             * "PadlParserUtil in getOrCreateGhostEntity aCurrentPackagePath.length() > 2 "
             * + aCurrentPackagePath.length());
             */
            packagePath = aCurrentPackagePath.substring(aCurrentPackagePath.indexOf('|') + 1).replace("|", ".");
        }

        // if package ghost is the same with the current package and this
        // ghost is not from source
        // this means generally that there is a probleme of resolving so we
        // put this ghost in a specific package
        // also when this ghost is a generic type, we do the same
        // These conditions are not always true but permit to handle a lot
        // of cases
        if ((ghostPackagePath.equals(packagePath) || ghostPackagePath.length() == 0
                && ArrayUtils.isEquals(packagePath.toCharArray(), Constants.DEFAULT_PACKAGE_ID))
                && !anEntityTypeBinding.isFromSource()
                || ghostPackagePath.length() == 0 && anEntityTypeBinding.isFromSource()
                        && anEntityTypeBinding.isTypeVariable()) {
            ghostPackagePath = "unknown.ghost.packag";
        }

        tmpStringBuffer.setLength(0);

        while (i < numberOfNames) {
            tmpStringBuffer.append(packageComponents[i]);
            tmpStringBuffer.append('.');

            i++;
        }

        tmpStringBuffer.append(anEntityTypeBinding.getName());
        ghostName = tmpStringBuffer.toString();

    }

    tmpStringBuffer.setLength(0);
    tmpStringBuffer.append(ghostPackagePath);
    if (tmpStringBuffer.length() != 0) {
        tmpStringBuffer.append('.');
    }
    tmpStringBuffer.append(ghostName);
    fullyQualifiedName = tmpStringBuffer.toString();

    final int indexOfDot = ghostName.lastIndexOf('.');

    if (indexOfDot < 0) {
        // Case of a ghost
        IFirstClassEntity ghost = aPadlModel.getTopLevelEntityFromID(fullyQualifiedName.toCharArray());
        if (ghost == null) {
            ghost = PadlParserUtil.createGhost(aPadlModel, fullyQualifiedName.toCharArray());
        }
        return ghost;
    } else {
        // case of a ghost member
        // get or create a ghost based on the package name and the ghostName
        final String searchedGhostID = PadlParserUtil.renameWith$(fullyQualifiedName, ghostPackagePath);

        StringTokenizer tokenizer;

        //   int nbTokens = tokenizer.countTokens(); // number of entities in the
        // hierarchy=class>memberClass1>MemberClass2

        tokenizer = new StringTokenizer(searchedGhostID, "$");

        IPackage searchedPackage = null;

        IFirstClassEntity currentEntity = null;
        final String currentEntityID = tokenizer.nextToken();

        searchedPackage = PadlParserUtil.getPackage(ghostPackagePath, aPadlModel);

        if (searchedPackage != null) {
            currentEntity = aPadlModel.getTopLevelEntityFromID(currentEntityID.toCharArray());

            if (currentEntity == null) {
                currentEntity = PadlParserUtil.createGhost(aPadlModel, currentEntityID.toCharArray());
            }
        } else {
            currentEntity = PadlParserUtil.createGhost(aPadlModel, currentEntityID.toCharArray());
        }

        // create the member entities
        IFirstClassEntity currentMemberEntity;
        String currentMemberEntityID;
        String currentMemberEntityName;

        while (tokenizer.hasMoreTokens()) {
            currentMemberEntityName = tokenizer.nextToken();
            currentMemberEntityID = currentEntity.getDisplayID() + '$' + currentMemberEntityName;

            currentMemberEntity = (IFirstClassEntity) currentEntity
                    .getConstituentFromID(currentMemberEntityID.toCharArray());

            if (currentMemberEntity == null) {
                currentMemberEntity = aPadlModel.getFactory().createMemberGhost(
                        currentMemberEntityID.toCharArray(), currentMemberEntityName.toCharArray());
                currentEntity.addConstituent((IConstituentOfEntity) currentMemberEntity);
            }
            currentEntity = currentMemberEntity;
        }
        // The last entity created or got in the padl model is which
        // is searched for
        return currentEntity;
    }
}

From source file:org.openbravo.advpaymentmngt.actionHandler.AddPaymentActionHandler.java

private void addCredit(FIN_Payment payment, JSONObject jsonparams, BigDecimal differenceAmount,
        String strDifferenceAction) throws JSONException {
    // Credit to Use Grid
    JSONObject creditToUseGrid = jsonparams.getJSONObject("credit_to_use");
    JSONArray selectedCreditLines = creditToUseGrid.getJSONArray("_selection");
    BigDecimal remainingRefundAmt = differenceAmount;
    String strSelectedCreditLinesIds = null;
    if (selectedCreditLines.length() > 0) {
        strSelectedCreditLinesIds = getSelectedCreditLinesIds(selectedCreditLines);
        List<FIN_Payment> selectedCreditPayment = FIN_Utility.getOBObjectList(FIN_Payment.class,
                strSelectedCreditLinesIds);
        HashMap<String, BigDecimal> selectedCreditPaymentAmounts = getSelectedCreditLinesAndAmount(
                selectedCreditLines, selectedCreditPayment);

        for (final FIN_Payment creditPayment : selectedCreditPayment) {
            BusinessPartner businessPartner = creditPayment.getBusinessPartner();
            if (businessPartner == null) {
                throw new OBException(OBMessageUtils.messageBD("APRM_CreditWithoutBPartner"));
            }/*from  ww w  .  ja va2s. co  m*/
            String currency = null;
            if (businessPartner.getCurrency() == null) {
                currency = creditPayment.getCurrency().getId();
                businessPartner.setCurrency(creditPayment.getCurrency());
            } else {
                currency = businessPartner.getCurrency().getId();
            }
            if (!creditPayment.getCurrency().getId().equals(currency)) {
                throw new OBException(String.format(OBMessageUtils.messageBD("APRM_CreditCurrency"),
                        businessPartner.getCurrency().getISOCode()));
            }
            BigDecimal usedCreditAmt = selectedCreditPaymentAmounts.get(creditPayment.getId());
            if (strDifferenceAction.equals("refund")) {
                if (remainingRefundAmt.compareTo(usedCreditAmt) > 0) {
                    remainingRefundAmt = remainingRefundAmt.subtract(usedCreditAmt);
                    usedCreditAmt = BigDecimal.ZERO;
                } else {
                    usedCreditAmt = usedCreditAmt.subtract(remainingRefundAmt);
                    remainingRefundAmt = BigDecimal.ZERO;
                }
            }
            final StringBuffer description = new StringBuffer();
            if (creditPayment.getDescription() != null && !creditPayment.getDescription().equals("")) {
                description.append(creditPayment.getDescription()).append("\n");
            }
            description.append(
                    String.format(OBMessageUtils.messageBD("APRM_CreditUsedPayment"), payment.getDocumentNo()));
            String truncateDescription = (description.length() > 255)
                    ? description.substring(0, 251).concat("...").toString()
                    : description.toString();
            creditPayment.setDescription(truncateDescription);
            // Set Used Credit = Amount + Previous used credit introduced by the user
            creditPayment.setUsedCredit(usedCreditAmt.add(creditPayment.getUsedCredit()));

            if (usedCreditAmt.compareTo(BigDecimal.ZERO) > 0) {
                FIN_PaymentProcess.linkCreditPayment(payment, usedCreditAmt, creditPayment);
            }
            OBDal.getInstance().save(creditPayment);
        }
    }
}

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

/**
 * //from  w w w .  j a  v  a2  s .  c  o m
 * @param in
 * @param line
 * @throws HttpException
 * @throws IOException
 */
@SuppressWarnings("unused")
private void readChunkedContent(PushbackInputStream in, StringBuffer line) throws HttpException, IOException {
    boolean doneChunks = false;
    int contentBytesRead = 0;
    byte[] bytes = new byte[Http.BUFFER_SIZE];
    ByteArrayOutputStream out = new ByteArrayOutputStream(Http.BUFFER_SIZE);

    while (!doneChunks) {
        if (Http.LOG.isTraceEnabled()) {
            Http.LOG.trace("Http: starting chunk");
        }

        readLine(in, line, false);

        String chunkLenStr;
        // if (LOG.isTraceEnabled()) { LOG.trace("chunk-header: '" + line + "'"); }

        int pos = line.indexOf(";");
        if (pos < 0) {
            chunkLenStr = line.toString();
        } else {
            chunkLenStr = line.substring(0, pos);
            // if (LOG.isTraceEnabled()) { LOG.trace("got chunk-ext: " + line.substring(pos+1)); }
        }
        chunkLenStr = chunkLenStr.trim();
        int chunkLen;
        try {
            chunkLen = Integer.parseInt(chunkLenStr, 16);
        } catch (NumberFormatException e) {
            throw new HttpException("bad chunk length: " + line.toString());
        }

        if (chunkLen == 0) {
            doneChunks = true;
            break;
        }

        if ((contentBytesRead + chunkLen) > http.getMaxContent())
            chunkLen = http.getMaxContent() - contentBytesRead;

        // read one chunk
        int chunkBytesRead = 0;
        while (chunkBytesRead < chunkLen) {

            int toRead = (chunkLen - chunkBytesRead) < Http.BUFFER_SIZE ? (chunkLen - chunkBytesRead)
                    : Http.BUFFER_SIZE;
            int len = in.read(bytes, 0, toRead);

            if (len == -1)
                throw new HttpException("chunk eof after " + contentBytesRead + " bytes in successful chunks"
                        + " and " + chunkBytesRead + " in current chunk");

            // DANGER!!! Will printed GZIPed stuff right to your
            // terminal!
            // if (LOG.isTraceEnabled()) { LOG.trace("read: " +  new String(bytes, 0, len)); }

            out.write(bytes, 0, len);
            chunkBytesRead += len;
        }

        readLine(in, line, false);

    }

    if (!doneChunks) {
        if (contentBytesRead != http.getMaxContent())
            throw new HttpException("chunk eof: !doneChunk && didn't max out");
        return;
    }

    content = out.toByteArray();
    parseHeaders(in, line);

}

From source file:org.latticesoft.util.container.VarBean.java

/**
 * Returns the full name including that of the parent(s) separated
 * by the separator String.//  w  w w  .j av  a  2s  . co m
 * @param separator the separator for the name
 * @param attributeName the name for the attribute to append in the list
 */
public String getHierarchyName(String separator, String attributeName) {
    if (separator == null) {
        separator = "-";
    }
    List l = this.getHierarchyList();
    StringBuffer sb = new StringBuffer();
    Iterator iter = l.iterator();
    while (iter.hasNext()) {
        VarBean b = (VarBean) iter.next();
        if (b.getString(attributeName) != null) {
            sb.append(b.getString(attributeName));
            sb.append(separator);
        }
    }
    String retVal = "";
    if (sb.length() > separator.length()) {
        retVal = sb.substring(0, sb.length() - separator.length());
    } else {
        retVal = sb.toString();
    }
    return retVal;
}

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

private void readChunkedContent(PushbackInputStream in, StringBuffer line) throws HttpException, IOException {
    boolean doneChunks = false;
    int contentBytesRead = 0;
    byte[] bytes = new byte[HttpProtocol.BUFFER_SIZE];
    ByteArrayOutputStream out = new ByteArrayOutputStream(HttpProtocol.BUFFER_SIZE);

    while (!doneChunks) {
        if (HttpProtocol.LOGGER.isTraceEnabled()) {
            HttpProtocol.LOGGER.trace("Http: starting chunk");
        }/* w w w.  j  a v  a 2  s  .  c o m*/

        readLine(in, line, false);

        String chunkLenStr;
        // if (LOG.isTraceEnabled()) { LOG.trace("chunk-header: '" + line +
        // "'"); }

        int pos = line.indexOf(";");
        if (pos < 0) {
            chunkLenStr = line.toString();
        } else {
            chunkLenStr = line.substring(0, pos);
            // if (LOG.isTraceEnabled()) { LOG.trace("got chunk-ext: " +
            // line.substring(pos+1)); }
        }
        chunkLenStr = chunkLenStr.trim();
        int chunkLen;
        try {
            chunkLen = Integer.parseInt(chunkLenStr, 16);
        } catch (NumberFormatException e) {
            throw new HttpException("bad chunk length: " + line.toString());
        }

        if (chunkLen == 0) {
            doneChunks = true;
            break;
        }

        if (http.getMaxContent() >= 0 && (contentBytesRead + chunkLen) > http.getMaxContent())
            chunkLen = http.getMaxContent() - contentBytesRead;

        // read one chunk
        int chunkBytesRead = 0;
        while (chunkBytesRead < chunkLen) {

            int toRead = (chunkLen - chunkBytesRead) < HttpProtocol.BUFFER_SIZE ? (chunkLen - chunkBytesRead)
                    : HttpProtocol.BUFFER_SIZE;
            int len = in.read(bytes, 0, toRead);

            if (len == -1)
                throw new HttpException("chunk eof after " + contentBytesRead + " bytes in successful chunks"
                        + " and " + chunkBytesRead + " in current chunk");

            // DANGER!!! Will printed GZIPed stuff right to your
            // terminal!
            // if (LOG.isTraceEnabled()) { LOG.trace("read: " + new
            // String(bytes, 0, len)); }

            out.write(bytes, 0, len);
            chunkBytesRead += len;
        }

        readLine(in, line, false);

    }

    if (!doneChunks) {
        if (contentBytesRead != http.getMaxContent())
            throw new HttpException("chunk eof: !doneChunk && didn't max out");
        return;
    }

    content = out.toByteArray();
    parseHeaders(in, line);

}

From source file:sim.app.sugarscape.Sugarscape.java

public void start() {
    super.start();
    agents_grid.clear();/* w  w w .  jav  a2 s.  c om*/
    scape_grid.clear();
    //scape_grid = new ObjectGrid2D(gridWidth, gridHeight);
    sim.app.sugarscape.Agent agent;
    /* If the season rate is very large, it will be summer for all foreseable simulation runs in the north and winter
    in the south. Growback rates for each are set as parameters and normally default to 1 */
    north_season = SUMMER;
    south_season = WINTER;
    Steppable season_changer = new Steppable() {
        public void step(SimState state) {
            Sugarscape sugar = (Sugarscape) state;
            if (sugar.north_season == SUMMER) {
                sugar.north_season = WINTER;
                sugar.south_season = SUMMER;
            } else {
                sugar.north_season = SUMMER;
                sugar.south_season = WINTER;
            }
        }
    };

    MultiStep season_multi = new MultiStep(season_changer, season_rate, true);
    schedule.scheduleRepeating(Schedule.EPOCH, 3, season_multi, 1); //change seasons last in order

    if (agents_file != null) { //config file for setting up agents spatial config
        try {
            InputStream is = Class.forName(sim.app.sugarscape.Sugarscape.class.getCanonicalName())
                    .getClassLoader().getResourceAsStream(agents_file);
            InputStreamReader ir = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(ir);

            String line = br.readLine();
            int y = 0;
            int affiliation;
            String affil_code;
            while (line != null) {
                int x = 0;
                int size = line.length();
                while (x < size) {
                    affil_code = line.substring(x, x + 1);
                    affiliation = Integer.parseInt(affil_code);
                    if (affiliation != 0) {
                        agent = this.newAgent();
                        agents_grid.field[x][y] = agent; //,new Int2D(x,y));
                        agent.my_loc.x = x;
                        agent.my_loc.y = y;
                    }
                    x++;
                }
                line = br.readLine();
                y++;
                //System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else { //otherwise distribute randomly in space
        for (int a = 0; a < numAgents; a++) {
            createNewAgent();
        }
    }

    ArrayList rows = new ArrayList(50);
    for (int a = 0; a < resources; a++) {
        rows.clear();
        try {
            InputStream is = Class.forName(sim.app.sugarscape.Sugarscape.class.getCanonicalName())
                    .getClassLoader().getResourceAsStream(terrain_files[a]);
            InputStreamReader ir = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(ir);
            String line = br.readLine();
            while (line != null) {
                rows.add(line);
                line = br.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        int row_count = rows.size();
        int capacity;
        String max;
        int equator = row_count / 2;
        int hemisphere = NORTH;
        Object[][] all_objs = scape_grid.field;
        //Object[][] all_pollut = pollution_grid.field;
        for (int y = 0; y < gridHeight; y++) {
            if (y >= equator) {
                hemisphere = SOUTH;
            }
            StringBuffer sb = new StringBuffer((String) rows.get(y));
            int type;
            for (int x = 0; x < gridWidth; x++) {
                max = sb.substring(x, x + 1);
                capacity = Integer.parseInt(max);
                if (capacity > 4) { //terrain file has values of 0-4, and 0,5-8
                    type = SPICE;
                    capacity = capacity - 4;
                } else {
                    type = SUGAR;
                }
                if (all_objs[x][y] == null) {
                    Scape site = new Scape(x, y, hemisphere, pollution_diffusion, this);
                    site.setResource(type, capacity, 1,
                            capacity); /* idealy the growback rate, third param, should not be constant */
                    all_objs[x][y] = site;
                } else {
                    ((Scape) all_objs[x][y]).setResource(type, capacity, 1, capacity);
                }
            }
        }
    }
    this.initializeEnvironment();

    //set up charts
    avg_agent_vision.clear();
    lorenz_curve.clear();
    gini_coeff.clear();
    agents_series.clear();
    blue_agents.clear();
    red_agents.clear();
    trade_series.clear();

    if (stats_rate > 0) {
        Statistics stats = new Statistics(this, schedule, stats_out);
        MultiStep multi_lorenz = new MultiStep(stats, stats_rate, true);
        schedule.scheduleRepeating(Schedule.EPOCH, 4, multi_lorenz, 1);
        stats.step(this);
    }
    //calculate and output frequency count for metabolic 'bins'
    //that is the total metabolism for each each across the population
    Steppable metabolism_bins_updater = new Steppable() {
        Histogram h = new Histogram("Metabolism", "Vision", 1 + metabolic_sugar + metabolic_spice, 5);

        public void step(SimState state) {
            //agents_grid.

            Bag all = null; //agents_grid.getAllObjects();
            int size = all.size();
            int total = 0;
            Object[] all_obj = all.objs;
            h.zero();
            for (int a = 0; a < size; a++) {
                Agent ag = (Agent) all_obj[a];
                total = ag.metabolic_rate_spice + ag.metabolic_rate_sugar;
                h.bins[total] = h.bins[total] + 1;
                h.bins_assoc[total] = h.bins_assoc[total] + ag.vision;
            }
            h.render();
            System.out.println(size + " = size, " + (state.schedule.time() + 1) + " = steps.");

        }
    };

    if (print_metabolism_bins) {
        MultiStep multi_metabolism_bins = new MultiStep(metabolism_bins_updater, metabolism_bins_freq, true);
        schedule.scheduleRepeating(Schedule.EPOCH, 6, multi_metabolism_bins, 1);
        multi_metabolism_bins.step(this);
    }

    //TO DO: Restore this
    if (logger != null) {
        MultiStep multi_logger = null; //new MultiStep(logger, log_frequency, true);
        //use order 4 along with statistics steppable
        //System.out.println("Logging "+ logger.grids.size() + " grids.");
        schedule.scheduleRepeating(Schedule.EPOCH, 4, multi_logger, 1);
        //Thread t = new Thread(logger);
        //t.start();
    }

    Steppable chart_updater = new Steppable() {
        private static final int BINS = 10;
        private float total;
        private float wealth_sugar_total;
        private double[] ages;

        public void step(SimState state) {

            Bag all = null; //agents_grid.getAllObjects();
            int size = active_agents_count;
            double[] values = null;
            if (size != 0) { /* what if there are zero agents? */
                values = new double[size];
            } else {
                values = new double[1];
                values[0] = 0;
            }
            total = 0;
            wealth_sugar_total = 0;
            if (age_chart_on) {
                ages = new double[size];
            }
            Iterator<Agent> i = active_agents.iterator();
            int a = 0;
            while (i.hasNext()) {
                Agent agent = i.next();
                values[a] = agent.wealth_sugar;
                wealth_sugar_total = wealth_sugar_total + agent.wealth_sugar;
                if (age_chart_on) {
                    ages[a] = agent.age;
                }
                a++;
            }

            if (age_chart_on) {
                age_hist_dataset = new HistogramDataset();
                age_hist_dataset.addSeries(Double.toString(state.schedule.time()), ages, 10);
                XYPlot xy = ((Sugarscape) state).age_histo_chart.getXYPlot();
                xy.setDataset(age_hist_dataset);
            }

            if (wealth_chart_on) {
                dataset = new HistogramDataset();
                dataset.addSeries(Double.toString(state.schedule.time()), values, 10);
                XYPlot xy = ((Sugarscape) state).chart4.getXYPlot();
                xy.setDataset(dataset);
                XYItemRenderer r = xy.getRenderer();
                XYItemLabelGenerator xylg = new StandardXYItemLabelGenerator("{2}", new DecimalFormat("0.00"),
                        new DecimalFormat("0.00"));
                r.setItemLabelGenerator(xylg);
                r.setItemLabelsVisible(true);
            }
        }
    };
    // Schedule the agent to update the chart
    if (chart_display) {
        MultiStep multi_chart = new MultiStep(chart_updater, chart_rate, true);
        schedule.scheduleRepeating(Schedule.EPOCH, 6, multi_chart, 1);
        chart_updater.step(this);
    }
}

From source file:com.amalto.workbench.editors.MenuMainPage.java

@Override
protected void createCharacteristicsContent(FormToolkit toolkit, Composite mainComposite) {

    try {//from   w  w  w . ja va2s .c  o  m
        // description
        Label descriptionLabel = toolkit.createLabel(mainComposite, Messages.MenuMainPage_Description,
                SWT.NULL);
        descriptionLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, true, 1, 1));
        descriptionText = toolkit.createText(mainComposite, "", SWT.BORDER);//$NON-NLS-1$
        descriptionText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        ((GridData) descriptionText.getLayoutData()).minimumHeight = 30;
        descriptionText.addModifyListener(new ModifyListener() {

            public void modifyText(ModifyEvent e) {
                if (refreshing) {
                    return;
                }

                markDirtyWithoutCommit();
            }
        });
        // Util.createCompDropTarget(descriptionText);
        // make the Page window a DropTarget - we need to dispose it
        windowTarget = new DropTarget(this.getPartControl(), DND.DROP_MOVE);
        windowTarget.setTransfer(new Transfer[] { TextTransfer.getInstance() });
        windowTarget.addDropListener(new DCDropTargetListener());

        Composite composite = toolkit.createComposite(mainComposite, SWT.BORDER);
        composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
        composite.setLayout(new GridLayout(1, false));

        menuTree = new TreeViewer(composite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
        menuTree.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
        ((GridData) menuTree.getControl().getLayoutData()).heightHint = 150;

        menuTree.setContentProvider(new ITreeContentProvider() {

            public void dispose() {
            }

            public Object[] getChildren(Object parentElement) {
                if (parentElement instanceof TreeEntry) {
                    WSMenuEntry wsEntry = ((TreeEntry) parentElement).getWSMenuEntry();
                    if (wsEntry.getSubMenus() != null) {
                        TreeEntry[] children = new TreeEntry[wsEntry.getSubMenus().size()];
                        for (int i = 0; i < wsEntry.getSubMenus().size(); i++) {
                            children[i] = new TreeEntry((TreeEntry) parentElement,
                                    wsEntry.getSubMenus().get(i));
                        }
                        return children;
                    }
                    return null;
                }

                if (parentElement instanceof WSMenu) { // the root
                    java.util.List<WSMenuEntry> menuEntries = ((WSMenu) parentElement).getMenuEntries();
                    if (menuEntries != null) {
                        TreeEntry[] children = new TreeEntry[menuEntries.size()];
                        for (int i = 0; i < menuEntries.size(); i++) {
                            children[i] = new TreeEntry(null, menuEntries.get(i));
                        }
                        return children;
                    }
                    return null;
                }

                return null; // ??!!?
            }

            public Object[] getElements(Object inputElement) {
                return getChildren(inputElement);
            }

            public Object getParent(Object element) {
                return null;
            }

            public boolean hasChildren(Object element) {
                return ((getChildren(element) == null) || (getChildren(element).length > 0));
            }

            public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
            }
        });
        menuTree.setLabelProvider(new LabelProvider() {

            @Override
            public String getText(Object element) {
                WSMenuEntry wsMenuEntry = ((TreeEntry) element).getWSMenuEntry();
                StringBuffer label = new StringBuffer(wsMenuEntry.getId() + " - ");//$NON-NLS-1$

                for (WSMenuMenuEntriesDescriptions description : wsMenuEntry.getDescriptions()) {
                    label.append("[").append(description.getLanguage()).append(": ")//$NON-NLS-1$//$NON-NLS-2$
                            .append(description.getLabel()).append("] ");//$NON-NLS-1$
                }
                if (label.length() > 200) {
                    return label.substring(0, 197) + "..."; //$NON-NLS-1$
                }
                return label.toString();
            }

            @Override
            public Image getImage(Object element) {
                return ImageCache.getCreatedImage(EImage.MENU.getPath());
            }
        });

        menuTreeMgr = new MenuManager();
        menuTreeMgr.setRemoveAllWhenShown(true);
        menuTreeMgr.addMenuListener(new IMenuListener() {

            public void menuAboutToShow(IMenuManager manager) {
                IStructuredSelection selection = ((IStructuredSelection) menuTree.getSelection());
                if ((selection == null) || (selection.getFirstElement() == null)) {
                    manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
                    return;
                }
                // TreeEntry entry = (TreeEntry)selection.getFirstElement();
                menuTreeMgr.add(new TreeEntryEditAction(menuTree));
                menuTreeMgr.add(new TreeEntryAddAction(menuTree, LOCATION_BEFORE));
                menuTreeMgr.add(new TreeEntryAddAction(menuTree, LOCATION_AFTER));
                menuTreeMgr.add(new TreeEntryAddAction(menuTree, LOCATION_UNDER));
                menuTreeMgr.add(new TreeEntryDeleteAction(menuTree));
                menuTreeMgr.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
            }
        });
        menuTree.addDoubleClickListener(new IDoubleClickListener() {

            public void doubleClick(DoubleClickEvent event) {
                (new TreeEntryEditAction(menuTree)).run();
            }
        });
        Menu menu = menuTreeMgr.createContextMenu(menuTree.getControl());
        menuTree.getControl().setMenu(menu);
        getSite().registerContextMenu(menuTreeMgr, menuTree);

        refreshData();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

}

From source file:com.clustercontrol.collect.composite.CollectGraphComposite.java

/**
 * ???????????//  w w w. j  av  a2 s  .co m
 * 
 * @param summaryType
 * @param itemCodeList
 */
private void setSettingLabel(int summaryType, List<CollectKeyInfoPK> itemCodeList) {
    ArrayList<String> itemCodeNameList = new ArrayList<>();
    for (EndpointUnit unit : EndpointManager.getActiveManagerList()) {
        for (CollectKeyInfoPK itemCode : itemCodeList) {
            String displayName = itemCode.getDisplayName();
            String itemName = itemCode.getItemName();
            if (!displayName.equals("") && !itemName.endsWith("[" + displayName + "]")) {
                itemName += "[" + displayName + "]";
            }

            String str = itemName + CollectSettingComposite.SEPARATOR_AT + itemCode.getMonitorId() + "("
                    + unit.getManagerName() + ")";
            if (!itemCodeNameList.contains(str)) {
                itemCodeNameList.add(str);
            }
        }
    }
    StringBuffer itemCodeStr = new StringBuffer();
    for (String itemCodeName : itemCodeNameList) {
        if (0 < itemCodeStr.length()) {
            itemCodeStr.append(", ");
        }
        itemCodeStr.append(HinemosMessage.replace(itemCodeName));
    }
    if (itemCodeStr.length() > 256) {
        itemCodeStr = new StringBuffer(itemCodeStr.substring(0, 256));
        itemCodeStr.append("...");
    }
    settingLabel.setText(
            Messages.getString("collection.summary.type") + " : " + SummaryTypeMessage.typeToString(summaryType)
                    + ",   " + Messages.getString("collection.display.name") + " : " + itemCodeStr.toString());
}

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

/**
 * @param in/*from   w w w. j a  v  a  2s  . com*/
 * @param line
 * @throws HttpException
 * @throws IOException
 */
private void readChunkedContent(PushbackInputStream in, StringBuffer line) throws HttpException, IOException {
    boolean doneChunks = false;
    int contentBytesRead = 0;
    byte[] bytes = new byte[Http.BUFFER_SIZE];
    ByteArrayOutputStream out = new ByteArrayOutputStream(Http.BUFFER_SIZE);

    while (!doneChunks) {
        if (Http.LOG.isTraceEnabled()) {
            Http.LOG.trace("Http: starting chunk");
        }

        readLine(in, line, false);

        String chunkLenStr;
        // if (LOG.isTraceEnabled()) { LOG.trace("chunk-header: '" + line + "'");
        // }

        int pos = line.indexOf(";");
        if (pos < 0) {
            chunkLenStr = line.toString();
        } else {
            chunkLenStr = line.substring(0, pos);
            // if (LOG.isTraceEnabled()) { LOG.trace("got chunk-ext: " +
            // line.substring(pos+1)); }
        }
        chunkLenStr = chunkLenStr.trim();
        int chunkLen;
        try {
            chunkLen = Integer.parseInt(chunkLenStr, 16);
        } catch (NumberFormatException e) {
            throw new HttpException("bad chunk length: " + line.toString());
        }

        if (chunkLen == 0) {
            doneChunks = true;
            break;
        }

        if (http.getMaxContent() >= 0 && (contentBytesRead + chunkLen) > http.getMaxContent())
            chunkLen = http.getMaxContent() - contentBytesRead;

        // read one chunk
        int chunkBytesRead = 0;
        while (chunkBytesRead < chunkLen) {

            int toRead = (chunkLen - chunkBytesRead) < Http.BUFFER_SIZE ? (chunkLen - chunkBytesRead)
                    : Http.BUFFER_SIZE;
            int len = in.read(bytes, 0, toRead);

            if (len == -1)
                throw new HttpException("chunk eof after " + contentBytesRead + " bytes in successful chunks"
                        + " and " + chunkBytesRead + " in current chunk");

            // DANGER!!! Will printed GZIPed stuff right to your
            // terminal!
            // if (LOG.isTraceEnabled()) { LOG.trace("read: " + new String(bytes, 0,
            // len)); }

            out.write(bytes, 0, len);
            chunkBytesRead += len;
        }

        readLine(in, line, false);

    }

    if (!doneChunks) {
        if (contentBytesRead != http.getMaxContent())
            throw new HttpException("chunk eof: !doneChunk && didn't max out");
        return;
    }

    content = out.toByteArray();
    parseHeaders(in, line, null);

}

From source file:com.wizecommerce.hecuba.HecubaClientManager.java

/**
 * Takes a list of comma delimited urls, and a list of comma delimited port numbers.
 * It will match the pairs of port to hostnames.  If the counts don't match, then it will
 * backfill with the last valid port number.
 * @param locationURLs address of cassandra nodes
 * @param ports ports that cassandra nodes are listening on
 * @return locationURLs combined with ports (location1:port1,location2:port2,...)
 *///from  w ww  . ja va2  s .c o  m
protected String getListOfNodesAndPorts(String locationURLs, String ports) {
    final String paramSeparator = ConfigUtils.getInstance().getConfiguration()
            .getString(HecubaConstants.GLOBAL_PROP_NAME_PREFIX + ".hecuba.path.separator", ":");
    final String[] splittedPorts = ports.split(paramSeparator);
    final String[] splittedLocationURLs = locationURLs.split(paramSeparator);
    final StringBuffer listOfNodesAndPortsBuffer = new StringBuffer();
    String port = "";
    for (int index = 0; index < splittedLocationURLs.length; index++) {
        final String locationURL = splittedLocationURLs[index];
        if (index < splittedPorts.length) {
            port = splittedPorts[index];
        }

        if (StringUtils.isEmpty(port)) {
            port = "9160";
        }
        listOfNodesAndPortsBuffer.append(locationURL).append(":").append(port).append(",");
    }
    return listOfNodesAndPortsBuffer.substring(0, listOfNodesAndPortsBuffer.lastIndexOf(","));
}