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:it.unibas.spicy.model.algebra.query.operators.sql.GenerateSQL.java

public static String projectionOnTargetValuesFromCorrespondences(List<VariableCorrespondence> correspondences,
        String fromClause, String whereClause) {
    StringBuilder result = new StringBuilder();
    result.append(INDENT).append("select distinct \n");
    List<String> alreadyCorrespondences = new ArrayList<String>();
    for (int i = 0; i < correspondences.size(); i++) {
        VariableCorrespondence correspondence = correspondences.get(i);
        //giannisk 
        //so as not to take into account constant values
        if (!correspondence.isConstant()) {
            //giannisk, so as not to take into account variables already selected
            if (!alreadyCorrespondences.contains(correspondence.getFirstSourcePath().toString())) {
                if (correspondence.getSourcePaths() != null) {
                    result.append(DOUBLE_INDENT)
                            .append(GenerateSQL.attributeNameWithVariable(correspondence.getFirstSourcePath()));
                    alreadyCorrespondences.add(correspondence.getFirstSourcePath().toString());
                } else {
                    String sourcePathName = correspondence.getSourceValue().toString();
                    sourcePathName = sourcePathName.replaceAll("\"", "\'");
                    result.append(DOUBLE_INDENT).append(sourcePathName);
                }/*from  w  w w  . j av  a  2  s .  c  o  m*/

                result.append(" as ")
                        .append(GenerateSQL.attributeNameInVariable(correspondence.getFirstSourcePath()));
                result.append(",\n");
                /*if ((i != correspondences.size() - 1)
                    //giannisk 
                    //so as not to take into account constant values
                    && (!correspondences.get(i+1).isConstant())) {
                result.append(",\n");
                }*/
            }
        }
    }
    //giannisk
    //delete the last "," character
    result = result.delete(result.length() - 2, result.length());
    result.append("\n");
    result.append(INDENT).append(fromClause);
    if (!whereClause.equals("")) {
        result.append(INDENT).append(whereClause);
    }
    return result.toString();
}

From source file:com.softwarecorporativo.monitoriaifpe.servico.AtividadeService.java

@RolesAllowed({ ALUNO, PROFESSOR })
public List<RelatorioDTO> converterAtividadesEmRelatorio(Monitoria monitoria, List<Atividade> atividades,
        Integer mes) {//from  w w  w.ja  v  a 2 s  .co m

    RelatorioDTO relatorio = new RelatorioDTO();

    relatorio.setAno(monitoria.getAnoMonitoria());
    relatorio.setEdital(monitoria.getEditalMonitoria());
    relatorio.setDisciplina(monitoria.getDisciplina().getComponenteCurricular().getDescricao());
    relatorio.setMatricula(monitoria.getAluno().getMatricula());
    relatorio.setCurso(monitoria.getAluno().getCurso().getDescricao());
    relatorio.setNome(monitoria.getNomeMonitor());
    relatorio.setOrientador(monitoria.getNomeOrientador());
    relatorio.setMes(Util.obterNomeMes(mes));
    StringBuilder descricaoAcumulada = new StringBuilder();
    StringBuilder observacaoAcumulada = new StringBuilder();

    List<SemanaDTO> semanas = new ArrayList<>();

    List<DiaDTO> dias = new ArrayList<>();

    SimpleDateFormat format = new SimpleDateFormat("HH:mm");

    SemanaDTO semana = new SemanaDTO();

    int quantidadeAtividades = 0;
    for (Atividade atividade : atividades) {

        DiaDTO dia = new DiaDTO();

        String horarioInicial = format.format(atividade.getDataInicio());
        String horarioFinal = format.format(atividade.getDataFim());

        dia.setHorario(horarioInicial + " - " + horarioFinal);
        dia.setData(atividade.getDataInicio());
        dias.add(dia);

        if (!StringUtils.isEmpty(atividade.getDescricao())) {
            descricaoAcumulada.append(atividade.getDescricao());
            descricaoAcumulada.append("; ");
        }
        if (!StringUtils.isEmpty(atividade.getObservacoes())) {
            observacaoAcumulada.append(atividade.getObservacoes());
            observacaoAcumulada.append("; ");
        }

        quantidadeAtividades += 1;
        if (((quantidadeAtividades % 5) == 0) || quantidadeAtividades == atividades.size()) {
            semana.setDias(dias);
            semana.setDescricao(descricaoAcumulada.toString());
            semana.setObservacao(observacaoAcumulada.toString());
            dias = new ArrayList<>();
            semanas.add(semana);
            semana = new SemanaDTO();
            descricaoAcumulada.delete(0, descricaoAcumulada.capacity());
            observacaoAcumulada.delete(0, observacaoAcumulada.capacity());

        }
    }

    relatorio.setSemanas(semanas);

    List<RelatorioDTO> relatorios = new ArrayList<>();
    relatorios.add(relatorio);

    return relatorios;
}

From source file:edu.usu.sdl.openstorefront.service.SearchServiceImpl.java

@Override
public List<ComponentSearchView> getSearchItems(SearchQuery query, FilterQueryParams filter) {
    // use for advanced search with And - Or combinations on separate fields
    String queryOperator = " " + SolrAndOr.OR + " ";
    String myQueryString;/*from   w  ww  .jav a  2 s. c o m*/

    // If incoming query string is blank, default to solar *:* for the full query
    if (StringUtils.isNotBlank(query.getQuery())) {
        StringBuilder queryData = new StringBuilder();

        Field fields[] = SolrComponentModel.class.getDeclaredFields();
        for (Field field : fields) {
            org.apache.solr.client.solrj.beans.Field fieldAnnotation = field
                    .getAnnotation(org.apache.solr.client.solrj.beans.Field.class);
            if (fieldAnnotation != null && field.getType() == String.class) {
                String name = field.getName();
                if (StringUtils.isNotBlank(fieldAnnotation.value())
                        && org.apache.solr.client.solrj.beans.Field.DEFAULT
                                .equals(fieldAnnotation.value()) == false) {
                    name = fieldAnnotation.value();
                }

                queryData.append(SolrEquals.EQUAL.getSolrOperator()).append(name)
                        .append(SolrManager.SOLR_QUERY_SEPERATOR).append(query.getQuery())
                        .append(queryOperator);
            }
        }
        myQueryString = queryData.toString();
        if (myQueryString.endsWith(queryOperator)) {
            queryData.delete((myQueryString.length() - (queryOperator.length())), myQueryString.length());
            myQueryString = queryData.toString();
        }
    } else {
        myQueryString = SolrManager.SOLR_ALL_QUERY;
    }
    log.log(Level.FINER, myQueryString);

    // execute the searchComponent method and bring back from solr a list array
    List<SolrComponentModel> resultsList = new ArrayList<>();
    try {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setQuery(myQueryString);

        // fields to be returned back from solr
        solrQuery.setFields(SolrComponentModel.ID_FIELD, SolrComponentModel.ISCOMPONENT_FIELD);
        solrQuery.setStart(filter.getOffset());
        solrQuery.setRows(filter.getMax());

        Field sortField = ReflectionUtil.getField(new SolrComponentModel(), filter.getSortField());
        if (sortField != null) {
            String sortFieldText = filter.getSortField();
            org.apache.solr.client.solrj.beans.Field fieldAnnotation = sortField
                    .getAnnotation(org.apache.solr.client.solrj.beans.Field.class);
            if (fieldAnnotation != null) {
                sortFieldText = fieldAnnotation.value();
            }
            SolrQuery.ORDER order = SolrQuery.ORDER.desc;
            if (OpenStorefrontConstant.SORT_ASCENDING.equalsIgnoreCase(filter.getSortOrder())) {
                order = SolrQuery.ORDER.asc;
            }
            solrQuery.addSort(sortFieldText, order);
        }

        solrQuery.setIncludeScore(true);

        QueryResponse response = SolrManager.getServer().query(solrQuery);
        SolrDocumentList results = response.getResults();
        DocumentObjectBinder binder = new DocumentObjectBinder();
        resultsList = binder.getBeans(SolrComponentModel.class, results);
    } catch (SolrServerException ex) {
        throw new OpenStorefrontRuntimeException("Search Failed",
                "Contact System Admin.  Seach server maybe Unavailable", ex);
    } catch (Exception ex) {
        log.log(Level.WARNING, "Solr query failed unexpectly; likely bad input.", ex);
    }

    //Pulling the full object on the return
    List<ComponentSearchView> views = new ArrayList<>();

    List<String> componentIds = new ArrayList<>();
    for (SolrComponentModel result : resultsList) {
        if (result.getIsComponent()) {
            componentIds.add(result.getId());
        }
    }

    //remove bad indexes, if any
    List<ComponentSearchView> componentSearchViews = getComponentService().getSearchComponentList(componentIds);
    Set<String> goodComponentIdSet = new HashSet<>();
    for (ComponentSearchView view : componentSearchViews) {
        goodComponentIdSet.add(view.getComponentId());
    }

    for (String componentId : componentIds) {
        if (goodComponentIdSet.contains(componentId) == false) {
            log.log(Level.FINE, MessageFormat.format("Removing bad index: {0}", componentId));
            deleteById(componentId);
        }
    }
    views.addAll(componentSearchViews);

    List<ComponentSearchView> articleViews = getAttributeService().getArticlesSearchView();
    Map<String, ComponentSearchView> allViews = new HashMap<>();
    for (ComponentSearchView componentSearchView : articleViews) {
        AttributeCodePk attributeCodePk = new AttributeCodePk();
        attributeCodePk.setAttributeType(componentSearchView.getArticleAttributeType());
        attributeCodePk.setAttributeCode(componentSearchView.getArticleAttributeCode());
        allViews.put(attributeCodePk.toKey(), componentSearchView);
    }
    for (SolrComponentModel result : resultsList) {

        if (result.getIsComponent() == false) {
            ComponentSearchView view = allViews.get(result.getId());
            if (view != null) {
                views.add(view);
            } else {
                log.log(Level.FINE, MessageFormat.format("Removing bad index: {0}", result.getId()));
                deleteById(result.getId());
            }
        }
    }

    //TODO: Get the score and sort by score
    return views;
}

From source file:org.apache.hadoop.mapreduce.v2.hs.webapp.HsJobsBlock.java

@Override
protected void render(Block html) {
    TBODY<TABLE<Hamlet>> tbody = html.h2("Retired Jobs").table("#jobs").thead().tr().th("Submit Time")
            .th("Start Time").th("Finish Time").th(".id", "Job ID").th(".name", "Name").th("User").th("Queue")
            .th(".state", "State").th("Maps Total").th("Maps Completed").th("Reduces Total")
            .th("Reduces Completed").th("Elapsed Time")._()._().tbody();
    LOG.info("Getting list of all Jobs.");
    // Write all the data into a JavaScript array of arrays for JQuery
    // DataTables to display
    StringBuilder jobsTableData = new StringBuilder("[\n");
    for (Job j : appContext.getAllJobs().values()) {
        JobInfo job = new JobInfo(j);
        jobsTableData.append("[\"").append(dateFormat.format(new Date(job.getSubmitTime()))).append("\",\"")
                .append(dateFormat.format(new Date(job.getStartTime()))).append("\",\"")
                .append(dateFormat.format(new Date(job.getFinishTime()))).append("\",\"").append("<a href='")
                .append(url("job", job.getId())).append("'>").append(job.getId()).append("</a>\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(job.getName())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(job.getUserName())))
                .append("\",\"")
                .append(StringEscapeUtils.escapeJavaScript(StringEscapeUtils.escapeHtml(job.getQueueName())))
                .append("\",\"").append(job.getState()).append("\",\"")
                .append(String.valueOf(job.getMapsTotal())).append("\",\"")
                .append(String.valueOf(job.getMapsCompleted())).append("\",\"")
                .append(String.valueOf(job.getReducesTotal())).append("\",\"")
                .append(String.valueOf(job.getReducesCompleted())).append("\",\"")
                .append(StringUtils//from   www  . j ava  2 s . com
                        .formatTimeSortable(Times.elapsed(job.getStartTime(), job.getFinishTime(), false)))
                .append("\"],\n");
    }

    //Remove the last comma and close off the array of arrays
    if (jobsTableData.charAt(jobsTableData.length() - 2) == ',') {
        jobsTableData.delete(jobsTableData.length() - 2, jobsTableData.length() - 1);
    }
    jobsTableData.append("]");
    html.script().$type("text/javascript")._("var jobsTableData=" + jobsTableData)._();
    tbody._().tfoot().tr().th().input("search_init").$type(InputType.text).$name("submit_time")
            .$value("Submit Time")._()._().th().input("search_init").$type(InputType.text).$name("start_time")
            .$value("Start Time")._()._().th().input("search_init").$type(InputType.text).$name("finish_time")
            .$value("Finish Time")._()._().th().input("search_init").$type(InputType.text).$name("job_id")
            .$value("Job ID")._()._().th().input("search_init").$type(InputType.text).$name("name")
            .$value("Name")._()._().th().input("search_init").$type(InputType.text).$name("user").$value("User")
            ._()._().th().input("search_init").$type(InputType.text).$name("queue").$value("Queue")._()._().th()
            .input("search_init").$type(InputType.text).$name("state").$value("State")._()._().th()
            .input("search_init").$type(InputType.text).$name("maps_total").$value("Maps Total")._()._().th()
            .input("search_init").$type(InputType.text).$name("maps_completed").$value("Maps Completed")._()._()
            .th().input("search_init").$type(InputType.text).$name("reduces_total").$value("Reduces Total")._()
            ._().th().input("search_init").$type(InputType.text).$name("reduces_completed")
            .$value("Reduces Completed")._()._().th().input("search_init").$type(InputType.text)
            .$name("elapsed_time").$value("Elapsed Time")._()._()._()._()._();
}

From source file:edu.cornell.med.icb.util.ICBStringUtils.java

/**
 * Highlight occurrences of highlightWords within
 * toHighlight. Place the value highlightStart before
 * the word and highlightEnd after it. You must provide
 * at least one of highlightStart & highlightEnd.
 * This WILL ignore the case of highlightWords when
 * marking the string./*from w  w  w  .  j av  a 2 s  .  com*/
 * @param toHighlight the text to highlight
 * @param highlightWords the array of words to highlight
 * within toHighlight
 * @param highlightStart the text to place before highlightWords
 * @param highlightEnd the text to place before highlightWords
 * @return the highlighted text
 */
public static String highlightStrings(final String toHighlight, final String[] highlightWords,
        final String highlightStart, final String highlightEnd) {
    if (StringUtils.isBlank(toHighlight)) {
        // Source word is empty, nothing to do.
        return toHighlight;
    }
    final String[] cleanHighlightWords = cleanStringArray(highlightWords);
    if (cleanHighlightWords == null || cleanHighlightWords.length == 0) {
        // No words to highlight, nothing to do
        return toHighlight;
    }
    for (int i = 0; i < cleanHighlightWords.length; i++) {
        cleanHighlightWords[i] = cleanHighlightWords[i].toLowerCase();
    }
    if (StringUtils.isBlank(highlightStart) && StringUtils.isBlank(highlightEnd)) {
        // No markup tags, nothing to do.
        return toHighlight;
    }

    final StringBuilder input = new StringBuilder(toHighlight);
    final StringBuilder inputLC = new StringBuilder(toHighlight.toLowerCase());
    final StringBuilder output = new StringBuilder();
    final StringBuilder tagStart;
    final StringBuilder tagEnd;

    if (highlightStart == null) {
        tagStart = new StringBuilder();
    } else {
        tagStart = new StringBuilder(highlightStart);
    }

    if (highlightEnd == null) {
        tagEnd = new StringBuilder();
    } else {
        tagEnd = new StringBuilder(highlightEnd);
    }

    int pos;
    int size;
    while (true) {
        if (input.length() == 0) {
            // No more text to search.
            break;
        }

        pos = -1;
        size = -1;
        for (final String toFind : cleanHighlightWords) {
            // Find the FIRST of the highlight words
            final int curPos = inputLC.indexOf(toFind);
            if (curPos != -1) {
                // We have a match
                if (pos == -1) {
                    // First match, keep it
                    pos = curPos;
                    size = toFind.length();
                } else if (curPos < pos) {
                    // Earlier match that what we fond before,
                    // keep it
                    pos = curPos;
                    size = toFind.length();
                }
            }
        }
        if (pos == -1) {
            // We're done, no more matches.
            output.append(input);
            break;
        }
        assert size > 0;
        if (pos > 0) {
            // Copy before position
            output.append(input.substring(0, pos));
        }
        // Highlight and copy the text
        output.append(tagStart);
        output.append(input.substring(pos, pos + size));
        output.append(tagEnd);

        // Remove the text from the source so we can
        // find the next occurrence.
        input.delete(0, pos + size);
        inputLC.delete(0, pos + size);
    }
    return output.toString();
}

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

/**
 * Process the task for user side/*from w w w .  java  2s .c  om*/
 * @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 processUserTask(int nIdResourceHistory, HttpServletRequest request, Locale locale,
        TaskEditTicketConfig config) {
    String strTaskInformation = StringUtils.EMPTY;
    StringBuilder sbEntries = new StringBuilder();

    String strUserMessage = request.getParameter(PARAMETER_USER_MESSAGE);

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

    EditableTicket editableTicket = _editableTicketService.findByIdTicket(ticket.getId());

    List<Entry> listEntriesToEdit = _editableTicketService.buildListEntriesToEdit(request,
            editableTicket.getListEditableTicketFields());

    for (Entry entry : listEntriesToEdit) {
        Iterator<Response> iterator = ticket.getListResponse().iterator();

        while (iterator.hasNext()) {
            Response response = iterator.next();

            if (response.getEntry().getIdEntry() == entry.getIdEntry()) {
                iterator.remove();
            }
        }

        _ticketFormService.getResponseEntry(request, entry.getIdEntry(), request.getLocale(), ticket);
        sbEntries.append(entry.getTitle()).append(SEPARATOR);
    }

    // remove and add generic attributes responses
    TicketHome.removeTicketResponse(ticket.getId());

    if ((ticket.getListResponse() != null) && !ticket.getListResponse().isEmpty()) {
        for (Response response : ticket.getListResponse()) {
            ResponseHome.create(response);
            TicketHome.insertTicketResponse(ticket.getId(), response.getIdResponse());
        }
    }

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

    ticket.setUserMessage(strUserMessage);
    TicketHome.update(ticket);

    editableTicket.setIsEdited(true);
    _editableTicketService.update(editableTicket);

    if (StringUtils.isEmpty(strUserMessage)) {
        strUserMessage = I18nService.getLocalizedString(MESSAGE_EDIT_TICKET_INFORMATION_NO_MESSAGE,
                Locale.FRENCH);
    }

    if (sbEntries.length() == 0) {
        strTaskInformation = MessageFormat.format(I18nService.getLocalizedString(
                MESSAGE_EDIT_TICKET_INFORMATION_VIEW_USER_NO_FIELD_EDITED, Locale.FRENCH), strUserMessage);
    } else {
        strTaskInformation = MessageFormat.format(
                I18nService.getLocalizedString(MESSAGE_EDIT_TICKET_INFORMATION_VIEW_USER, Locale.FRENCH),
                sbEntries.toString(), strUserMessage);
    }

    return strTaskInformation;
}

From source file:com.panguso.lc.analysis.format.dao.impl.DaoImpl.java

@Override
public List<T> search(T condition, int pageNo, int pageSize) {
    StringBuilder qString = new StringBuilder("select model from " + entityClass.getSimpleName() + " model");
    StringBuilder qWhere = new StringBuilder(" where ");
    StringBuilder qCondition = new StringBuilder();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(entityClass);
    for (int i = 0, count = propertyDescriptors.length; i < count; i++) {
        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
        String name = propertyDescriptor.getName();
        Class<?> type = propertyDescriptor.getPropertyType();
        String value = null;/*from   w ww  . ja va  2s  .co  m*/
        try {
            value = BeanUtils.getProperty(condition, name);
        } catch (Exception e) {
            // ?
            continue;
        }
        if (value == null || name.equals("class")) {
            continue;
        }
        if ("java.lang.String".equals(type.getName())) {
            qCondition.append("model.");
            qCondition.append(name);
            qCondition.append(" like ");
            qCondition.append("'%");
            qCondition.append(value);
            qCondition.append("%'");
        } else {
            qCondition.append("model.");
            qCondition.append(name);
            qCondition.append("=");
            qCondition.append(value);
        }
        qCondition.append(" and ");

    }
    if (qCondition.length() != 0) {
        qString.append(qWhere).append(qCondition);
        if (qCondition.toString().endsWith(" and ")) {
            qString.delete(qString.length() - " and ".length(), qString.length());
        }
    }
    Query query = em.createQuery(qString.toString());
    query.setFirstResult(pageNo * pageSize);
    query.setMaxResults(pageSize);
    return query.getResultList();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.dam.dao.DAMQueriesLevel2.java

/**
 * Combines all the level2DataFiles (getConstituentDataFiles()) into one file
 * @param dataFile/*ww w.  j  a  va 2  s  . c  o m*/
 * @throws IOException
 */

public void createConsolidatedFiles(final DataFile dataFile) throws IOException {

    DiseaseContextHolder.setDisease(dataFile.getDiseaseType());

    if (tempfileDirectory == null) {
        throw new IOException("No tempfileDirectory specified");
    }
    if (!(new File(tempfileDirectory)).exists()) {
        throw new IOException("Directory does not exist " + tempfileDirectory);
    }
    final DataFileLevelTwoConsolidated dataFileLevelTwoConsolidated = (DataFileLevelTwoConsolidated) dataFile;
    final String uniqueName = getUniqueFilename(dataFileLevelTwoConsolidated);
    final String consolidatedFilePath = tempfileDirectory + File.separator + uniqueName;
    final String consolidatedTmpFilePath = consolidatedFilePath + "_tmp";
    dataFileLevelTwoConsolidated.setPath(consolidatedFilePath);

    TreeSet<DataFileLevelTwo> dataFilesLevelTwo = dataFileLevelTwoConsolidated.getConstituentDataFiles();
    // copy first file into consolidatedFile
    FileUtil.copyFile(dataFilesLevelTwo.first().getPath(), consolidatedFilePath);
    // copy other files into consolidated file
    final StringBuilder dataToWrite = new StringBuilder();
    for (DataFileLevelTwo dataFileLevelTwo : dataFilesLevelTwo.tailSet(dataFilesLevelTwo.first(), false)) {

        BufferedReader consolidatedFile = null;
        BufferedReader constituentFile = null;
        BufferedWriter consolidatedTmpFile = null;

        try {
            consolidatedFile = new BufferedReader(new FileReader(consolidatedFilePath), SIXTY_FOUR_MEGS);
            constituentFile = new BufferedReader(new FileReader(dataFileLevelTwo.getPath()), SIXTY_FOUR_MEGS);
            consolidatedTmpFile = new BufferedWriter(new FileWriter(consolidatedTmpFilePath), SIXTY_FOUR_MEGS);
            String constituentRowData = "";
            boolean firstRow = true;
            int numColumnsToSkip = 1; // default, but will change if file has constant columns

            // assuming all the files will have same row count
            while ((constituentRowData = constituentFile.readLine()) != null) {
                // clear the data
                dataToWrite.delete(0, dataToWrite.length());
                final String consolidatedRowData = consolidatedFile.readLine();

                if (consolidatedRowData != null) {

                    final String[] rowDataArray = constituentRowData.split("\\t");
                    if (firstRow) {
                        for (final String cellData : rowDataArray) {
                            if (cellData.length() == 0) {
                                numColumnsToSkip++;
                            }
                        }
                    } else {
                        dataToWrite.append("\n");
                    }

                    dataToWrite.append(consolidatedRowData);
                    for (int i = numColumnsToSkip; i < rowDataArray.length; i++) {
                        dataToWrite.append("\t").append(rowDataArray[i]);
                    }
                    consolidatedTmpFile.write(dataToWrite.toString());
                }
                firstRow = false;

            }

        } finally {
            closeFile(consolidatedFile);
            closeFile(constituentFile);
            closeFile(consolidatedTmpFile);
            // move consolidatedTmpFile  to consolidatedFile
            FileUtil.move(consolidatedTmpFilePath, consolidatedFilePath);
            new File(consolidatedTmpFilePath).delete();
        }
    }

}

From source file:io.anserini.doc.DataModel.java

public String generateEffectiveness(String collection) {
    Map<String, Object> config = this.collections.get(collection);
    StringBuilder builder = new StringBuilder();
    ObjectMapper oMapper = new ObjectMapper();
    List models = oMapper.convertValue((List) safeGet(config, "models"), List.class);
    List topics = oMapper.convertValue((List) safeGet(config, "topics"), List.class);
    List evals = oMapper.convertValue((List) safeGet(config, "evals"), List.class);
    for (Object evalObj : evals) {
        Eval eval = oMapper.convertValue(evalObj, Eval.class);
        builder.append(String.format("%1$-40s|", eval.getMetric().toUpperCase()));
        for (Object modelObj : models) {
            Model model = oMapper.convertValue(modelObj, Model.class);
            builder.append(String.format(" %1$-10s|", model.getName().toUpperCase()));
        }//w w  w .  j  av a 2  s .  c  o m
        builder.append("\n");
        builder.append(":").append(StringUtils.repeat("-", 39)).append("|");
        for (Object modelObj : models) {
            builder.append(StringUtils.repeat("-", 11)).append("|");
        }
        builder.append("\n");
        for (int i = 0; i < topics.size(); i++) {
            Topic topic = oMapper.convertValue(topics.get(i), Topic.class);
            builder.append(String.format("%1$-40s|", topic.getName().toUpperCase()));
            for (Object modelObj : models) {
                Model model = oMapper.convertValue(modelObj, Model.class);
                builder.append(String.format(" %-10.4f|", model.getResults().get(eval.getMetric()).get(i)));
            }
            builder.append("\n");
        }
        builder.append("\n\n");
    }
    builder.delete(builder.lastIndexOf("\n"), builder.length());

    return builder.toString();
}

From source file:net.sourceforge.fenixedu.presentationTier.backBeans.sop.evaluation.SOPEvaluationManagementBackingBean.java

private void processWrittenTestAdditionalValues(final ExecutionCourse executionCourse,
        final List<WrittenEvaluation> associatedWrittenEvaluations) {
    for (final WrittenEvaluation writtenTest : associatedWrittenEvaluations) {
        int totalCapacity = 0;
        final StringBuilder buffer = new StringBuilder(20);
        for (final Space room : writtenTest.getAssociatedRooms()) {
            buffer.append(room.getName()).append("; ");
            totalCapacity += room.<Integer>getMetadata("examCapacity").orElse(0);
        }/*ww  w. j  a va  2 s .c  o  m*/
        if (buffer.length() > 0) {
            buffer.delete(buffer.length() - 2, buffer.length() - 1);
        }
        writtenEvaluationsRooms.put(writtenTest.getExternalId(), buffer.toString());
        int numberOfEnroledStudents = writtenTest.getCountStudentsEnroledAttendingExecutionCourses();
        executionCoursesEnroledStudents.put(writtenTest.getExternalId(), numberOfEnroledStudents);
        writtenEvaluationsMissingPlaces.put(writtenTest.getExternalId(),
                Integer.valueOf(numberOfEnroledStudents - totalCapacity));
    }
}