Example usage for java.util SortedMap keySet

List of usage examples for java.util SortedMap keySet

Introduction

In this page you can find the example usage for java.util SortedMap keySet.

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:com.streamsets.pipeline.lib.jdbc.JdbcUtil.java

public String generateQuery(int opCode, String tableName, List<String> primaryKeys,
        List<String> primaryKeyParams, SortedMap<String, String> columns, int numRecords, boolean caseSensitive,
        boolean multiRow) throws OnRecordErrorException {
    String query;/*  www . j  a  v a2  s  .  c  o m*/
    String valuePlaceholder;
    String valuePlaceholders;

    if (opCode != OperationType.INSERT_CODE && primaryKeys.isEmpty()) {
        LOG.error("Primary key columns are missing in records: {}", primaryKeys);
        throw new OnRecordErrorException(JdbcErrors.JDBC_62, tableName);
    }

    if (!caseSensitive) {
        switch (opCode) {
        case OperationType.INSERT_CODE:
            valuePlaceholder = String.format("(%s)", joiner.join(columns.values()));
            valuePlaceholders = org.apache.commons.lang3.StringUtils.repeat(valuePlaceholder, ", ", numRecords);
            query = String.format("INSERT INTO %s (%s) VALUES %s", tableName, joiner.join(columns.keySet()),
                    valuePlaceholders);
            break;
        case OperationType.DELETE_CODE:
            valuePlaceholder = String.format("(%s)", joiner.join(primaryKeyParams));
            valuePlaceholders = org.apache.commons.lang3.StringUtils.repeat(valuePlaceholder, ", ", numRecords);
            if (multiRow) {
                query = String.format("DELETE FROM %s WHERE (%s) IN (%s)", tableName, joiner.join(primaryKeys),
                        valuePlaceholders);
            } else {
                query = String.format("DELETE FROM %s WHERE %s = ?", tableName,
                        joinerWhereClause.join(primaryKeys));
            }
            break;
        case OperationType.UPDATE_CODE:
            query = String.format("UPDATE %s SET %s = ? WHERE %s = ?", tableName,
                    joinerColumn.join(columns.keySet()), joinerWhereClause.join(primaryKeys));
            break;
        default:
            // Should be checked earlier. Shouldn't reach here
            LOG.error("Unsupported Operation code: {}}", opCode);
            throw new OnRecordErrorException(JdbcErrors.JDBC_70, opCode);
        }
    } else {
        switch (opCode) {
        case OperationType.INSERT_CODE:
            valuePlaceholder = String.format("(%s)", joiner.join(columns.values()));
            valuePlaceholders = org.apache.commons.lang3.StringUtils.repeat(valuePlaceholder, ", ", numRecords);
            query = String.format("INSERT INTO %s (\"%s\") VALUES %s", tableName,
                    joinerWithQuote.join(columns.keySet()), valuePlaceholders);
            break;
        case OperationType.DELETE_CODE:
            valuePlaceholder = String.format("(%s)", joiner.join(primaryKeyParams));
            valuePlaceholders = org.apache.commons.lang3.StringUtils.repeat(valuePlaceholder, ", ", numRecords);
            if (multiRow) {
                query = String.format("DELETE FROM %s WHERE (\"%s\") IN (%s)", tableName,
                        joinerWithQuote.join(primaryKeys), valuePlaceholders);
            } else {
                query = String.format("DELETE FROM %s WHERE \"%s\" = ?", tableName,
                        joinerWhereClauseWitheQuote.join(primaryKeys));
            }
            break;
        case OperationType.UPDATE_CODE:
            query = String.format("UPDATE %s SET \"%s\" = ? WHERE \"%s\" = ?", tableName,
                    joinerColumnWithQuote.join(columns.keySet()),
                    joinerWhereClauseWitheQuote.join(primaryKeys));
            break;
        default:
            // Should be checked earlier. Shouldn't reach here
            LOG.error("Unsupported Operation code: {}}", opCode);
            throw new OnRecordErrorException(JdbcErrors.JDBC_70, opCode);
        }
    }
    return query;
}

From source file:com.aurel.track.exchange.excel.ExcelImportBL.java

/**
 * Render grid errors/* w  w  w . j  a v  a2  s.c  o  m*/
 * 
 * @param errorsMap
 * @param locale
 * @return
 */
private static List<String> renderGridErrors(SortedMap<Integer, SortedMap<String, ErrorData>> errorsMap,
        Locale locale) {
    List<String> gridErrors = new LinkedList<String>();
    if (errorsMap != null) {
        Iterator<Integer> itrRows = errorsMap.keySet().iterator();
        while (itrRows.hasNext()) {
            Integer row = itrRows.next();
            Map<String, ErrorData> errorsOnRow = errorsMap.get(row);
            if (errorsOnRow != null) {
                Iterator<String> itrColumns = errorsOnRow.keySet().iterator();
                while (itrColumns.hasNext()) {
                    String column = itrColumns.next();
                    ErrorData originalErrorData = errorsOnRow.get(column);
                    List<ErrorParameter> resourceParameters = new ArrayList<ErrorParameter>();
                    resourceParameters.add(new ErrorParameter(row));
                    resourceParameters.add(new ErrorParameter(column));
                    resourceParameters.add(new ErrorParameter(originalErrorData.getResourceKey()));
                    ErrorData modifiedErrorData = new ErrorData("admin.actions.importExcel.err.gridDataError",
                            resourceParameters);
                    gridErrors.add(ErrorHandlerJSONAdapter.createMessage(modifiedErrorData, locale));
                }
            }
        }
    }
    return gridErrors;
}

From source file:org.gvnix.web.screen.roo.addon.AbstractPatternMetadata.java

/**
 * Remove from <code>relatedFields</code> those types that are being
 * returned in any other populate method (these methods have ModelAttribute
 * method annotation)//w  ww  .j a v  a2 s. c om
 * 
 * @param relatedFields
 */
private void filterAlreadyPopulatedTypes(SortedMap<JavaType, JavaTypeMetadataDetails> typesForPopulate) {

    Set<JavaType> keyTypesForPopulate = typesForPopulate.keySet();
    if (keyTypesForPopulate.isEmpty()) {
        return;
    }

    for (MethodMetadata method : controllerMethods) {
        JavaType returnType = method.getReturnType();
        if (returnType.isCommonCollectionType()) {
            for (JavaType genericType : returnType.getParameters()) {
                if (typesForPopulate.keySet().contains(genericType)) {
                    typesForPopulate.remove(genericType);
                }
            }
        } else if (typesForPopulate.keySet().contains(returnType)) {
            typesForPopulate.remove(returnType);
        }
    }
}

From source file:io.fabric8.maven.plugin.mojo.internal.ImportMojo.java

private void chooseSshKeyPairs(Map<String, String> secretData, String host) throws MojoExecutionException {
    String homeDir = System.getProperty("user.home", ".");
    File sshDir = new File(homeDir, ".ssh");
    SortedMap<String, String> keyPairs = new TreeMap<>();
    if (sshDir.isDirectory() && sshDir.exists()) {
        File[] files = sshDir.listFiles();
        if (files != null) {
            for (File file : files) {
                String publicName = file.getName();
                if (file.isFile() && publicName.endsWith(".pub")) {
                    String privateName = Strings.stripSuffix(publicName, ".pub");
                    if (new File(sshDir, privateName).isFile()) {
                        keyPairs.put(privateName, publicName);
                    }/* ww w  .j ava 2  s .co  m*/
                }
            }
        }
    }

    if (keyPairs.isEmpty()) {
        log.warn("No SSH key pairs could be found in %s to choose from!", sshDir);
        log.warn("You may want to clone the git repository over https:// instead to avoid ssh key pairs?");
    } else {
        if (keyPairs.size() == 0) {
            String privateName = keyPairs.firstKey();
            importSshKeys(secretData, sshDir, privateName, keyPairs.get(privateName));
        } else {
            List<String> privateKeys = new ArrayList<>(keyPairs.keySet());
            String privateKey = null;
            try {
                privateKey = prompter.prompt(
                        "Which public / private key pair do you wish to use for SSH authentication with host: "
                                + host,
                        privateKeys);
            } catch (PrompterException e) {
                log.warn("Failed to get user input: %s", e);
            }
            if (Strings.isNotBlank(privateKey)) {
                String publicKey = keyPairs.get(privateKey);
                if (Strings.isNullOrBlank(publicKey)) {
                    log.warn("Invalid answer: %s when available values are: %s", privateKey, privateKeys);
                } else {
                    importSshKeys(secretData, sshDir, privateKey, publicKey);
                }
            }
        }
    }
}

From source file:br.eti.ranieri.opcoesweb.importacao.offline.ImportadorOffline.java

private void calcularBlackScholes(List<CotacaoBDI> cotacoes, ConfiguracaoImportacao configuracaoImportacao)
        throws Exception {
    if (cotacoes == null)
        return;//from   w  w w.j  av a  2 s .c  o m

    // Organiza as cotacoes por data e acao. As cotacoes da
    // acao e das opcoes ficam, por enquanto, na mesma lista
    SortedMap<LocalDate, Map<Acao, List<CotacaoBDI>>> diaAcaoOpcoes = new TreeMap<LocalDate, Map<Acao, List<CotacaoBDI>>>();
    for (CotacaoBDI cotacao : cotacoes) {
        LocalDate data = cotacao.getDataPregao();

        Map<Acao, List<CotacaoBDI>> cotacoesPorAcao = new HashMap<Acao, List<CotacaoBDI>>();
        if (diaAcaoOpcoes.containsKey(data)) {
            cotacoesPorAcao = diaAcaoOpcoes.get(data);
        } else {
            diaAcaoOpcoes.put(data, cotacoesPorAcao);
        }

        Acao acao = null;
        if (cotacao.getCodigoNegociacao().startsWith("PETR")) {
            acao = Acao.PETROBRAS;
        } else if (cotacao.getCodigoNegociacao().startsWith("VALE")) {
            acao = Acao.VALE;
        } else {
            log.error("Codigo de negociacao [{}] nao esta " + "vinculada a VALE e nem a PETROBRAS.",
                    cotacao.getCodigoNegociacao());
            continue;
        }

        List<CotacaoBDI> cotacoesAcaoOpcoes = new ArrayList<CotacaoBDI>();
        if (cotacoesPorAcao.containsKey(acao)) {
            cotacoesAcaoOpcoes = cotacoesPorAcao.get(acao);
        } else {
            cotacoesPorAcao.put(acao, cotacoesAcaoOpcoes);
        }

        cotacoesAcaoOpcoes.add(cotacao);
    }

    // Agora separa, para cada dia e para cada acao, as
    // cotacoes da acao, das opcoes que vencem este mes
    // e das opcoes que vencem no proximo mes.
    // 
    // Para cada dia e para cada acao, calcula o Black&Scholes
    // em cada dupla acao e lista de opcoes
    for (LocalDate data : diaAcaoOpcoes.keySet()) {

        Serie serieAtualOpcoes = Serie.getSerieAtualPorData(data);
        Serie proximaSerieOpcoes = Serie.getProximaSeriePorData(data);
        Double selic = taxaSelic.getSelic(data);

        for (Acao acao : diaAcaoOpcoes.get(data).keySet()) {

            CotacaoBDI cotacaoAcao = null;
            List<CotacaoBDI> cotacoesOpcoesSerie1 = new ArrayList<CotacaoBDI>();
            List<CotacaoBDI> cotacoesOpcoesSerie2 = new ArrayList<CotacaoBDI>();

            for (CotacaoBDI cotacao : diaAcaoOpcoes.get(data).get(acao)) {
                if (CodigoBDI.LOTE_PADRAO.equals(cotacao.getCodigoBdi())
                        && TipoMercadoBDI.MERCADO_A_VISTA.equals(cotacao.getTipoMercado())) {
                    if (cotacaoAcao != null)
                        log.error("Sobrescreveu cotacao [{}] com [{}].", cotacaoAcao, cotacao);
                    cotacaoAcao = cotacao;
                } else if (CodigoBDI.OPCOES_DE_COMPRA.equals(cotacao.getCodigoBdi())
                        && TipoMercadoBDI.OPCOES_DE_COMPRA.equals(cotacao.getTipoMercado())) {
                    if (serieAtualOpcoes.isSerieDaOpcao(cotacao.getCodigoNegociacao())) {
                        cotacoesOpcoesSerie1.add(cotacao);
                    } else if (proximaSerieOpcoes.isSerieDaOpcao(cotacao.getCodigoNegociacao())) {
                        cotacoesOpcoesSerie2.add(cotacao);
                    }
                }
            }

            if (cotacaoAcao == null) {
                log.error("Nao foi encontrada cotacao de " + "acao [{}] no dia [{}].", acao.getCodigo(), data);
                continue;
            }
            if (cotacoesOpcoesSerie1.size() == 0) {
                log.error("Nao foram encontradas cotacoes de opcoes "
                        + "de [{}] no dia [{}] para vencer neste mes.", acao.getCodigo(), data);
                continue;
            }
            if (cotacoesOpcoesSerie2.size() == 0) {
                log.error("Nao foram encontradas cotacoes de opcoes "
                        + "de [{}] no dia [{}] para vencer proximo mes.", acao.getCodigo(), data);
                continue;
            }

            CotacaoBDI opcaoTeorica1 = new CotacaoBDI(data, //
                    CodigoBDI.OPCOES_DE_COMPRA, //
                    TipoMercadoBDI.OPCOES_DE_COMPRA, //
                    "Teorica", 0, 0, 0, //
                    cotacaoAcao.getFechamento(), //
                    cotacoesOpcoesSerie1.iterator().next().getDataVencimento());

            CotacaoBDI opcaoTeorica2 = new CotacaoBDI(data, //
                    CodigoBDI.OPCOES_DE_COMPRA, //
                    TipoMercadoBDI.OPCOES_DE_COMPRA, //
                    "Teorica", 0, 0, 0, //
                    cotacaoAcao.getFechamento(), //
                    cotacoesOpcoesSerie2.iterator().next().getDataVencimento());

            Integer opcoesPorDia = configuracaoImportacao.getQuantidadeOpcoesPorAcaoPorDia();

            CotacaoAcaoOpcoes cotacao = blackScholes.calcularIndices(cotacaoAcao, serieAtualOpcoes,
                    cotacoesOpcoesSerie1, opcaoTeorica1, proximaSerieOpcoes, cotacoesOpcoesSerie2,
                    opcaoTeorica2, opcoesPorDia, selic);

            persistencia.incluirCotacaoHistorica(data, acao, cotacao);
        }
    }
}

From source file:freemarker.ext.dump.DumpDirectiveTest.java

@Test
public void dumpStringToStringMap() {

    String varName = "capitals";
    Map<String, Object> dataModel = new HashMap<String, Object>();

    Map<String, String> myMap = new HashMap<String, String>();
    myMap.put("Albany", "New York");
    myMap.put("St. Paul", "Minnesota");
    myMap.put("Austin", "Texas");
    myMap.put("Sacramento", "California");
    myMap.put("Richmond", "Virginia");
    dataModel.put(varName, myMap);//from   w  w w  .ja  v  a 2s. co  m

    Map<String, Object> expectedDumpValue = new HashMap<String, Object>();
    expectedDumpValue.put(Key.TYPE.toString(), Type.HASH_EX);
    SortedMap<String, Object> myMapExpectedDump = new TreeMap<String, Object>();

    for (String key : myMap.keySet()) {
        Map<String, Object> itemDump = new HashMap<String, Object>();
        itemDump.put(Key.TYPE.toString(), Type.STRING);
        itemDump.put(Key.VALUE.toString(), myMap.get(key));
        myMapExpectedDump.put(key, itemDump);
    }
    expectedDumpValue.put(Key.VALUE.toString(), (myMapExpectedDump));

    Map<String, Object> expectedDump = new HashMap<String, Object>();
    expectedDump.put(varName, expectedDumpValue);

    Map<String, Object> dump = getDump(varName, dataModel);
    assertEquals(expectedDump, dump);

    // Test the sorting of the map
    List<String> expectedKeys = new ArrayList<String>(myMapExpectedDump.keySet());
    @SuppressWarnings("unchecked")
    Map<String, Object> actualDumpValue = (Map<String, Object>) dump.get(varName);
    @SuppressWarnings("unchecked")
    SortedMap<String, Object> myMapActualDump = (SortedMap<String, Object>) actualDumpValue
            .get(Key.VALUE.toString());
    List<String> actualKeys = new ArrayList<String>(myMapActualDump.keySet());
    assertEquals(expectedKeys, actualKeys);
}

From source file:accumulo.balancer.GroupBalancer.java

@Override
public void getAssignments(SortedMap<TServerInstance, TabletServerStatus> current,
        Map<KeyExtent, TServerInstance> unassigned, Map<KeyExtent, TServerInstance> assignments) {

    if (current.size() == 0) {
        return;/*  w  w w.j  ava 2  s.com*/
    }

    Function<KeyExtent, String> partitioner = getPartitioner();

    List<ComparablePair<String, KeyExtent>> tabletsByGroup = new ArrayList<>();
    for (Entry<KeyExtent, TServerInstance> entry : unassigned.entrySet()) {
        TServerInstance last = entry.getValue();
        if (last != null) {
            // Maintain locality
            String fakeSessionID = " ";
            TServerInstance simple = new TServerInstance(last.getLocation(), fakeSessionID);
            Iterator<TServerInstance> find = current.tailMap(simple).keySet().iterator();
            if (find.hasNext()) {
                TServerInstance tserver = find.next();
                if (tserver.host().equals(last.host())) {
                    assignments.put(entry.getKey(), tserver);
                    continue;
                }
            }
        }

        tabletsByGroup
                .add(new ComparablePair<String, KeyExtent>(partitioner.apply(entry.getKey()), entry.getKey()));
    }

    Collections.sort(tabletsByGroup);

    Iterator<TServerInstance> tserverIter = Iterators.cycle(current.keySet());
    for (ComparablePair<String, KeyExtent> pair : tabletsByGroup) {
        KeyExtent ke = pair.getSecond();
        assignments.put(ke, tserverIter.next());
    }

}

From source file:org.openmrs.web.controller.encounter.EncounterFormController.java

/**
 * @see org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest,
 *      java.lang.Object, org.springframework.validation.Errors)
 *//*from   w  ww  .j  a v  a2s  .c om*/
@Override
protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors error)
        throws Exception {

    Encounter encounter = (Encounter) obj;

    // the generic returned key-value pair mapping
    Map<String, Object> map = new HashMap<String, Object>();

    // obsIds of obs that were edited
    List<Integer> editedObs = new Vector<Integer>();

    // the map returned to the form
    // This is a mapping between the formfield and a list of the Obs/ObsGroup in that field
    // This mapping is sorted according to the comparator in FormField.java
    SortedMap<FormField, List<Obs>> obsMapToReturn = null;
    String sortType = Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER);
    if ("weight".equals(sortType)) {
        obsMapToReturn = new TreeMap<FormField, List<Obs>>(); // use FormField.compareTo
    } else {
        obsMapToReturn = new TreeMap<FormField, List<Obs>>(new NumberingFormFieldComparator()); // use custom comparator
    }

    // this maps the obs to form field objects for non top-level obs
    // it is keyed on obs so that when looping over an exploded obsGroup
    // the formfield can be fetched easily (in order to show the field numbers etc)
    Map<Obs, FormField> otherFormFields = new HashMap<Obs, FormField>();

    if (Context.isAuthenticated()) {
        EncounterService es = Context.getEncounterService();
        FormService fs = Context.getFormService();

        // used to restrict the form field lookup
        Form form = encounter.getForm();

        List<EncounterType> encTypes = es.getAllEncounterTypes();
        // Non-retired types first
        Collections.sort(encTypes, new MetadataComparator(Context.getLocale()));
        map.put("encounterTypes", encTypes);

        map.put("encounterRoles", es.getAllEncounterRoles(false));
        map.put("forms", Context.getFormService().getAllForms());
        // loop over the encounter's observations to find the edited obs
        for (Obs o : encounter.getObsAtTopLevel(true)) {

            // only edited obs has previous version
            if (o.hasPreviousVersion()) {
                editedObs.add(o.getObsId());
            }

            // get the formfield for this obs
            FormField ff = fs.getFormField(form, o.getConcept(), obsMapToReturn.keySet(), false);
            if (ff == null) {
                ff = new FormField();
            }

            // we only put the top-level obs in the obsMap.  Those would
            // be the obs that don't have an obs grouper 
            if (o.getObsGroup() == null) {
                // populate the obs map with this formfield and obs
                List<Obs> list = obsMapToReturn.get(ff);
                if (list == null) {
                    list = new Vector<Obs>();
                    obsMapToReturn.put(ff, list);
                }
                list.add(o);
            } else {
                // this is not a top-level obs, just put the formField
                // in a separate list and be done with it
                otherFormFields.put(o, ff);
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("setting obsMap in page context (size: " + obsMapToReturn.size() + ")");
    }
    map.put("obsMap", obsMapToReturn);

    map.put("otherFormFields", otherFormFields);

    map.put("locale", Context.getLocale());
    map.put("editedObs", editedObs);
    if (encounter.getPatient() != null) {
        map.put("patientVisits", Context.getVisitService().getVisitsByPatient(encounter.getPatient()));
    }

    return map;
}

From source file:eus.ixa.ixa.pipe.convert.AbsaSemEval.java

public static String absa2015Toabsa2015AnotatedWithMultipleDocClasModels(String fileName, String modelsList) {
    //reading the ABSA xml file
    SAXBuilder sax = new SAXBuilder();
    XPathFactory xFactory = XPathFactory.instance();
    Document doc = null;//  w  w w.  j a  v a  2 s .c  o  m
    try {
        doc = sax.build(fileName);
        XPathExpression<Element> expr = xFactory.compile("//sentence", Filters.element());
        List<Element> sentences = expr.evaluate(doc);

        int cantSent = 0;

        for (Element sent : sentences) {

            Element opinionsElement = sent.getChild("Opinions");
            if (opinionsElement != null) {
                //iterating over every opinion in the opinions element
                List<Element> opinionList = opinionsElement.getChildren();
                for (int i = opinionList.size() - 1; i >= 0; i--) {
                    Element opinion = opinionList.get(i);
                    opinionsElement.removeContent(opinion);
                }
            }

            KAFDocument kaf;
            final String lang = "en";
            final String kafVersion = "1.0";
            kaf = new KAFDocument(lang, kafVersion);
            final Properties properties = new Properties();
            properties.setProperty("language", lang);
            properties.setProperty("normalize", "default");
            properties.setProperty("untokenizable", "no");
            properties.setProperty("hardParagraph", "no");
            InputStream inputStream = new ByteArrayInputStream(
                    sent.getChildText("text").getBytes(Charset.forName("UTF-8")));
            BufferedReader breader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            final eus.ixa.ixa.pipe.tok.Annotate annotator = new eus.ixa.ixa.pipe.tok.Annotate(breader,
                    properties);
            annotator.tokenizeToKAF(kaf);

            //System.err.println(kaf.toString());

            BufferedReader reader = new BufferedReader(new FileReader(modelsList));
            int lines = 0;
            while (reader.readLine() != null)
                lines++;
            reader.close();

            boolean Binary = false;
            if (lines > 1)
                Binary = true;

            File file = new File(modelsList);
            FileReader fileReader = new FileReader(file);
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                //System.err.println("-" + line + "-" + kaf.getLang());

                /*
                File fileTmp = new File(line);
                String fileTmp0 = Paths.get(".").toAbsolutePath().normalize().toString()+"/tmpModels/"+line+"."+cantSent;
                File fileTmp2 = new File(fileTmp0);
                Files.copy(fileTmp.toPath(), fileTmp2.toPath());
                */
                Properties oteProperties = new Properties();
                oteProperties.setProperty("model", line);
                oteProperties.setProperty("language", kaf.getLang());
                oteProperties.setProperty("clearFeatures", "no");

                //eus.ixa.ixa.pipe.doc.Annotate docClassifier = new eus.ixa.ixa.pipe.doc.Annotate(oteProperties);
                //docClassifier.classify(kaf);

                StatisticalDocumentClassifier docClassifier = new StatisticalDocumentClassifier(oteProperties);
                String source = oteProperties.getProperty("model");

                List<List<WF>> sentences0 = kaf.getSentences();
                List<String> tokens = new ArrayList<>();
                for (List<WF> sentence : sentences0) {
                    for (WF wf : sentence) {
                        tokens.add(wf.getForm());
                    }
                }
                String[] document = tokens.toArray(new String[tokens.size()]);
                String label = docClassifier.classify(document);
                //Topic topic = kaf.newTopic(label);
                double[] probs = docClassifier.classifyProb(document);
                //topic.setConfidence((float) probs[0]);
                //topic.setSource(Paths.get(source).getFileName().toString());
                //topic.setMethod("ixa-pipe-doc");

                SortedMap<Double, String> map = new TreeMap<Double, String>(Collections.reverseOrder());

                //System.err.println("RESULTADO: " + docClassifier.getClassifierME().getAllLabels(probs));
                System.err.println("SENTENCE:" + sent.getChildText("text"));
                Double sum = 0.0;
                for (int i = 0; i < probs.length; i++) {
                    //System.err.println("RESULTADO: " + docClassifier.getClassifierME().getLabel(i) + "\t\t" + probs[i]);
                    sum += probs[i];

                    map.put(probs[i], docClassifier.getClassifierME().getLabel(i));

                    //System.err.println("\t\tPUT: " + probs[i] + " -- " + docClassifier.getClassifierME().getLabel(i));

                    //Topic topic = kaf.newTopic(docClassifier.getClassifierME().getLabel(i));
                    //topic.setConfidence((float) probs[i]);
                    //topic.setSource(Paths.get(source).getFileName().toString());
                    //topic.setMethod("ixa-pipe-doc");
                }
                sum = sum / probs.length;
                System.err.println("MEDIA: " + sum);

                Set<Double> Keys = map.keySet();

                boolean first = true;
                for (Double key : Keys) {
                    System.err.println("\t\t" + key + "\t" + map.get(key));
                    if (Binary) {
                        if (key >= 0.40) {
                            Topic topic = kaf.newTopic(map.get(key));
                            topic.setConfidence((float) key.floatValue());
                            topic.setSource(Paths.get(source).getFileName().toString());
                            topic.setMethod("ixa-pipe-doc");
                        }
                        break;
                    } else {
                        if (first) {
                            first = false;
                            /*if (key > 0.65 || (key < 0.20 && key > 0.10)) {
                               Topic topic = kaf.newTopic(map.get(key));
                               topic.setConfidence((float) key.floatValue());
                               topic.setSource(Paths.get(source).getFileName().toString());
                               topic.setMethod("ixa-pipe-doc");
                               //break;
                            }
                            else */
                            if (key < 0.10) {
                                break;
                            } else {
                                Topic topic = kaf.newTopic(map.get(key));
                                topic.setConfidence((float) key.floatValue());
                                topic.setSource(Paths.get(source).getFileName().toString());
                                topic.setMethod("ixa-pipe-doc");
                            }
                        } else if (key > 0.25) {
                            Topic topic = kaf.newTopic(map.get(key));
                            topic.setConfidence((float) key.floatValue());
                            topic.setSource(Paths.get(source).getFileName().toString());
                            topic.setMethod("ixa-pipe-doc");
                        }
                    }

                }

                //Files.delete(fileTmp2.toPath());
            }
            fileReader.close();

            //System.err.println(kaf.toString());
            cantSent++;

            System.err.println("IsBinary: " + Binary);

            List<Topic> topicList = kaf.getTopics();
            for (Topic topic : topicList) {
                //System.err.println(topic.getTopicValue());
                if (!topic.getTopicValue().equals("NO")) {
                    Element opinionElem = new Element("Opinion");
                    opinionElem.setAttribute("target", "na");
                    opinionElem.setAttribute("category", topic.getTopicValue());
                    //TODO we still do not have polarity here
                    opinionElem.setAttribute("polarity", String.valueOf(topic.getConfidence()));
                    opinionElem.setAttribute("from", "0");
                    opinionElem.setAttribute("to", "0");
                    opinionsElement.addContent(opinionElem);
                }
            }

        } //end of sentence
    } catch (JDOMException | IOException e) {
        e.printStackTrace();
    }

    XMLOutputter xmlOutput = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    xmlOutput.setFormat(format);
    return xmlOutput.outputString(doc);
}