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:com.dldzkj.app.renxing.mainfragment.MyPostFragment1.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.delete_btn:
        if (deleteList == null)
            deleteList = new ArrayList<Integer>();
        for (Integer key : isCheckedMap.keySet()) {
            if (isCheckedMap.get(key)) {
                deleteList.add(key);/*  w w  w.j a  v  a2  s.  c o m*/
            }
        }
        if (deleteList.size() == 0) {//??
            menuDelete.setIcon(R.drawable.ic_delede);
            menuDelete.setTitle("");
            bottom.setVisibility(View.GONE);
            adapter.setDeleteMode(false);
            return;
        }
        StringBuffer sb = new StringBuffer();
        for (Integer key : deleteList) {
            sb.append(key + "#");
        }
        String rids = sb.substring(0, sb.length() - 1);
        Log.d("zxl", "rids:" + rids);
        btnEnable = false;
        WebRequstDeletePost(rids);

        break;
    case R.id.select_all:
        Set<Integer> set = isCheckedMap.keySet();
        Iterator<Integer> iterator = set.iterator();
        if (selectAll.getText().equals("")) {
            while (iterator.hasNext()) {
                Integer keyId = iterator.next();
                isCheckedMap.put(keyId, true);
            }
            selectAll.setText("?");
            deleteBtn.setTextColor(Color.parseColor("#eb5959"));
        } else {
            while (iterator.hasNext()) {
                Integer keyId = iterator.next();
                isCheckedMap.put(keyId, false);
            }
            selectAll.setText("");
            deleteBtn.setTextColor(Color.parseColor("#666666"));
        }
        adapter.notifyDataSetChanged();
        break;

    }
}

From source file:org.openedit.util.StreamGobbler.java

@Override
public void run() {
    parentThread = Thread.currentThread();
    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
    String line = null;/*from  w w  w. ja  v  a  2  s  . co m*/
    try {
        StringBuffer writer = null;
        if (isLoggingEnabled) {
            writer = new StringBuffer();
        }
        while (!Thread.currentThread().isInterrupted() && (line = br.readLine()) != null) {
            if (isLoggingEnabled) {
                writer.append(line);
                writer.append('\n');
                if (writer.length() > 100000) //Dont let this buffer get more than 100k of memory
                {
                    String cut = writer.substring(writer.length() - 70000, writer.length());
                    writer = new StringBuffer(cut);
                }
            }
        }
        if (isLoggingEnabled) {
            fieldOutput = writer.toString();
        }
    } catch (IOException e) {
        if (isLoggingEnabled) {
            log.debug("Failed to gobble stream", e);
            log.info("Failed to gobble stream");

        }
    }
}

From source file:org.openhealthtools.openxds.webapp.action.ViewAction.java

public String execute() throws Exception {
    contextpath = getRequest().getContextPath();
    StringBuffer reqURL = getRequest().getRequestURL();
    int index = 0;
    if (reqURL != null)
        index = reqURL.lastIndexOf("/");

    if (index != -1) {
        registryUrl = reqURL.substring(0, index + 1) + "services/DocumentRegistry";
    }/*  w w  w.java 2s.  co  m*/
    return SUCCESS;
}

From source file:org.esgf.globusonline.GOauthView1Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView doPost(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //grab the dataset name, file names and urls from the query string
    String dataset_name = request.getParameter("id");
    String[] file_names = request.getParameterValues("child_id");
    String[] file_urls = request.getParameterValues("child_url");
    String esg_user = "";
    String esg_password = "";
    //String e;//  ww w.  j  a v a 2s  .  c  om
    //grab the credential string
    String credential = request.getParameter("credential");
    System.out.println("Starting GlobusOnline workflow");
    //System.out.println("\n\n\n\t\tGO Credential " + credential + "\n\n\n");

    StringBuffer currentURL = request.getRequestURL();
    String currentURI = request.getRequestURI();
    //System.out.println("current URL is: " + currentURL);
    //System.out.println("current URI is: " + currentURI);
    //System.out.println("index is: " + currentURL.lastIndexOf(currentURI));
    String BaseURL = currentURL.substring(0, currentURL.lastIndexOf(currentURI));
    //System.out.println("BaseURL string is: " + BaseURL );

    //Instantiate model object:
    Map<String, Object> model = new HashMap<String, Object>();

    //Bail out if no gsiftp URLs are in file_names
    if (file_names != null) {
        for (int i = 0; i < file_names.length; i++) {
            if (!(file_urls[i] == null) && (file_urls[i].contains("gsiftp"))) {
                break;
            } else {
                model.put(GOFORMVIEW_ERROR, "error");
                String error_msg = "Selected dataset " + dataset_name
                        + " contains no GridFTP URLS, and cannot be transferred with this transfer method.";
                model.put(GOFORMVIEW_ERROR_MSG, error_msg);
                return new ModelAndView("goauthview3", model);
            }
        }
    } else {
        System.out.println("file_urls itself was null\n");
        model.put(GOFORMVIEW_ERROR, "error");
        String error_msg = "Selected dataset(s) " + dataset_name
                + " contain no GridFTP URLS, and cannot be transferred with this transfer method.";
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);
    }
    //Create a session if it doesn't already exist, so we can save state.
    HttpSession session = request.getSession(true);
    if (session.isNew() == false) {
        session.invalidate();
        session = request.getSession(true);
    }

    //System.out.println("Auth1, session id is:" + session.getId());

    session.setAttribute("fileUrls", file_urls);
    session.setAttribute("fileNames", file_names);
    session.setAttribute("datasetName", dataset_name);
    session.setAttribute("baseurl", BaseURL);
    if (!(credential == null)) {
        session.setAttribute("usercertificatefile", credential);
    }

    Cookie[] cookies = request.getCookies();
    String openId = "";

    for (int i = 0; i < cookies.length; i++) {
        if (cookies[i].getName().equals("esgf.idp.cookie")) {
            openId = cookies[i].getValue();
        }
    }

    LOG.debug("Got User OpenID: " + openId);
    // Create the client
    Properties GOProperties = getGOProperties();
    String PortalID = (String) GOProperties.getProperty("GOesgfPortalID", "bogususer");
    String PortalPass = (String) GOProperties.getProperty("GOesgfPortalPassword", "boguspassword");

    String loginUri = "";
    try {
        GoauthClient cli = new GoauthClient("nexus.api.globusonline.org", "globusonline.org", PortalID,
                PortalPass);
        cli.setIgnoreCertErrors(true);

        // Redirect the user agent to the globusonline log in page
        loginUri = cli.getLoginUrl(response.encodeURL(BaseURL + "/esgf-web-fe/goauthview2"));

    } catch (NexusClientException e) {
        System.out.println("ERROR:  GOesgfPortalID and/or GOesgfPortalPassword wrong or not set.");
        //            e.printStackTrace();
        model.put(GOFORMVIEW_ERROR, "error");
        String error_msg = "GlobusOnline Configuration file not found. Please create /esg/config/globusonline.properties and populate it with GOesgfPortalID and GOesgfPortalPassword";
        model.put(GOFORMVIEW_ERROR_MSG, error_msg);
        return new ModelAndView("goauthview3", model);
    }
    String myproxyServerStr = null;

    return new ModelAndView("redirect:" + loginUri, model);
}

From source file:org.apache.hadoop.hdfs.server.namenode.TestFSDirectory.java

/** Dump the tree, make some changes, and then dump the tree again. */
@Test// w  w w. j ava  2  s  .c o  m
public void testDumpTree() throws Exception {
    HopsTransactionalRequestHandler verifyFileBlocksHandler = new HopsTransactionalRequestHandler(
            HDFSOperationType.VERIFY_FILE_BLOCKS, dir.toString()) {
        @Override
        public void acquireLock(TransactionLocks locks) throws IOException {
            LockFactory lf = LockFactory.getInstance();
            INodeLock il = lf.getINodeLock(TransactionLockTypes.INodeLockType.WRITE_ON_TARGET_AND_PARENT,
                    TransactionLockTypes.INodeResolveType.PATH_AND_ALL_CHILDREN_RECURSIVELY, dir.toString())
                    .setNameNodeID(cluster.getNameNode().getId())
                    .setActiveNameNodes(cluster.getNameNode().getActiveNameNodes().getActiveNodes());
            locks.add(il).add(lf.getLeaseLock(TransactionLockTypes.LockType.WRITE))
                    .add(lf.getLeasePathLock(TransactionLockTypes.LockType.READ_COMMITTED))
                    .add(lf.getBlockLock()).add(lf.getBlockRelated(LockFactory.BLK.RE, LockFactory.BLK.CR,
                            LockFactory.BLK.UC, LockFactory.BLK.UR, LockFactory.BLK.PE, LockFactory.BLK.IV));
        }

        @Override
        public Object performTask() throws StorageException, IOException {
            final INode root = fsdir.getINode(dir.toString());

            LOG.info("Original tree");
            final StringBuffer b1 = root.dumpTreeRecursively();
            System.out.println("b1=" + b1);

            final BufferedReader in = new BufferedReader(new StringReader(b1.toString()));

            String line = in.readLine();
            checkClassName(line);

            for (; (line = in.readLine()) != null;) {
                line = line.trim();
                Assert.assertTrue(line.startsWith(INodeDirectory.DUMPTREE_LAST_ITEM)
                        || line.startsWith(INodeDirectory.DUMPTREE_EXCEPT_LAST_ITEM));
                checkClassName(line);
            }
            return b1;
        }
    };
    final StringBuffer b1 = (StringBuffer) verifyFileBlocksHandler.handle();
    LOG.info("Create a new file " + file4);
    DFSTestUtil.createFile(hdfs, file4, 1024, REPLICATION, seed);

    verifyFileBlocksHandler = new HopsTransactionalRequestHandler(HDFSOperationType.VERIFY_FILE_BLOCKS,
            dir.toString()) {
        @Override
        public void acquireLock(TransactionLocks locks) throws IOException {
            LockFactory lf = LockFactory.getInstance();
            INodeLock il = lf.getINodeLock(TransactionLockTypes.INodeLockType.WRITE_ON_TARGET_AND_PARENT,
                    TransactionLockTypes.INodeResolveType.PATH_AND_ALL_CHILDREN_RECURSIVELY, dir.toString())
                    .setNameNodeID(cluster.getNameNode().getId())
                    .setActiveNameNodes(cluster.getNameNode().getActiveNameNodes().getActiveNodes());
            locks.add(il).add(lf.getLeaseLock(TransactionLockTypes.LockType.WRITE))
                    .add(lf.getLeasePathLock(TransactionLockTypes.LockType.READ_COMMITTED))
                    .add(lf.getBlockLock()).add(lf.getBlockRelated(LockFactory.BLK.RE, LockFactory.BLK.CR,
                            LockFactory.BLK.UC, LockFactory.BLK.UR, LockFactory.BLK.PE, LockFactory.BLK.IV));
        }

        @Override
        public Object performTask() throws StorageException, IOException {
            final INode root = fsdir.getINode(dir.toString());
            final StringBuffer b2 = root.dumpTreeRecursively();
            System.out.println("b2=" + b2);

            int i = 0;
            int j = b1.length() - 1;
            for (; b1.charAt(i) == b2.charAt(i); i++)
                ;
            int k = b2.length() - 1;
            for (; b1.charAt(j) == b2.charAt(k); j--, k--)
                ;
            final String diff = b2.substring(i, k + 1);
            System.out.println("i=" + i + ", j=" + j + ", k=" + k);
            System.out.println("diff=" + diff);
            Assert.assertTrue(i > j);
            Assert.assertTrue(diff.contains(file4.getName()));
            return null;
        }
    };
    verifyFileBlocksHandler.handle();
}

From source file:com.dldzkj.app.renxing.mainfragment.MyPostFragment0.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.delete_btn:
        if (deleteList == null)
            deleteList = new ArrayList<Integer>();
        for (Integer key : isCheckedMap.keySet()) {
            if (isCheckedMap.get(key)) {
                deleteList.add(key);//from w  ww.java2  s  .co  m
            }
        }
        if (deleteList.size() == 0) {//??
            menuDelete.setIcon(R.drawable.ic_delede);
            menuDelete.setTitle("");
            bottom.setVisibility(View.GONE);
            adapter.setDeleteMode(false);
            return;
        }
        StringBuffer sb = new StringBuffer();
        for (Integer key : deleteList) {
            sb.append(key + "#");
        }
        String pids = sb.substring(0, sb.length() - 1);
        Log.d("zxl", "pids:" + pids);
        btnEnable = false;
        WebRequstDeletePost(pids);

        break;
    case R.id.select_all:
        Set<Integer> set = isCheckedMap.keySet();
        Iterator<Integer> iterator = set.iterator();
        if (selectAll.getText().equals("")) {
            while (iterator.hasNext()) {
                Integer keyId = iterator.next();
                isCheckedMap.put(keyId, true);
            }
            selectAll.setText("?");
            deleteBtn.setTextColor(Color.parseColor("#eb5959"));
        } else {
            while (iterator.hasNext()) {
                Integer keyId = iterator.next();
                isCheckedMap.put(keyId, false);
            }
            selectAll.setText("");
            deleteBtn.setTextColor(Color.parseColor("#666666"));
        }
        adapter.notifyDataSetChanged();
        break;

    }
}

From source file:nl.b3p.kaartenbalie.struts.DepositAction.java

@Override
public ActionForward save(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }//  w w w  .ja v  a 2  s.  co m

    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        super.addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }
    /*
     * Alle gegevens voor de betaling.
     */
    Integer amount = (Integer) dynaForm.get("amount");
    Integer fraction = (Integer) dynaForm.get("fraction");
    String description = dynaForm.getString("description");
    String paymentMethod = dynaForm.getString("paymentMethod");
    BigDecimal billing = integersToBD(amount, fraction);
    Integer exchangeRate = Transaction.getExchangeRate();
    if (billing.doubleValue() <= 0) {
        log.error("Amount cannot be less then or equal to zero!");
        throw new Exception("Amount cannot be less then or equal to zero!");
    }

    /*
     * Start de transactie
     */
    StringBuffer tdesc = new StringBuffer();
    if (description != null) {
        tdesc.append(description);
    }
    if (paymentMethod != null) {
        tdesc.append("/");
        tdesc.append(paymentMethod);
    }
    if (exchangeRate != null) {
        tdesc.append("/1:");
        tdesc.append(exchangeRate);
    }
    if (tdesc.length() > 32) {
        tdesc = new StringBuffer(tdesc.substring(0, 32));
    }
    Organization organization = getOrganization(dynaForm, request);
    AccountManager am = AccountManager.getAccountManager(organization.getId());

    /* Er komt null terug als accounting uit staat in AccountManager.java */
    Transaction tpd = am.prepareTransaction(Transaction.DEPOSIT, tdesc.toString());

    /* Prijs, koers, conversie */
    if (tpd != null) {
        tpd.setBillingAmount(billing);
        BigDecimal creditAlt = billing.multiply(new BigDecimal(exchangeRate.intValue()));
        tpd.setCreditAlteration(creditAlt);
        tpd.setTxExchangeRate(exchangeRate);
        am.commitTransaction(tpd, (User) request.getUserPrincipal());
    }

    ActionRedirect redirect = new ActionRedirect(mapping.findForward(BACK));
    redirect.addParameter("selectedOrganization", organization.getId().toString());

    return redirect;
}

From source file:net.alchemiestick.katana.winehqappdb.WineApp.java

@Override
protected String doInBackground(HttpUriRequest... url) {
    if (url[0] == null)
        return this.body;
    HttpResponse res = null;/*from   ww w .j a va2s.  com*/
    while (res == null)
        try {
            SearchView.do_sleep(500);
            res = this.client.execute(url[0]);
        } finally {
            continue;
        }

    while (res.getStatusLine() == null) {
        SearchView.do_sleep(500);
    }

    StringBuffer sb = new StringBuffer("");
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()), (2 * 1024));
        String line;
        boolean first = true;
        while ((line = br.readLine()) != null) {
            if (first) {
                first = false;
                continue;
            }
            sb.append(line + "\n");
        }

        this.body = sb.substring(sb.indexOf("<body"), (sb.lastIndexOf("</body>") + 7));
    } catch (IOException ioe) {
        this.str = "IO Failed!!!:; ; ;";
        this.str += ioe.toString();
    } catch (Exception ex) {
    } finally {
        this.client.close();
    }
    return this.body;
}

From source file:com.callidusrobotics.ui.MessageBox.java

@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public void addLine(final String string, final Color foreground, final Color background,
        final boolean preformatted) {
    final List<String> tokens = getMessageTokens(string, preformatted);
    final StringBuffer stringBuffer = new StringBuffer(lineLength);

    // Append the string token-by-token, line-by-line to the end of the messagebuffer
    while (!tokens.isEmpty()) {
        stringBuffer.delete(0, stringBuffer.length());
        stringBuffer.append(tokens.remove(0));

        // The first word to be printed on the line is too long and needs to be hyphenated
        if (stringBuffer.length() > lineLength) {
            tokens.add(0, stringBuffer.substring(lineLength - 1, stringBuffer.length()));
            stringBuffer.delete(lineLength - 1, stringBuffer.length());
            stringBuffer.append('-');
        }//from   w w w  .  ja va 2 s .  c o m

        // Continue to append tokens to the linebuffer one-by-one and append enough whitespace to fill the buffer
        while (stringBuffer.length() < lineLength) {
            stringBuffer.append(' ');

            final boolean tokenWillFit = !tokens.isEmpty()
                    && stringBuffer.length() + tokens.get(0).length() <= lineLength;
            if (!preformatted && tokenWillFit) {
                stringBuffer.append(tokens.remove(0));
            }
        }

        lineBuffer.add(new BufferLine(stringBuffer.toString(), foreground, background));

        // Delete the oldest message line
        if (lineBuffer.size() > maxLines) {
            lineBuffer.remove(0);
        }
    }
}

From source file:com.openedit.util.URLUtilities.java

/**
 * This is the server name only //w ww . j  av  a2s  .co m
 *
 * returns http://www.acme.com/
 */
public String buildRoot() {
    if (fieldRequest == null) {
        return null;
    }

    StringBuffer ctx = fieldRequest.getRequestURL();
    String servername = ctx.substring(0, ctx.indexOf("/", 8));

    return servername + "/";
}