Example usage for java.lang StringBuilder delete

List of usage examples for java.lang StringBuilder delete

Introduction

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

Prototype

@Override
public StringBuilder delete(int start, int end) 

Source Link

Usage

From source file:com.virtusa.akura.reporting.controller.CRStudentPerformanceController.java

/**
 * Method is to return GradeClass list.//from  ww w .j  a va 2s.c om
 *
 * @param request - HttpServletRequest
 * @param modelMap - ModelMap attribute.
 * @return list of classGrade
 * @throws AkuraAppException - Detailed exception
 */

@RequestMapping(value = GRADE_CLASS_HTM)
@ResponseBody
public String populateGradeClass(ModelMap modelMap, HttpServletRequest request) throws AkuraAppException {

    StringBuilder allGradeClass = new StringBuilder();
    int gradeId = Integer.parseInt(request.getParameter(SELECTED_VALUE));
    Grade grade = commonService.findGradeById(gradeId);
    List<ClassGrade> classGrades = commonService.getClassGradeListByGrade(grade);
    boolean isFirst = true;
    StringBuilder classes = new StringBuilder();

    for (ClassGrade classGrade : classGrades) {
        classes.append(classGrade.getDescription());
        classes.append("_");
        classes.append(classGrade.getClassGradeId());

        if (isFirst) {
            allGradeClass.append(classes.toString()); // no comma
            isFirst = false;
        } else {
            allGradeClass.append(","); // comma
            allGradeClass.append(classes.toString());
        }
        classes.delete(0, classes.length());
    }
    return allGradeClass.toString();
}

From source file:it.unibo.alchemist.language.protelis.datatype.ArrayTupleImpl.java

@Override
public String toString() {
    if (string == null) {
        final StringBuilder sb = new StringBuilder();
        sb.append('[');
        for (final Object o : a) {
            final boolean notNumber = !(o instanceof Number || o instanceof Tuple);
            final boolean isString = o instanceof String;
            if (isString) {
                sb.append('"');
            } else if (notNumber) {
                sb.append('\'');
            }//  w  ww .j av a2 s .  co m
            sb.append(o.toString());
            if (isString) {
                sb.append('"');
            } else if (notNumber) {
                sb.append('\'');
            }
            sb.append(", ");
        }
        if (a.length > 0) {
            sb.delete(sb.length() - 2, sb.length());
        }
        sb.append(']');
        string = sb.toString();
    }
    return string;
}

From source file:com.virtusa.akura.common.controller.ManageAssignmentController.java

/**
 * Method is to return list of subjects which are related to the Grade.
 *
 * @return a map which has key - grade and value - list of grade subjects.
 * @param request of type HttpServletRequest
 * @param modelMap - a ModelMap contains the subjects.
 * @throws AkuraAppException - Details exception
 */// ww  w .j a  va 2 s .c  o  m
@RequestMapping(value = GRADE_SUBJECT_HTM)
@ResponseBody
public String populateGradeSubject(ModelMap modelMap, HttpServletRequest request) throws AkuraAppException {

    StringBuilder allGradeSubject = new StringBuilder();
    int gradeId = Integer.parseInt(request.getParameter(SELECTED_VALUE));

    List<GradeSubject> subjectGrades = commonService.getGradeSubjectIdListByGrade(gradeId);

    boolean isFirst = true;

    StringBuilder subjects = new StringBuilder();

    for (GradeSubject subjectGrade : subjectGrades) {
        subjects.append(subjectGrade.getSubject().getDescription());
        subjects.append(AkuraWebConstant.UNDERSCORE_STRING);
        subjects.append(subjectGrade.getGradeSubjectId());

        if (isFirst) {
            allGradeSubject.append(subjects.toString()); // no comma
            isFirst = false;
        } else {
            allGradeSubject.append(AkuraWebConstant.STRING_COMMA); // comma
            allGradeSubject.append(subjects.toString());
        }
        subjects.delete(0, subjects.length());
    }
    return allGradeSubject.toString();
}

From source file:it.doqui.index.ecmengine.business.personalization.multirepository.index.lucene.RepositoryAwareADMLuceneSearcherImpl.java

private String parameterise(String unparameterised, Map<QName, QueryParameterDefinition> map,
        QueryParameter[] queryParameters, NamespacePrefixResolver nspr) throws QueryParameterisationException {

    Map<QName, List<Serializable>> valueMap = new HashMap<QName, List<Serializable>>();

    if (queryParameters != null) {
        for (QueryParameter parameter : queryParameters) {
            List<Serializable> list = valueMap.get(parameter.getQName());
            if (list == null) {
                list = new ArrayList<Serializable>();
                valueMap.put(parameter.getQName(), list);
            }/* w  w w .j a v  a  2  s.  c o m*/
            list.add(parameter.getValue());
        }
    }

    Map<QName, ListIterator<Serializable>> iteratorMap = new HashMap<QName, ListIterator<Serializable>>();

    List<QName> missing = new ArrayList<QName>(1);
    StringBuilder buffer = new StringBuilder(unparameterised);
    int index = 0;
    while ((index = buffer.indexOf("${", index)) != -1) {
        int endIndex = buffer.indexOf("}", index);
        String qNameString = buffer.substring(index + 2, endIndex);
        QName key = QName.createQName(qNameString, nspr);
        QueryParameterDefinition parameterDefinition = map.get(key);
        if (parameterDefinition == null) {
            missing.add(key);
            buffer.replace(index, endIndex + 1, "");
        } else {
            ListIterator<Serializable> it = iteratorMap.get(key);
            if ((it == null) || (!it.hasNext())) {
                List<Serializable> list = valueMap.get(key);
                if ((list != null) && (list.size() > 0)) {
                    it = list.listIterator();
                }
                if (it != null) {
                    iteratorMap.put(key, it);
                }
            }
            String value;
            if (it == null) {
                value = parameterDefinition.getDefault();
            } else {
                value = DefaultTypeConverter.INSTANCE.convert(String.class, it.next());
            }
            buffer.replace(index, endIndex + 1, value);
        }
    }
    if (missing.size() > 0) {
        StringBuilder error = new StringBuilder();
        error.append("The query uses the following parameters which are not defined: ");
        for (QName qName : missing) {
            error.append(qName);
            error.append(", ");
        }
        error.delete(error.length() - 1, error.length() - 1);
        error.delete(error.length() - 1, error.length() - 1);
        throw new QueryParameterisationException(error.toString());
    }
    return buffer.toString();
}

From source file:info.icefilms.icestream.browse.Location.java

protected static String DownloadPage(URL url, String sendCookie, String sendData, StringBuilder getCookie,
        Callback callback) {//from   w w w . ja  v  a2s  .c  om
    // Declare our buffer
    ByteArrayBuffer byteArrayBuffer;

    try {
        // Setup the connection
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux i686; rv:2.0) Gecko/20100101 Firefox/4.0");
        urlConnection.setRequestProperty("Referer", mIceFilmsURL.toString());
        if (sendCookie != null)
            urlConnection.setRequestProperty("Cookie", sendCookie);
        if (sendData != null) {
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setDoOutput(true);
        }
        urlConnection.setConnectTimeout(callback.GetConnectionTimeout());
        urlConnection.setReadTimeout(callback.GetConnectionTimeout());
        urlConnection.connect();

        // Get the output stream and send the data
        if (sendData != null) {
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(sendData.getBytes());
            outputStream.flush();
            outputStream.close();
        }

        // Get the cookie
        if (getCookie != null) {
            // Clear the string builder
            getCookie.delete(0, getCookie.length());

            // Loop thru the header fields
            String headerName;
            String cookie;
            for (int i = 1; (headerName = urlConnection.getHeaderFieldKey(i)) != null; ++i) {
                if (headerName.equalsIgnoreCase("Set-Cookie")) {
                    // Get the cookie
                    cookie = GetGroup("([^=]+=[^=;]+)", urlConnection.getHeaderField(i));

                    // Add it to the string builder
                    if (cookie != null)
                        getCookie.append(cookie);

                    break;
                }
            }
        }

        // Get the input stream
        InputStream inputStream = urlConnection.getInputStream();

        // For some reason we can actually get a null InputStream instead of an exception
        if (inputStream == null) {
            Log.e("Ice Stream", "Page download failed. Unable to create Input Stream.");
            if (callback.GetErrorBoolean() == false) {
                callback.SetErrorBoolean(true);
                callback.SetErrorStringID(R.string.browse_page_download_error);
            }
            urlConnection.disconnect();
            return null;
        }

        // Get the file size
        final int fileSize = urlConnection.getContentLength();

        // Create our buffers
        byte[] byteBuffer = new byte[2048];
        byteArrayBuffer = new ByteArrayBuffer(2048);

        // Download the page
        int amountDownloaded = 0;
        int count;
        while ((count = inputStream.read(byteBuffer, 0, 2048)) != -1) {
            // Check if we got canceled
            if (callback.IsCancelled()) {
                inputStream.close();
                urlConnection.disconnect();
                return null;
            }

            // Add data to the buffer
            byteArrayBuffer.append(byteBuffer, 0, count);

            // Update the downloaded amount
            amountDownloaded += count;
        }

        // Close the connection
        inputStream.close();
        urlConnection.disconnect();

        // Check for amount downloaded calculation error
        if (fileSize != -1 && amountDownloaded != fileSize) {
            Log.w("Ice Stream", "Total amount downloaded (" + amountDownloaded + " bytes) does not "
                    + "match reported content length (" + fileSize + " bytes).");
        }
    } catch (SocketTimeoutException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_timeout_error);
        }
        return null;
    } catch (IOException exception) {
        Log.e("Ice Stream", "Page download failed.", exception);
        if (callback.GetErrorBoolean() == false) {
            callback.SetErrorBoolean(true);
            callback.SetErrorStringID(R.string.browse_page_download_error);
        }
        return null;
    }

    // Convert things to a string
    return new String(byteArrayBuffer.toByteArray());
}

From source file:org.matsim.pt.counts.obsolete.PtCountSimComparisonKMLWriter.java

/**
 * Creates the CountsErrorGraph for all the data
 *
 * @param kmlFilename//from ww w .  j  a  v a2 s  . com
 *            the filename of the kml file
 * @param visible
 *            true if initially visible
 * @return the ScreenOverlay Feature
 */

private ScreenOverlayType createBiasErrorGraph(PtCountsType type, String kmlFilename) {
    int index = kmlFilename.lastIndexOf(System.getProperty("file.separator"));
    if (index == -1) {
        index = kmlFilename.lastIndexOf('/');
    }
    String outdir;
    if (index == -1) {
        outdir = "";
    } else {
        outdir = kmlFilename.substring(0, index) + System.getProperty("file.separator");
    }
    // ------------------------------------------------------------------------------

    List<CountSimComparison> countComparisonFilter;
    switch (type) {
    case Boarding:
        countComparisonFilter = this.boardCountComparisonFilter.getCountsForHour(null);
        break;
    case Alighting:
        countComparisonFilter = this.alightCountComparisonFilter.getCountsForHour(null);
        break;
    default:
        countComparisonFilter = this.occupancyCountComparisonFilter.getCountsForHour(null);
    }
    PtBiasErrorGraph pbeg = new PtBiasErrorGraph(countComparisonFilter, this.iter, null,
            "error graph - " + type.name());
    pbeg.createChart(0);

    double[] meanError = pbeg.getMeanRelError();
    double[] meanBias = pbeg.getMeanAbsBias();

    String file = outdir + "biasErrorGraphData" + type.name() + ".txt";
    log.info("writing chart data to " + new File(file).getAbsolutePath());
    try {
        BufferedWriter bwriter = IOUtils.getBufferedWriter(file);
        StringBuilder buffer = new StringBuilder(100);
        buffer.append("hour \t mean relative error \t mean absolute bias");
        bwriter.write(buffer.toString());
        bwriter.newLine();
        for (int i = 0; i < meanError.length; i++) {
            buffer.delete(0, buffer.length());
            buffer.append(i + 1);
            buffer.append('\t');
            buffer.append(meanError[i]);
            buffer.append('\t');
            buffer.append(meanBias[i]);
            bwriter.write(buffer.toString());
            bwriter.newLine();
        }
        bwriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String chartFilename = "errorGraphErrorBias" + type.name() + ".png";
    try {
        writeChartToKmz(chartFilename, pbeg.getChart());
        return createOverlayBottomRight(chartFilename, "Error Graph [Error/Bias]");
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:com.cesnet.pki.DigicertConnector.java

/**
 * Calls digicert by specific url with given api key
 * /*from w w  w.j  av a2 s  .c  om*/
 * @param urlSuffix the String to parse as a URL
 * @param apiKey api key
 * @return String of certificate base64 encoded data
 * @throws MalformedURLException if no protocol is specified, or an unknown protocol is found, or spec is null
 * @throws ProtocolException if the method cannot be reset or if the requested method isn't valid for HTTP
 * @throes SecurityException if a security manager is set and the method is "TRACE", but the "allowHttpTrace" NetPermission is not granted
 * @throws IllegalArgumentException if Input-buffer size is less or equal zero
 * @throws UnsupportedEncodingException if the named charset is not supported
 * @throws IOException if an I/O error occurs while creating the input stream
 * @throws UnknownServiceException if the protocol does not support input
 */
private String callDigicert(String urlSuffix, String apiKey)
        throws MalformedURLException, ProtocolException, SecurityException, IllegalArgumentException,
        UnsupportedEncodingException, IOException, UnknownServiceException {

    StringBuilder builder = new StringBuilder();
    String currentLine;

    URL url = new URL(urlBase + urlSuffix);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    conn.setRequestMethod("GET");
    conn.setRequestProperty("X-DC-DEVKEY", apiKey);
    conn.setRequestProperty("Accept", "*/*");
    conn.setDoOutput(true);

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
        while ((currentLine = reader.readLine()) != null) {
            builder.append(currentLine);
        }
    } catch (Exception e) {
        System.out.println("apiKey\t" + apiKey);
        System.out.println(e.getMessage());
        return null;
    }

    builder.delete(0, "-----BEGIN PKCS7-----".length()); // we do not want first line (-----BEGIN PKCS7-----)
    builder.delete(builder.length() - ("-----END PKCS7-----".length()), builder.length()); // neather -----END PKCS7-----

    return builder.toString();
}

From source file:com.androgogic.AikauLoginController.java

/**
 * /* www  .  java  2s.  co m*/
 * @param request
 * @param response
 * @throws Exception
 */
protected void beforeSuccess(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {
        final HttpSession session = request.getSession();

        // Get the authenticated user name and use it to retrieve all of the groups that the user is a member of...
        String username = (String) request.getParameter(PARAM_USERNAME);
        if (username == null) {
            username = (String) session.getAttribute(UserFactory.SESSION_ATTRIBUTE_KEY_USER_ID);
        }

        if (username != null && session.getAttribute(SESSION_ATTRIBUTE_KEY_USER_GROUPS) == null) {
            Connector conn = FrameworkUtil.getConnector(session, username,
                    AlfrescoUserFactory.ALFRESCO_ENDPOINT_ID);
            ConnectorContext c = new ConnectorContext(HttpMethod.GET);
            c.setContentType("application/json");
            Response res = conn.call("/api/people/" + URLEncoder.encode(username) + "?groups=true", c);
            if (Status.STATUS_OK == res.getStatus().getCode()) {
                // Assuming we get a successful response then we need to parse the response as JSON and then
                // retrieve the group data from it...
                // 
                // Step 1: Get a String of the response...
                String resStr = res.getResponse();

                // Step 2: Parse the JSON...
                JSONParser jp = new JSONParser();
                Object userData = jp.parse(resStr.toString());

                // Step 3: Iterate through the JSON object getting all the groups that the user is a member of...
                StringBuilder groups = new StringBuilder(512);
                if (userData instanceof JSONObject) {
                    Object groupsArray = ((JSONObject) userData).get("groups");
                    if (groupsArray instanceof org.json.simple.JSONArray) {
                        for (Object groupData : (org.json.simple.JSONArray) groupsArray) {
                            if (groupData instanceof JSONObject) {
                                Object groupName = ((JSONObject) groupData).get("itemName");
                                if (groupName != null) {
                                    groups.append(groupName.toString()).append(',');
                                }
                            }
                        }
                    }
                }

                // Step 4: Trim off any trailing commas...
                if (groups.length() != 0) {
                    groups.delete(groups.length() - 1, groups.length());
                }

                // Step 5: Store the groups on the session...
                session.setAttribute(SESSION_ATTRIBUTE_KEY_USER_GROUPS, groups.toString());
            } else {
                session.setAttribute(SESSION_ATTRIBUTE_KEY_USER_GROUPS, "");
            }
        }
    } catch (ConnectorServiceException e1) {
        throw new Exception("Error creating remote connector to request user group data.");
    }
}

From source file:com.cloud.utils.db.SqlGenerator.java

public Pair<StringBuilder, Attribute[]> buildSelectSql(boolean enableQueryCache) {
    StringBuilder sql = new StringBuilder("SELECT ");

    sql.append(enableQueryCache ? "SQL_CACHE " : "");

    ArrayList<Attribute> attrs = new ArrayList<Attribute>();

    for (Attribute attr : _attributes) {
        if (attr.isSelectable()) {
            attrs.add(attr);/*  w  ww .  j  a  v a2s. c o  m*/
            sql.append(attr.table).append(".").append(attr.columnName).append(", ");
        }
    }

    if (attrs.size() > 0) {
        sql.delete(sql.length() - 2, sql.length());
    }

    sql.append(" FROM ").append(buildTableReferences());

    sql.append(" WHERE ");

    sql.append(buildDiscriminatorClause().first());

    return new Pair<StringBuilder, Attribute[]>(sql, attrs.toArray(new Attribute[attrs.size()]));
}

From source file:fr.paris.lutece.plugins.workflow.modules.ticketing.service.task.TaskEditTicket.java

/**
 * Process the task for agent side/*w  ww  .j  a v  a  2  s .  c o m*/
 * @param nIdResourceHistory the ResourceHistory id
 * @param request the request
 * @param locale the locale
 * @param config the task configuration
 * @return the information message to store
 */
private String processAgentTask(int nIdResourceHistory, HttpServletRequest request, Locale locale,
        TaskEditTicketConfig config) {
    String strTaskInformation = StringUtils.EMPTY;

    String strAgentMessage = request.getParameter(PARAMETER_MESSAGE + UNDERSCORE + getId());
    String[] listIdsEntry = request.getParameterValues(PARAMETER_IDS_ENTRY + UNDERSCORE + getId());

    // We get the ticket to modify
    Ticket ticket = getTicket(nIdResourceHistory);

    boolean bCreate = false;
    List<EditableTicketField> listEditableTicketFields = new ArrayList<EditableTicketField>();

    EditableTicket editableTicket = _editableTicketService.find(nIdResourceHistory, getId());

    if (editableTicket == null) {
        editableTicket = new EditableTicket();
        editableTicket.setIdHistory(nIdResourceHistory);
        editableTicket.setIdTask(getId());
        editableTicket.setIdTicket(ticket.getId());
        bCreate = true;
    }

    StringBuilder sbEntries = new StringBuilder();

    if (listIdsEntry != null) {
        for (String strIdEntry : listIdsEntry) {
            if (StringUtils.isNotBlank(strIdEntry) && StringUtils.isNumeric(strIdEntry)) {
                int nIdEntry = Integer.parseInt(strIdEntry);
                EditableTicketField editableTicketField = new EditableTicketField();
                editableTicketField.setIdEntry(nIdEntry);

                listEditableTicketFields.add(editableTicketField);

                Entry entry = EntryHome.findByPrimaryKey(nIdEntry);
                sbEntries.append(entry.getTitle()).append(SEPARATOR);
            }
        }

        if (sbEntries.length() != 0) {
            sbEntries.delete(sbEntries.length() - SEPARATOR.length(), sbEntries.length());
        }
    }

    editableTicket.setMessage(StringUtils.isNotBlank(strAgentMessage) ? strAgentMessage : StringUtils.EMPTY);
    editableTicket.setListEditableTicketFields(listEditableTicketFields);
    editableTicket.setIsEdited(false);

    if (bCreate) {
        _editableTicketService.create(editableTicket);
    } else {
        _editableTicketService.update(editableTicket);
    }

    if (ticket != null) {
        ticket.setUrl(buildEditUrl(request, nIdResourceHistory, getId(), config.getIdUserEditionAction()));
        TicketHome.update(ticket);
    }

    if (sbEntries.length() == 0) {
        strTaskInformation = MessageFormat.format(I18nService.getLocalizedString(
                MESSAGE_EDIT_TICKET_INFORMATION_VIEW_AGENT_NO_FIELD_EDITED, Locale.FRENCH), strAgentMessage);
    } else {
        strTaskInformation = MessageFormat.format(
                I18nService.getLocalizedString(MESSAGE_EDIT_TICKET_INFORMATION_VIEW_AGENT, Locale.FRENCH),
                sbEntries.toString(), strAgentMessage);
    }

    return strTaskInformation;
}