Example usage for java.lang StringBuffer delete

List of usage examples for java.lang StringBuffer delete

Introduction

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

Prototype

@Override
public synchronized StringBuffer delete(int start, int end) 

Source Link

Usage

From source file:org.overlord.sramp.governance.workflow.jbpm.EmbeddedJbpmManager.java

@Override
public long newProcessInstance(String deploymentId, String processId, Map<String, Object> context)
        throws WorkflowException {
    HttpURLConnection connection = null;
    Governance governance = new Governance();
    final String username = governance.getOverlordUser();
    final String password = governance.getOverlordPassword();
    Authenticator.setDefault(new Authenticator() {
        @Override//from   w w  w.  j a  va2s.  co  m
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password.toCharArray());
        }
    });

    try {
        deploymentId = URLEncoder.encode(deploymentId, "UTF-8"); //$NON-NLS-1$
        processId = URLEncoder.encode(processId, "UTF-8"); //$NON-NLS-1$
        String urlStr = governance.getGovernanceUrl()
                + String.format("/rest/process/start/%s/%s", deploymentId, processId); //$NON-NLS-1$
        URL url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        StringBuffer params = new StringBuffer();
        for (String key : context.keySet()) {
            String value = String.valueOf(context.get(key));
            value = URLEncoder.encode(value, "UTF-8"); //$NON-NLS-1$
            params.append(String.format("&%s=%s", key, value)); //$NON-NLS-1$
        }
        //remove leading '&'
        if (params.length() > 0)
            params.delete(0, 1);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST"); //$NON-NLS-1$
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        if (params.length() > 0) {
            PrintWriter out = new PrintWriter(connection.getOutputStream());
            out.print(params.toString());
            out.close();
        }
        connection.connect();
        int responseCode = connection.getResponseCode();
        if (responseCode >= 200 && responseCode < 300) {
            InputStream is = (InputStream) connection.getContent();
            String reply = IOUtils.toString(is);
            logger.info("reply=" + reply); //$NON-NLS-1$
            return Long.parseLong(reply);
        } else {
            logger.error("HTTP RESPONSE CODE=" + responseCode); //$NON-NLS-1$
            throw new WorkflowException("Unable to connect to " + urlStr); //$NON-NLS-1$
        }
    } catch (Exception e) {
        throw new WorkflowException(e);
    } finally {
        if (connection != null)
            connection.disconnect();
    }
}

From source file:h2weibo.utils.StatusImageExtractor.java

public byte[] extract(StringBuffer input) {
    if (input == null)
        return null;

    for (String key : simplePatterns.keySet()) {
        Pattern p = Pattern.compile(key);
        Matcher m = p.matcher(input);

        if (m.find()) {
            String mediaUrl = simplePatterns.get(key);
            mediaUrl = mediaUrl.replaceAll("_KEY_", m.group(1));

            try {
                byte[] bytes = downloadUrl(mediaUrl);
                input.delete(m.start(), m.end()); // -1 for the space before
                return bytes;
            } catch (IOException e) {
                log.error("Not able to download image", e);
            }/* w w w  .  j av a 2s. c  o m*/
        }
    }

    for (String key : jsonPatterns.keySet()) {
        Pattern p = Pattern.compile(key);
        Matcher m = p.matcher(input);

        if (m.find()) {
            String jsonUrl = jsonPatterns.get(key)[0];
            jsonUrl = jsonUrl.replaceAll("_KEY_", m.group(1));

            try {
                byte[] jsonData = downloadUrl(jsonUrl);
                JSONObject obj = new JSONObject(new String(jsonData));
                String imageUrl = (String) obj.get(jsonPatterns.get(key)[1]);

                return downloadUrl(imageUrl);
            } catch (IOException e) {
                log.error("Not able to download image", e);
            } catch (JSONException e) {
                log.error("Not able to parse json", e);
            }
        }
    }

    return null;
}

From source file:org.opennms.protocols.radius.springsecurity.RadiusAuthenticationProvider.java

/** {@inheritDoc} */
@Override//from  w  w  w.j  a va  2  s  .  co  m
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken token)
        throws AuthenticationException {
    if (!StringUtils.hasLength(username)) {
        logger.info("Authentication attempted with empty username");
        throw new BadCredentialsException(
                messages.getMessage("RadiusAuthenticationProvider.emptyUsername", "Username cannot be empty"));
    }
    String password = (String) token.getCredentials();
    if (!StringUtils.hasLength(password)) {
        logger.info("Authentication attempted with empty password");
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }

    InetAddress serverIP = null;
    serverIP = InetAddressUtils.addr(server);
    if (serverIP == null) {
        logger.error("Could not resolve radius server address " + server);
        throw new AuthenticationServiceException(messages.getMessage(
                "RadiusAuthenticationProvider.unknownServer", "Could not resolve radius server address"));
    }
    AttributeFactory.loadAttributeDictionary("net.jradius.dictionary.AttributeDictionaryImpl");
    AttributeList attributeList = new AttributeList();
    attributeList.add(new Attr_UserName(username));
    attributeList.add(new Attr_UserPassword(password));
    RadiusPacket reply;
    try {
        RadiusClient radiusClient = new RadiusClient(serverIP, secret, port, port + 1, timeout);
        AccessRequest request = new AccessRequest(radiusClient, attributeList);

        logger.debug("Sending AccessRequest message to " + InetAddressUtils.str(serverIP) + ":" + port
                + " using " + (authTypeClass == null ? "PAP" : authTypeClass.getAuthName())
                + " protocol with timeout = " + timeout + ", retries = " + retries + ", attributes:\n"
                + attributeList.toString());
        reply = radiusClient.authenticate(request, authTypeClass, retries);
    } catch (RadiusException e) {
        logger.error("Error connecting to radius server " + server + " : " + e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError",
                new Object[] { e }, "Error connecting to radius server: " + e));
    } catch (IOException e) {
        logger.error("Error connecting to radius server " + server + " : " + e);
        throw new AuthenticationServiceException(messages.getMessage("RadiusAuthenticationProvider.radiusError",
                new Object[] { e }, "Error connecting to radius server: " + e));
    }
    if (reply == null) {
        logger.error("Timed out connecting to radius server " + server);
        throw new AuthenticationServiceException(messages.getMessage(
                "RadiusAuthenticationProvider.radiusTimeout", "Timed out connecting to radius server"));
    }
    if (!(reply instanceof AccessAccept)) {
        logger.info("Received a reply other than AccessAccept from radius server " + server + " for user "
                + username + " :\n" + reply.toString());
        throw new BadCredentialsException(messages
                .getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    }
    logger.debug("Received AccessAccept message from " + InetAddressUtils.str(serverIP) + ":" + port
            + " for user " + username + " with attributes:\n" + reply.getAttributes().toString());

    String roles = null;
    if (!StringUtils.hasLength(rolesAttribute)) {
        logger.debug("rolesAttribute not set, using default roles (" + defaultRoles + ") for user " + username);
        roles = new String(defaultRoles);
    } else {
        Iterator<RadiusAttribute> attributes = reply.getAttributes().getAttributeList().iterator();
        while (attributes.hasNext()) {
            RadiusAttribute attribute = attributes.next();
            if (rolesAttribute.equals(attribute.getAttributeName())) {
                roles = new String(attribute.getValue().getBytes());
                break;
            }
        }
        if (roles == null) {
            logger.info("Radius attribute " + rolesAttribute + " not found, using default roles ("
                    + defaultRoles + ") for user " + username);
            roles = new String(defaultRoles);
        }
    }

    String[] rolesArray = roles.replaceAll("\\s*", "").split(",");
    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(rolesArray.length);
    for (String role : rolesArray) {
        authorities.add(new SimpleGrantedAuthority(role));
    }
    if (logger.isDebugEnabled()) {
        StringBuffer readRoles = new StringBuffer();
        for (GrantedAuthority authority : authorities) {
            readRoles.append(authority.toString() + ", ");
        }
        if (readRoles.length() > 0) {
            readRoles.delete(readRoles.length() - 2, readRoles.length());
        }
        logger.debug("Parsed roles " + readRoles + " for user " + username);
    }

    return new User(username, password, true, true, true, true, authorities);
}

From source file:web.DirslideshowController.java

public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from www . j  a  v a  2s.com*/
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest", e);
    }

    if (!rbDirectoryExists.equals("1")) {
        return handleError("Cannot manage directory feature in deluxe version.");
    }

    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null in DirslideshowController");
    }

    /** users should be allowed to view the directory blobs without the session **/
    String directoryid = request.getParameter(DbConstants.DIRECTORY_ID);
    if (RegexStrUtil.isNull(directoryid)) {
        return handleError("request, directory is null, for DirslideshowController ");
    }
    if (directoryid.length() > GlobalConst.directoryidSize) {
        return handleError("directoryid.length() > WebConstants.directoryidSize, for DirslideshowController ");
    }
    directoryid = RegexStrUtil.goodNameStr(directoryid);

    String dirName = request.getParameter(DbConstants.DIRNAME);
    if (!RegexStrUtil.isNull(dirName) && dirName.length() > GlobalConst.dirNameSize) {
        return handleError("dirName.length() > WebConstants.dirNameSize, DirslideshowController");
    }
    dirName = RegexStrUtil.goodNameStr(dirName);

    DirectoryDao directoryDao = (DirectoryDao) daoMapper.getDao(DbConstants.DIRECTORY);
    if (directoryDao == null) {
        return handleError("DirectoryDao is null in DirslideshowController directory");
    }

    DirectoryStreamBlobDao dirBlobDao = (DirectoryStreamBlobDao) daoMapper.getDao(DbConstants.DIR_BLOB);
    if (dirBlobDao == null) {
        return handleError("dirBlobDao is null in DirslideshowController directory");
    }

    List photos = null;
    List tagList = null;
    try {
        photos = directoryDao.getBlobsByCategory(directoryid, DbConstants.PHOTO_CATEGORY,
                DbConstants.BLOB_READ_FROM_SLAVE);
        tagList = dirBlobDao.getAllTags(directoryid, DbConstants.BLOB_READ_FROM_SLAVE);
    } catch (BaseDaoException e) {
        return handleError("Exception occured in getStreamBlobs() DirslideshowController, directory() ", e);
    }
    if (photos == null) {
        return handleError("photos null, DirslideshowController, directoryid = " + directoryid);
    }

    /** 
     * check if this photo exists 
          */
    int photoNum = 0;
    int nextPhotoNum = 0;
    int prevPhotoNum = 0;

    String goPhoto = request.getParameter(DbConstants.GOTO_PHOTO);
    if (!RegexStrUtil.isNull(goPhoto)) {
        String showphoto = request.getParameter(DbConstants.SHOW_PHOTO);
        if (!RegexStrUtil.isNull(showphoto)) {
            photoNum = new Integer(showphoto).intValue();
        }
    } else {
        String photoNumStr = request.getParameter(DbConstants.PHOTO_NUM);
        if (!RegexStrUtil.isNull(photoNumStr)) {
            photoNum = new Integer(photoNumStr).intValue();
        }
    }

    //logger.info("fn photoNum = " + photoNum);

    String timerStr = request.getParameter(DbConstants.TIMER);
    if (RegexStrUtil.isNull(timerStr)) {
        timerStr = "0";
    }

    if (photos.size() == 1) {
        photoNum = nextPhotoNum = prevPhotoNum = 0;
    } else {
        if (photoNum >= photos.size()) {
            photoNum = 0;
            nextPhotoNum = photoNum + 1;
            prevPhotoNum = photos.size() - 1;
        } else {
            nextPhotoNum = photoNum + 1;
            if (photoNum != 0) {
                prevPhotoNum = photoNum - 1;
                ;
            } else {
                prevPhotoNum = photos.size() - 1;
            }
        }
    }

    Directory cobrand = null;
    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleUserpageError("CobrandDao is null, DirslideshowController ");
    }
    try {
        cobrand = cobrandDao.getDirCobrand(directoryid);
    } catch (Exception e) {
        return handleError("exception getDirCobrand(), DirslideshowController ", e);
    }

    String url = "";
    String fn = request.getParameter(DbConstants.FNDOTX);
    Map myModel = new HashMap();
    if (!RegexStrUtil.isNull(fn)) {
        String beg = request.getParameter("count");
        //logger.info("fn count = " + beg );
        if (beg != null) {
            int count = new Integer(beg).intValue();
            //logger.info("fn converted to int = " + count );

            /*
            photos.size = 3;
            photonum = 0, count = 2;  
            photonum = 1, count = 1;  into play
            photonum = 2, count = 0;
            photonum = 3, count = -1;
            */

            if ((count > 0) && count <= photos.size()) {
                count--;
                String newBeg = "-1";
                if (count >= 0) {
                    newBeg = new Integer(count).toString();
                }
                //logger.info("fn newCount = " + newBeg );

                StringBuffer myUrl = new StringBuffer("<META HTTP-EQUIV=\"Refresh\" CONTENT=\"");
                myUrl.append(timerStr);
                myUrl.append("; URL=");
                myUrl.append("dirslideshow?directoryid=");
                myUrl.append(directoryid);
                myUrl.append("&dirname=");
                myUrl.append(dirName);
                myUrl.append("&photonum=");
                myUrl.append(nextPhotoNum);
                myUrl.append("&timer=");
                myUrl.append(timerStr);
                myUrl.append("&count=");
                myUrl.append(newBeg);
                myUrl.append("&fn.x=");
                myUrl.append(DbConstants.PLAY);
                myUrl.append("\">");
                url = myUrl.toString();
                //logger.info("url = " + url);
            } else {
                //lastone 
                myModel.put("count", null);
            }
        } // beg != null 
    } else {
        //logger.info("no more play, set the counter to null ");
        myModel.put("count", null);
    }

    StringBuffer usertags = new StringBuffer();
    if (tagList != null && tagList.size() > 0) {
        for (int i = 0; i < tagList.size(); i++) {
            if ((Photo) tagList.get(i) != null) {
                usertags.append(((Photo) tagList.get(i)).getValue(DbConstants.USER_TAGS));
            }
        }
    }

    /**
    * views resolved to the name of the jsp using ViewResolver
    */
    String viewName = DbConstants.DIR_SLIDE_SHOW;
    myModel.put(viewName, photos);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.DIRNAME, dirName);
    myModel.put(DbConstants.DIRECTORY_ID, directoryid);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.SHARE_INFO, shareInfo);
    myModel.put(DbConstants.USER_TAGS, usertags.toString());

    StringBuffer sb = new StringBuffer();
    sb.append(photoNum);
    myModel.put(DbConstants.PHOTO_NUM, sb.toString());

    sb.delete(0, sb.length());
    sb.append(nextPhotoNum);
    myModel.put(DbConstants.NEXT_NUM, sb.toString());

    sb.delete(0, sb.length());
    sb.append(prevPhotoNum);
    myModel.put(DbConstants.PREV_NUM, sb.toString());

    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.TIMER, timerStr);
    myModel.put(DbConstants.URL, url);
    myModel.put(DbConstants.BUSINESS_EXISTS, isBizExists(login));
    return new ModelAndView(viewName, "model", myModel);

    //myModel.put(DbConstants.FN, fn);
}

From source file:web.SlidesController.java

/**
 * This method is called by the spring framework. The configuration
 * for this controller to be invoked is based on the pagetype and
 * is set in the urlMapping property in the spring config file.
 *
 * @param request the <code>HttpServletRequest</code>
 * @param response the <code>HttpServletResponse</code>
 * @throws ServletException/*from w w  w . jav a2  s.  c om*/
 * @throws IOException
 * @return ModelAndView this instance is returned to spring
 */
public synchronized ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {
        ModelAndView m = super.handleRequest(request, response);
    } catch (Exception e) {
        return handleError("error in handleRequest");
    }

    if (getDaoMapper() == null) {
        return handleError("DaoMapper is null in SlidesController, member " + member);
    }

    String member = request.getParameter(DbConstants.MEMBER);
    if (RegexStrUtil.isNull(member)) {
        return handleError("member is null, Forwarding to " + member + "SlidesController");
    }

    member = RegexStrUtil.goodId(member);

    Hdlogin memberInfo = null;
    MemberDao memberDao = (MemberDao) daoMapper.getDao(DbConstants.MEMBER);
    if (memberDao == null) {
        return handleError("MemberDao is null, SlidesController, login, " + login);
    }

    try {
        memberInfo = memberDao.getMemberInfo(member);
    } catch (BaseDaoException e) {
        return handleError("getMemberInfo(member) exception in SlidesController, member=" + member, e);
    }

    if (memberInfo == null) {
        return handleError("memberInfo is null, in SlidesController" + member);
    }

    DisplaypageDao displayDao = (DisplaypageDao) getDaoMapper().getDao(DbConstants.DISPLAY_PAGE);
    if (displayDao == null) {
        return handleError("DisplaypageDao is null, " + member);
    }
    Displaypage uDisplaypage = null;
    try {
        uDisplaypage = displayDao.getDisplaypage(member);
    } catch (BaseDaoException e) {
        return handleError("Exception occurred in getMyDisplayInfo(), for member, " + member, e);
    }
    if (uDisplaypage == null) {
        return handleUserpageError("displaypage is null" + member);
    }

    /**
     *  if the user has not published photos, check:
     *    1. Is this login same as member?
          *    2. Is the login in session?
     */
    String published = uDisplaypage.getValue(DbConstants.PHOTOS);
    if (!RegexStrUtil.isNull(published) && (published.equals("0"))) {
        if (!RegexStrUtil.isNull(login) && !login.equals(member)) {
            return handleUserpageError(login + " user cannot access slideshow of this member =" + member);
        }
        outOfSession(request, response);
    }

    /**
     *    start the slide show
     */
    CarryonDao carryonDao = (CarryonDao) getDaoMapper().getDao(DbConstants.CARRYON);
    if (carryonDao == null) {
        return handleError("carryonDao is null, SlidesController for member " + member);
    }

    /**
     *  retrieve the update blob stream and other blobs
     */
    List carryon = null;
    List tagList = null;
    HashSet tagSet = null;
    try {
        carryon = carryonDao.getCarryonByCategory(memberInfo.getValue(DbConstants.LOGIN_ID),
                DbConstants.PHOTO_CATEGORY, DbConstants.READ_FROM_SLAVE);
        tagList = carryonDao.getTags(memberInfo.getValue(DbConstants.LOGIN_ID), DbConstants.READ_FROM_SLAVE);
        tagSet = carryonDao.getUniqueTags(tagList);
    } catch (BaseDaoException e) {
        return handleError("Exception occurred in getCarryonByCategory() member, " + member, e);
    }
    if (carryon == null) {
        return handleError("carryon is null for SlidesController, member = " + member);
    }

    /** 
     * check if this photo exists 
          */
    int photoNum = 0;
    int nextPhotoNum = 0;
    int prevPhotoNum = 0;

    String goPhoto = request.getParameter(DbConstants.GOTO_PHOTO);
    if (!RegexStrUtil.isNull(goPhoto)) {
        String showphoto = request.getParameter(DbConstants.SHOW_PHOTO);
        if (!RegexStrUtil.isNull(showphoto)) {
            photoNum = new Integer(showphoto).intValue();
        }
    } else {
        String photoNumStr = request.getParameter(DbConstants.PHOTO_NUM);
        if (!RegexStrUtil.isNull(photoNumStr)) {
            photoNum = new Integer(photoNumStr).intValue();
        }
    }

    String timerStr = request.getParameter(DbConstants.TIMER);
    if (RegexStrUtil.isNull(timerStr)) {
        timerStr = "0";
    }

    String fn = request.getParameter(DbConstants.FNDOTX);
    if (carryon.size() == 1) {
        photoNum = nextPhotoNum = prevPhotoNum = 0;
    } else {
        if (photoNum >= carryon.size()) {
            photoNum = 0;
            nextPhotoNum = photoNum + 1;
            prevPhotoNum = carryon.size() - 1;
        } else {
            nextPhotoNum = photoNum + 1;
            if (photoNum != 0) {
                prevPhotoNum = photoNum - 1;
                ;
            } else {
                prevPhotoNum = carryon.size() - 1;
            }
        }
    }

    CobrandDao cobrandDao = (CobrandDao) getDaoMapper().getDao(DbConstants.COBRAND);
    if (cobrandDao == null) {
        return handleUserpageError("CobrandDao is null, SlidesController");
    }

    Userpage cobrand = cobrandDao.getUserCobrand(memberInfo.getValue(DbConstants.LOGIN_ID));
    String url = "";
    Map myModel = new HashMap();

    if (!RegexStrUtil.isNull(fn)) {
        String beg = request.getParameter("count");
        if (beg != null) {
            int count = new Integer(beg).intValue();
            if ((count > 0) && count <= carryon.size()) {
                count--;
                String newBeg = "-1";
                if (count >= 0) {
                    newBeg = new Integer(count).toString();
                }
                StringBuffer myUrl = new StringBuffer("<META HTTP-EQUIV=\"Refresh\" CONTENT=\"");
                myUrl.append(timerStr);
                myUrl.append("; URL=");
                myUrl.append("slides?member=");
                myUrl.append(member);
                myUrl.append("&photonum=");
                myUrl.append(nextPhotoNum);
                myUrl.append("&timer=");
                myUrl.append(timerStr);
                myUrl.append("&count=");
                myUrl.append(newBeg);
                myUrl.append("&fn.x=");
                myUrl.append(DbConstants.PLAY);
                myUrl.append("\">");
                url = myUrl.toString();
            } else {
                //lastone
                myModel.put("count", null);
            }
        } // beg != null
    } else {
        myModel.put("count", null);
    }

    /**
    * editphotos or editfiles - views resolved to the name of the jsp using ViewResolver
    */
    String viewName = DbConstants.SLIDES;
    myModel.put(viewName, carryon);
    myModel.put(DbConstants.DIR_EXISTS, rbDirectoryExists);
    myModel.put(DbConstants.USER_PAGE, userpage);
    myModel.put(DbConstants.VISITOR_PAGE, memberUserpage);
    myModel.put(DbConstants.LOGIN_INFO, loginInfo);
    myModel.put(DbConstants.SHARE_INFO, shareInfo);
    myModel.put(DbConstants.PUBLISHED, published);
    if (tagSet != null) {
        myModel.put(DbConstants.USER_TAGS, RegexStrUtil.goodText(tagSet.toString()));
    }

    StringBuffer sb = new StringBuffer();
    sb.append(photoNum);
    myModel.put(DbConstants.PHOTO_NUM, sb.toString());

    sb.delete(0, sb.length());
    sb.append(nextPhotoNum);
    myModel.put(DbConstants.NEXT_NUM, sb.toString());

    sb.delete(0, sb.length());
    sb.append(prevPhotoNum);
    myModel.put(DbConstants.PREV_NUM, sb.toString());

    myModel.put(DbConstants.COBRAND, cobrand);
    myModel.put(DbConstants.TIMER, timerStr);

    myModel.put(DbConstants.URL, url);
    return new ModelAndView(viewName, "model", myModel);
    //myModel.put(DbConstants.FN, fn);
}

From source file:com.icesoft.faces.webapp.parser.JsfJspDigester.java

/**
 * This member gets the previous body text and returns it. It also clears
 * out that body text from the parent./*from   www  .  jav  a2 s.c  om*/
 *
 * @return The parent's body text.
 */
public String stealParentBodyText() {

    StringBuffer parentBodyText = (StringBuffer) bodyTexts.peek();
    if (parentBodyText == null || parentBodyText.length() == 0) {
        return null;
    }

    String returnString = new String(parentBodyText.toString());
    if (returnString.trim().length() == 0) {
        // Don't want to create whitespace only components;
        returnString = null;
    }

    // Get rid of body text that we just processed;
    parentBodyText.delete(0, parentBodyText.length());

    return returnString;
}

From source file:org.apache.hadoop.hbase.backup.impl.TableBackupClient.java

/**
 * Get backup request meta data dir as string.
 * @param backupInfo backup info/*  w  w  w .  j av  a  2 s .  c o  m*/
 * @return meta data dir
 */
private String obtainBackupMetaDataStr(BackupInfo backupInfo) {
    StringBuffer sb = new StringBuffer();
    sb.append("type=" + backupInfo.getType() + ",tablelist=");
    for (TableName table : backupInfo.getTables()) {
        sb.append(table + ";");
    }
    if (sb.lastIndexOf(";") > 0) {
        sb.delete(sb.lastIndexOf(";"), sb.lastIndexOf(";") + 1);
    }
    sb.append(",targetRootDir=" + backupInfo.getBackupRootDir());

    return sb.toString();
}

From source file:hudson.plugins.clearcase.ucm.UcmMakeBaselineComposite.java

/**
 * Make a composite baseline//www .j a v  a2  s .c  o  m
 *
 * @param compositeBaselineName the composite baseline name
 * @param compositeStream the composite UCM Clearcase stream with Pvob like : 'P_EngDesk_Product_3.2_int@\P_ORC'
 * @param compositeComponent the composite UCM Clearcase component name like 'C_ Build_EngDesk'
 * @param clearToolLauncher the ClearCase launcher
 * @param filePath the filepath
 * @throws Exception
 */
private void makeCompositeBaseline(ClearTool clearTool, String compositeBaselineName, String compositeStream,
        String compositeComponent, String pvob) throws Exception {

    // Get a view containing the composite component
    String compositeView = getOneViewFromStream(clearTool, this.compositeStreamSelector);

    // Get the component list (with pvob suffix) for the stream
    List<String> componentList = getComponentList(clearTool, this.compositeStreamSelector);

    StringBuffer sb = new StringBuffer();
    for (String comp : componentList) {
        // Exclude the composite component
        if (!comp.contains(compositeComponent)) {
            sb.append(",").append(comp);
        }
    }
    sb.delete(0, 1);
    String dependsOn = sb.toString();

    clearTool.mkbl(compositeBaselineName, compositeView, null, true, false, Arrays.asList(compositeComponent),
            dependsOn, dependsOn);

}

From source file:org.jactr.core.slot.DefaultConditionalSlot.java

public boolean matchesCondition(Object test) {
    if (test instanceof ISlot)
        test = ((ISlot) test).getValue();

    if (LOGGER.isDebugEnabled()) {
        StringBuffer sb = new StringBuffer("Test value : ");
        sb.append(test);/*www .j ava  2 s . c  om*/
        if (test != null) {
            sb.append(", ");
            sb.append(test.getClass().getName());
            sb.append(", ");
            sb.append(test.hashCode());
        }
        LOGGER.debug(sb.toString());
        sb.delete(0, sb.length());

        sb.append("Cond value : ");
        Object tmp = getValue();
        sb.append(tmp);
        if (tmp != null) {
            sb.append(", ");
            sb.append(tmp.getClass().getName());
            sb.append(", ");
            sb.append(tmp.hashCode());
        }
        LOGGER.debug(sb.toString());
    }

    boolean rtn = false;
    try {
        switch (_condition) {
        case EQUALS:
            rtn = equalValues(test);
            break;

        case LESS_THAN:
            rtn = lessThan(test);
            break;

        case LESS_THAN_EQUALS:
            rtn = equalValues(test) | lessThan(test);
            break;

        case GREATER_THAN:
            rtn = greaterThan(test);
            break;

        case GREATER_THAN_EQUALS:
            rtn = equalValues(test) | greaterThan(test);
            break;

        case NOT_EQUALS:
            rtn = !equalValues(test);
            break;

        case WITHIN:
            rtn = within(test);
            break;
        }
    } catch (Exception e) {
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Unknown failure comparing " + this + " with " + test, e);
    }

    if (LOGGER.isDebugEnabled())
        LOGGER.debug("matchesCondition " + this + " " + test + " : " + rtn);

    return rtn;
}

From source file:com.upyun.sdk.UpYunClient.java

public void downloadFile(String path, String fileName) throws UpYunExcetion {
    try {//from   w  w  w. j a  v  a 2  s  .com
        StringBuffer url = new StringBuffer();
        for (String str : fileName.split("/")) {
            if (str == null || str.length() == 0) {
                continue;
            }
            url.append(UrlCodingUtil.encodeBase64(str.getBytes("utf-8")) + "/");
        }
        url = url.delete(url.length() - 1, url.length());
        sign.setUri(url.toString());
    } catch (UnsupportedEncodingException e) {
        LogUtil.exception(logger, e);
    }
    sign.setContentLength(0);
    sign.setMethod(HttpMethod.GET.name());
    String url = autoUrl + sign.getUri();
    Map<String, String> headers = sign.getHeaders();

    HttpResponse httpResponse = HttpClientUtils.getByHttp(url, headers);
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        throw new UpYunExcetion(httpResponse.getStatusLine().getStatusCode(),
                httpResponse.getStatusLine().getReasonPhrase());
    }

    HttpEntity entity = httpResponse.getEntity();

    try {
        FileUtil.saveToFile(path + "/" + fileName, entity.getContent());
    } catch (Exception e) {
        LogUtil.exception(logger, e);
    }
}