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:eea.eprtr.cms.controller.FileOpsController.java

/**
 * Upload file for transfer.//from w ww .j  a va2s. co  m
 */
@RequestMapping(value = "/filecatalogue", method = RequestMethod.POST)
public String importFile(@RequestParam("file") MultipartFile myFile,
        final RedirectAttributes redirectAttributes, final HttpServletRequest request) throws IOException {

    if (myFile == null || myFile.getOriginalFilename() == null) {
        redirectAttributes.addFlashAttribute("message", "Select a file to upload");
        return "redirect:filecatalogue";
    }
    String fileName = storeFile(myFile);
    redirectAttributes.addFlashAttribute("filename", fileName);
    StringBuffer requestUrl = request.getRequestURL();
    redirectAttributes.addFlashAttribute("url",
            requestUrl.substring(0, requestUrl.length() - "/filecatalogue".length()));
    return "redirect:filecatalogue";
}

From source file:ch.entwine.weblounge.bridge.oaipmh.harvester.OaiPmhRepositoryClient.java

/**
 * Join the query parameters.// w w w . ja  va2 s  .  c  om
 */
private String join(String... as) {
    StringBuffer buf = new StringBuffer();
    for (String a : as) {
        if (a.length() > 0)
            buf.append(a).append("&");
    }
    return buf.substring(0, Math.max(buf.length() - "&".length(), 0));
}

From source file:com.concursive.connect.web.modules.wiki.utils.HTMLToWikiUtils.java

public static void processImage(StringBuffer sb, Node n, Element element, String appendToCRLF,
        String contextPath, int projectId) {
    // Images/*from  www  . j  a  v  a 2s  .co m*/
    // [[Image:Filename.jpg]]
    // [[Image:Filename.jpg|A caption]]
    // [[Image:Filename.jpg|thumb]]
    // [[Image:Filename.jpg|right]]
    // [[Image:Filename.jpg|left]]

    // <img
    // style="float: right;"
    // style="display:block;margin: 0 auto;"
    // title="This is the title of the image"
    // longdesc="http://i.l.cnn.net/cnn/2008/LIVING/personal/04/08/fees/art.fees.jpg?1"
    // src="http://i.l.cnn.net/cnn/2008/LIVING/personal/04/08/fees/art.fees.jpg"
    // alt="This is an image description"
    // width="292"
    // height="219" />

    // image right: float: right; margin: 3px; border: 3px solid black;
    // image left: float: left; margin: 3px; border: 3px solid black;

    // <img
    // src="${ctx}/show/some-company/wiki-image/Workflow+-+Ticket+Example.png"
    // alt="Workflow - Ticket Example.png"
    // width="315"
    // height="362" />

    // See if the parent is a link
    String link = null;
    String title = null;
    if (hasParentNodeType(n, "a")) {
        // Get the attributes of the link
        StringBuffer linkSB = new StringBuffer();
        processLink(linkSB, (Element) element.getParentNode(), appendToCRLF, contextPath, projectId);
        link = linkSB.substring(2, linkSB.length() - 2);
    } else {
        // tooltip (will be used as caption), but not for links
        title = element.getAttribute("title");
    }

    // Determine if this is an embedded video link
    if (link != null && link.startsWith("http://www.youtube.com/v/")) {
        processVideoLink(sb, n, element, appendToCRLF, contextPath, link);
    } else {
        processImage(sb, n, element, appendToCRLF, contextPath, projectId, link, title);
    }
}

From source file:org.rifidi.emulator.reader.alien.command.exception.AlienExceptionHandler.java

/**
 * This error is used when the argument that the user passed in was not a
 * possible value//from   ww  w  . j  av  a  2  s. c o m
 * 
 * @param arg
 * @param obj
 * @param PossibleValues
 *            The list of possible values
 * @return
 */
public ArrayList<Object> error10(ArrayList<Object> arg, CommandObject obj, ArrayList<String> PossibleValues) {
    String retVal = "";
    for (Object i : arg) {
        retVal += i.toString();
    }
    StringBuffer sb = new StringBuffer();
    for (String s : PossibleValues) {
        sb.append(s + "|");
    }
    String values = sb.substring(0, sb.length() - 1);
    return this.errorFormat("Error 10: String must be a member of: " + values, retVal, obj);
}

From source file:oracle.custom.ui.servlet.LoginServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*w ww  .  j  a v  a2  s .co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //System.out.println("User Agent " + request.getHeader("User-Agent"));
    try (PrintWriter out = response.getWriter()) {
        // if we come back here after the user is already authenticated it means
        // that we're looking for OAuth consent
        if (request.getSession().getAttribute("AUTHENTICATED") != null) {
            request.getRequestDispatcher("/oauthallowed.jsp").forward(request, response);
        }
        try {
            String tenantName = (String) DomainName.getDomainName();

            String endpoint = OpenIdConfiguration.getInstance(tenantName).getAuthzEndpoint();
            String clientId = CredentialsList.getCredentials().get(tenantName).getId();
            StringBuffer url = request.getRequestURL();
            String uri = request.getRequestURI();
            String ctx = request.getContextPath();
            String base = url.substring(0, url.length() - uri.length() + ctx.length()) + "/";
            //String redirecturl = base + "atreturn/";
            //String openIdConfig = endpoint + "?client_id=" + clientId + 
            //        "&response_type=code&redirect_uri=" + redirecturl + 
            //        "&scope=urn:opc:idm:t.user.me+openid+urn:opc:idm:__myscopes__&nonce=" + UUID.randomUUID().toString();

            URIBuilder builder = new URIBuilder(endpoint);
            builder.addParameter("client_id", clientId);
            builder.addParameter("response_type", "code");
            builder.addParameter("redirect_uri", base + "atreturn/");
            builder.addParameter("scope", "urn:opc:idm:t.user.me openid urn:opc:idm:__myscopes__");
            builder.addParameter("nonce", UUID.randomUUID().toString());
            URI redirectUrl = builder.build();

            System.out.println("Opend Id URL is " + redirectUrl.toString());
            response.sendRedirect(redirectUrl.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
            request.getRequestDispatcher("/error.jsp").forward(request, response);
        }
    }
}

From source file:com.all.backend.web.controller.PasswordResetServerController.java

@RequestMapping("/reset/{key}")
public String showResetPasswordView(@PathVariable String key, Model model, HttpServletRequest request) {
    log.info("\nACTION:PasswordReset");
    User user = registrationService.getUserForPasswordResetRequest(key);
    if (user != null) {
        StringBuffer requestURL = request.getRequestURL();
        String url = requestURL.substring(0, requestURL.lastIndexOf("/") + 1);
        log.debug("url: " + url);
        model.addAttribute("submitUrl", url);
        model.addAttribute("userFullName", user.getFullName());
        model.addAttribute("key", key);
        return "resetPassword.jsp";
    }//w w w  .j ava 2  s.  c om
    return "expiredPassword.jsp";
}

From source file:com.dyuproject.demos.openidservlet.HomeServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    if (request.getSession().getAttribute(WebConstants.SessionConstants.RC_USER) != null) {
        response.sendRedirect("/login/logged.html");
        return;/*w w w .  jav a2 s . c  om*/
    }
    String loginWith = request.getParameter("loginWith");
    if (loginWith != null) {
        // If the ui supplies a LoginWithGoogle or LoginWithYahoo
        // link/button,
        // this will speed up the openid process by skipping discovery.
        // The override is done by adding the OpenIdUser to the request
        // attribute.
        if (loginWith.equals("google")) {
            OpenIdUser user = OpenIdUser.populate("https://www.google.com/accounts/o8/id",
                    YadisDiscovery.IDENTIFIER_SELECT, "https://www.google.com/accounts/o8/ud");
            request.setAttribute(OpenIdUser.ATTR_NAME, user);

        } else if (loginWith.equals("yahoo")) {
            OpenIdUser user = OpenIdUser.populate("http://https://me.yahoo.com/user",
                    YadisDiscovery.IDENTIFIER_SELECT, "https://open.login.yahooapis.com/openid/op/auth");
            request.setAttribute(OpenIdUser.ATTR_NAME, user);
        }
    }

    String errorMsg = OpenIdServletFilter.DEFAULT_ERROR_MSG;
    try {
        OpenIdUser user = _relyingParty.discover(request);
        if (user == null) {
            if (RelyingParty.isAuthResponse(request)) {
                // authentication timeout
                response.sendRedirect(request.getRequestURI());
            } else {
                // set error msg if the openid_identifier is not resolved.
                if (request.getParameter(_relyingParty.getIdentifierParameter()) != null) {
                    request.setAttribute(OpenIdServletFilter.ERROR_MSG_ATTR, errorMsg);
                }

                // new user
                request.getRequestDispatcher("/login/login.jsp").forward(request, response);
            }
            return;
        }

        if (user.isAuthenticated()) {
            // user already authenticated
            request.getRequestDispatcher("/preAuth").forward(request, response);
            return;
        }

        if (user.isAssociated() && RelyingParty.isAuthResponse(request)) {
            // verify authentication
            if (_relyingParty.verifyAuth(user, request, response)) {
                // authenticated
                // redirect to home to remove the query params instead of
                // doing:
                // request.getRequestDispatcher("/home.jsp").forward(request,
                // response);
                response.sendRedirect(request.getContextPath() + "/home/");
            } else {
                // failed verification
                request.getRequestDispatcher("/login/login.jsp").forward(request, response);
            }
            return;
        }

        // associate and authenticate user
        StringBuffer url = request.getRequestURL();
        String trustRoot = url.substring(0, url.indexOf("/", 9));
        String realm = url.substring(0, url.lastIndexOf("/"));
        String returnTo = url.toString();
        if (_relyingParty.associateAndAuthenticate(user, request, response, trustRoot, realm, returnTo)) {
            // successful association
            return;
        }

    } catch (UnknownHostException uhe) {
        System.err.println("not found");
        errorMsg = OpenIdServletFilter.ID_NOT_FOUND_MSG;
    } catch (FileNotFoundException fnfe) {
        System.err.println("could not be resolved");
        errorMsg = OpenIdServletFilter.DEFAULT_ERROR_MSG;
    } catch (Exception e) {
        errorMsg = OpenIdServletFilter.DEFAULT_ERROR_MSG;
    }
    request.setAttribute(OpenIdServletFilter.ERROR_MSG_ATTR, errorMsg);

    request.getRequestDispatcher("/login/login.jsp").forward(request, response);
}

From source file:eionet.transfer.controller.FileOpsController.java

/**
 * Upload file for transfer./*from   w w w .  jav  a  2  s . c  om*/
 */
@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
public String importFile(@RequestParam("file") MultipartFile myFile, @RequestParam("fileTTL") int fileTTL,
        final RedirectAttributes redirectAttributes, final HttpServletRequest request) throws IOException {

    if (myFile == null || myFile.getOriginalFilename() == null) {
        redirectAttributes.addFlashAttribute("message", "Select a file to upload");
        return "redirect:fileupload";
    }
    if (fileTTL > 90) {
        redirectAttributes.addFlashAttribute("message", "Invalid expiration date");
        return "redirect:fileupload";
    }
    String uuidName = storeFile(myFile, fileTTL);
    redirectAttributes.addFlashAttribute("uuid", uuidName);
    StringBuffer requestUrl = request.getRequestURL();
    redirectAttributes.addFlashAttribute("url",
            requestUrl.substring(0, requestUrl.length() - "/fileupload".length()));
    return "redirect:fileupload";
    //return "redirect:uploadSuccess";
}

From source file:org.openmrs.module.idcards.web.servlet.PrintEmptyIdcardsServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse)
 *///w ww. java2  s .c  o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Integer mrnCount = ServletRequestUtils.getRequiredIntParameter(request, "mrn_count");
    Integer templateId = ServletRequestUtils.getIntParameter(request, "templateId", 1);
    String generatedMRNs = ServletRequestUtils.getStringParameter(request, "generated_mrns", "none");
    String password = ServletRequestUtils.getStringParameter(request, "pdf_password");
    if (!StringUtils.hasLength(password))
        throw new ServletException("A non-empty password is required.");

    IdcardsTemplate card = getIdcardsService().getIdcardsTemplate(templateId);

    StringBuffer requestURL = request.getRequestURL();
    String baseURL = requestURL.substring(0, requestURL.indexOf("/moduleServlet"));

    List<Integer> identifiers = null;

    if ("none".equals(generatedMRNs)) {
        identifiers = Collections.nCopies(mrnCount, 0);
    } else if ("pregenerated".equals(generatedMRNs)) {
        identifiers = getIdcardsService().printGeneratedIdentifiers(mrnCount, card);
    } else if ("generateNew".equals(generatedMRNs)) {
        Integer min = Integer
                .valueOf(Context.getAdministrationService().getGlobalProperty("idcards.generateMin"));
        Integer max = Integer
                .valueOf(Context.getAdministrationService().getGlobalProperty("idcards.generateMax"));
        identifiers = getIdcardsService().generateAndPrintIdentifiers(mrnCount, min, max, card);
    } else
        throw new ServletException("Invalid choice for 'generatedMRNs' parameter");

    generateOutput(card, baseURL, response, identifiers, password);

}

From source file:com.panet.imeta.core.row.ValueDataUtil.java

/**
 * Alternate faster version of string replace using a stringbuffer as input.
 * /*from   w w  w  .j  ava  2s.  c o m*/
 * @param str The string where we want to replace in
 * @param code The code to search for
 * @param repl The replacement string for code
 */
public static void replaceBuffer(StringBuffer str, String code, String repl) {
    int clength = code.length();

    int i = str.length() - clength;

    while (i >= 0) {
        String look = str.substring(i, i + clength);
        if (look.equalsIgnoreCase(code)) // Look for a match!
        {
            str.replace(i, i + clength, repl);
        }
        i--;
    }
}