Example usage for java.lang StringBuilder insert

List of usage examples for java.lang StringBuilder insert

Introduction

In this page you can find the example usage for java.lang StringBuilder insert.

Prototype

@Override
public StringBuilder insert(int offset, double d) 

Source Link

Usage

From source file:com.sciaps.view.SpectrumShotPanel.java

public void addItems(ArrayList<SpectrumShotItem> shotItems) {
    StringBuilder errMsg = new StringBuilder();
    for (SpectrumShotItem item : shotItems) {
        if (shotListTableModel_.isNameAlreadyExist(item.getName())) {
            errMsg.append(item.getName()).append(",");
        } else {/* www . j av  a2 s.c o  m*/
            shotListTableModel_.addRow(item);
        }
    }

    if (errMsg.length() != 0) {
        errMsg.insert(0, "The following shot(s) can't be added due to duplicated name:\n");
        errMsg.append("\n");
        showErrorDialog(errMsg.toString());
    }
}

From source file:cn.webwheel.DefaultMain.java

/**
 * Wrap exception to a json object and return it to client.
 * <p>// w  ww .j a  v  a  2 s. co m
 * <b>json object format:</b><br/>
 * <p><blockquote><pre>
 *     {
 *         "msg": "the exception's message",
 *         "stackTrace":[
 *             "exception's stack trace1",
 *             "exception's stack trace2",
 *             "exception's stack trace3",
 *             ....
 *         ]
 *     }
 * </pre></blockquote></p>
 */
public Object executeActionError(WebContext ctx, ActionInfo ai, Object action, Throwable e) throws Throwable {
    if (e instanceof LogicException) {
        return ((LogicException) e).getResult();
    }
    Logger.getLogger(DefaultMain.class.getName()).log(Level.SEVERE, "action execution error", e);
    StringBuilder sb = new StringBuilder();
    sb.append("{\n");
    String s;
    try {
        s = JsonResult.objectMapper.writeValueAsString(e.toString());
    } catch (IOException e1) {
        s = "\"" + e.toString().replace("\"", "'") + "\"";
    }
    sb.append("    \"msg\" : " + s + ",\n");
    sb.append("    \"stackTrace\" : [");
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    String[] ss = sw.toString().split("\r\n");
    for (int i = 1; i < ss.length; i++) {
        if (sb.charAt(sb.length() - 1) != '[') {
            sb.append(',');
        }
        sb.append("\n        ").append(JsonResult.objectMapper.writeValueAsString(ss[i]));
    }
    sb.append("\n    ]\n");
    sb.append("}");
    HttpServletResponse response = ctx.getResponse();
    if (JsonResult.defWrapMultipart && ServletFileUpload.isMultipartContent(ctx.getRequest())
            && !"XMLHttpRequest".equals(ctx.getRequest().getHeader("X-Requested-With"))) {
        response.setContentType("text/html");
        sb.insert(0, "<textarea>\n");
        sb.append("\n</textarea>");
    } else {
        response.setContentType("application/json");
    }
    response.setCharacterEncoding("utf-8");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Pragma", "no-cache");
    response.setHeader("Expires", "-1");
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.getWriter().write(sb.toString());
    return EmptyResult.inst;
}

From source file:org.georchestra.security.Proxy.java

private String concat(String target, StringBuilder builder) {
    if (target == null) {
        return null;
    }/*from   w  ww  .  j  a  va 2s . com*/
    String target2 = target;
    if (target.endsWith("/")) {
        target2 = target.substring(0, target.length() - 1);
    }
    if (builder.charAt(0) != '/') {
        builder.insert(0, '/');
    }
    return target2 + builder;

}

From source file:com.lcw.one.modules.sys.web.UserController.java

@RequiresPermissions("sys:user:edit")
@RequestMapping(value = "import", method = RequestMethod.POST)
public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
    if (Global.isDemoMode()) {
        addMessage(redirectAttributes, "?????");
        return "redirect:" + Global.getAdminPath() + "/sys/user/?repage";
    }/*from  w w  w. j av  a 2 s.  c o m*/

    try {
        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        ImportExcel ei = new ImportExcel(file, 1, 0);
        List<User> list = ei.getDataList(User.class);
        for (User user : list) {
            try {
                if ("true".equals(checkLoginName("", user.getLoginName()))) {
                    user.setPassword(SystemService.entryptPassword("123456"));
                    BeanValidators.validateWithException(validator, user);
                    systemService.saveUser(user);
                    successNum++;
                } else {
                    failureMsg.append("<br/>?? " + user.getLoginName() + " ; ");
                    failureNum++;
                }
            } catch (ConstraintViolationException ex) {
                failureMsg.append("<br/>?? " + user.getLoginName() + " ");
                List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                for (String message : messageList) {
                    failureMsg.append(message + "; ");
                    failureNum++;
                }
            } catch (Exception ex) {
                failureMsg
                        .append("<br/>?? " + user.getLoginName() + " " + ex.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, " " + failureNum + " ??");
        }
        addMessage(redirectAttributes, "? " + successNum + " ?" + failureMsg);
    } catch (Exception e) {
        addMessage(redirectAttributes, "??" + e.getMessage());
    }
    return "redirect:" + Global.getAdminPath() + "/sys/user/?repage";
}

From source file:com.sfs.whichdoctor.webservice.RotationServiceImpl.java

/**
 * Get a list of relevant rotations for people for the specified date range.
 *
 * @param PEOsysids - the unique person identifers (as a CSV list of numbers)
 * @param periodFrom - the start date to retrieve rotations from
 * @param periodTo - the end date to retrieve rotations from
 *
 * @return the trainee rotations/*from   w  w  w  .ja  v a2s . co m*/
 */
public final String getRotations(final String PEOsysids, final Calendar periodFrom, final Calendar periodTo) {

    StringBuilder results = new StringBuilder();

    if (this.getAllowedAddress() && StringUtils.isNotBlank(PEOsysids)) {
        List<Integer> identifiers = parseIdentifiers(PEOsysids);

        for (int identifier : identifiers) {

            PersonsRotations pr = loadRotations(identifier, periodFrom, periodTo);

            results.append(this.rotationXmlOutput.getSecondGenRotations(pr.getRotations(), identifier,
                    pr.getDivision(), pr.getCurrentRotations()));
        }
    }

    if (results.length() > 0) {
        results.insert(0, "<trainees>");
        results.append("</trainees>");
    } else {
        results.append("<trainees />");
    }

    return results.toString();
}

From source file:com.sfs.whichdoctor.webservice.RotationServiceImpl.java

/**
 * Gets a list of relevant trainee rotations for a person for the specified
 * date range and training type./*  w ww  . ja v a 2  s.  c  o  m*/
 *
 * @param PEOsysids the PEOsysids
 * @param periodFrom the period from
 * @param periodTo the period to
 * @param trainingType the training type
 * @return the trainee rotations
 */
public final String GetTraineeRotations(final String PEOsysids, final Calendar periodFrom,
        final Calendar periodTo, final String trainingType) {

    StringBuilder results = new StringBuilder();

    if (this.getAllowedAddress() && StringUtils.isNotBlank(PEOsysids)) {
        List<Integer> identifiers = parseIdentifiers(PEOsysids);

        for (int identifier : identifiers) {

            PersonsRotations pr = loadRotations(identifier, periodFrom, periodTo);

            results.append(this.rotationXmlOutput.getThirdGenRotations(
                    orderThirdGenRotations(pr.getRotations()), identifier, pr.getDivision(), trainingType));
        }
    }

    if (results.length() > 0) {
        results.insert(0, "<Trainees>");
        results.append("</Trainees>");
    } else {
        results.append("<Trainees />");
    }

    return results.toString();
}

From source file:de.tudarmstadt.ukp.csniper.webapp.search.xmi.SerializedCasContextProvider.java

@Override
public ItemContext getContext(EvaluationItem aItem, int aLeftSize, int aRightSize) throws IOException {
    Timer timer = new Timer();

    File base = new File(new File(corpusService.getRepositoryPath(), aItem.getCollectionId().toUpperCase()),
            BIN);/* w w w .ja va 2 s.c  o  m*/
    String docId = aItem.getDocumentId();
    JCasState state = jcasThreadLocal.get();
    if ((state.documentId == null) || (state.collectionId == null)
            || !StringUtils.equals(state.documentId, docId)
            || !StringUtils.equals(state.collectionId, aItem.getCollectionId())) {
        timer.start();

        ObjectInputStream is = null;
        try {
            // No need to reset the CAS
            is = new ObjectInputStream(
                    new XZCompressorInputStream(new FileInputStream(new File(base, docId + ".ser.xz"))));

            CASCompleteSerializer serializer = (CASCompleteSerializer) is.readObject();
            deserializeCASComplete(serializer, (CASImpl) state.cas);

            state.documentId = aItem.getDocumentId();
            state.collectionId = aItem.getCollectionId();
        } catch (IllegalStateException e) {
            throw new IOException(e);
        } catch (ClassNotFoundException e) {
            throw new IOException(e);
        } finally {
            closeQuietly(is);
        }

        timer.stop();
        log.debug("Reading the CAS took " + timer.getTime() + "ms");
    } else {
        log.debug("Reusing CAS");
    }

    timer.reset();
    timer.start();

    // text offset based
    String text = state.cas.getDocumentText();

    // Absolute offsets
    int windowBegin = Math.max(0, (int) aItem.getBeginOffset() - aLeftSize);
    int windowEnd = Math.min(text.length(), (int) aItem.getEndOffset() + aRightSize);

    // Relative offsets
    int unitBegin = (int) aItem.getBeginOffset() - windowBegin;
    int unitEnd = (int) aItem.getEndOffset() - windowBegin;

    StringBuilder windowText = new StringBuilder(text.substring(windowBegin, windowEnd));

    List<Token> tokens;
    try {
        tokens = JCasUtil.selectCovered(state.cas.getJCas(), Token.class, (int) aItem.getBeginOffset(),
                (int) aItem.getEndOffset());
    } catch (CASException e) {
        throw new IOException(e);
    }
    int unitEndDisplacement = 0;
    int matchEndDisplacement = 0;
    int matchBeginDisplacement = 0;

    boolean anyMatchSet = false;
    int matchBeginOffset = aItem.getOriginalTextMatchBegin();
    int matchEndOffset = aItem.getOriginalTextMatchEnd();

    if (aItem.isOriginalMatchSet()) {
        matchBeginOffset = aItem.getOriginalTextMatchBegin();
        matchEndOffset = aItem.getOriginalTextMatchEnd();
        anyMatchSet = true;
    } else if (aItem.isTokenMatchSet()) {
        matchBeginOffset = tokens.get(aItem.getTokenMatchBegin()).getBegin();
        matchEndOffset = tokens.get(aItem.getTokenMatchEnd()).getEnd();
        anyMatchSet = true;
    }

    Collections.reverse(tokens);
    // compute actual offsets if token based offsets are set
    if (outputPos) {
        for (Token t : tokens) {
            if (t.getPos() != null && t.getPos().getPosValue() != null) {
                String postfix = "/" + t.getPos().getPosValue();
                windowText.insert(t.getEnd() - windowBegin, postfix);
                unitEndDisplacement += postfix.length();
                if (anyMatchSet) {
                    if ((t.getEnd() <= matchEndOffset) && (t.getBegin() >= matchBeginOffset)) {
                        matchEndDisplacement += postfix.length();
                    }
                    if (t.getEnd() <= matchBeginOffset) {
                        matchBeginDisplacement += postfix.length();
                    }
                }
            }
        }
    }

    ItemContext ctx = new ItemContext(windowText.toString(), windowBegin, windowEnd, unitBegin,
            unitEnd + unitEndDisplacement);

    if (anyMatchSet) {
        ctx.setMatch(matchBeginOffset - windowBegin + matchBeginDisplacement,
                matchEndOffset - windowBegin + matchBeginDisplacement + matchEndDisplacement);
    }

    ctx.setTextLength(text.length());

    timer.stop();
    log.debug("Extracting the context took " + timer.getTime() + "ms");

    return ctx;
}

From source file:com.github.rwitzel.streamflyer.xml.XmlVersionModifier.java

/**
 * @see com.github.rwitzel.streamflyer.core.Modifier#modify(java.lang.StringBuilder, int, boolean)
 *///from  w ww . ja  v a 2  s.  co m
@Override
public AfterModification modify(StringBuilder characterBuffer, int firstModifiableCharacterInBuffer,
        boolean endOfStreamHit) {

    switch (state) {

    case NO_LONGER_MODIFYING:

        return factory.skipEntireBuffer(characterBuffer, firstModifiableCharacterInBuffer, endOfStreamHit);

    case INITIAL:

        state = XmlVersionModifierState.PROLOG_REQUEST;

        // you never know how many whitespace characters are in the prolog
        return factory.modifyAgainImmediately(INITIAL_NUMBER_OF_CHARACTERS, firstModifiableCharacterInBuffer);

    case PROLOG_REQUEST:

        // (Should we do aware of BOMs here? No. I consider it the
        // responsibility of the caller to provide characters without BOM.)

        Matcher matcher = Pattern.compile("<\\?xml[^>]*version\\s*=\\s*['\"]((1.0)|(1.1))['\"].*")
                .matcher(characterBuffer);
        if (matcher.matches()) {

            // replace version in prolog
            characterBuffer.replace(matcher.start(1), matcher.end(1), xmlVersion);
        } else {
            // is there a prolog that is too long?
            Matcher matcher2 = Pattern.compile("<\\?xml.*").matcher(characterBuffer);
            if (matcher2.matches()) {
                // this is not normal at all -> throw exception
                throw new XmlPrologRidiculouslyLongException(characterBuffer.toString());
            }

            // insert prolog
            characterBuffer.insert(0, "<?xml version='" + xmlVersion + "'>");
        }

        state = XmlVersionModifierState.NO_LONGER_MODIFYING;

        return factory.skipEntireBuffer(characterBuffer, firstModifiableCharacterInBuffer, endOfStreamHit);

    default:
        throw new IllegalStateException("state " + state + " not supported");

    }

}

From source file:com.aistor.modules.sys.web.UserController.java

@RequiresPermissions("sys:user:edit")
@RequestMapping(value = "import", method = RequestMethod.POST)
public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
    try {/*from   w  w w .  j  a va 2 s .  c o  m*/
        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        ImportExcel ei = new ImportExcel(file, 1, 0);
        List<User> list = ei.getDataList(User.class);
        for (User user : list) {
            try {
                if ("true".equals(checkLoginName("", user.getLoginName()))) {
                    user.setPassword(SystemService.entryptPassword("123456"));
                    BeanValidators.validateWithException(validator, user);
                    systemService.saveUser(user);
                    successNum++;
                } else {
                    failureMsg.append("<br/>?? " + user.getLoginName() + " ; ");
                    failureNum++;
                }
            } catch (ConstraintViolationException ex) {
                failureMsg.append("<br/>?? " + user.getLoginName() + " ");
                List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                for (String message : messageList) {
                    failureMsg.append(message + "; ");
                    failureNum++;
                }
            } catch (Exception ex) {
                failureMsg
                        .append("<br/>?? " + user.getLoginName() + " " + ex.getMessage());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, " " + failureNum + " ??");
        }
        addMessage(redirectAttributes, "? " + successNum + " ?" + failureMsg);
    } catch (Exception e) {
        addMessage(redirectAttributes, "??" + e.getMessage());
    }
    return "redirect:" + Global.ADMIN_PATH + "/sys/user/?repage";
}