Example usage for java.util Collections reverseOrder

List of usage examples for java.util Collections reverseOrder

Introduction

In this page you can find the example usage for java.util Collections reverseOrder.

Prototype

@SuppressWarnings("unchecked")
public static <T> Comparator<T> reverseOrder() 

Source Link

Document

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.

Usage

From source file:org.apache.geode.management.internal.cli.GfshParser.java

private CommandTarget locateExactMatchingTarget(final String userInput)// exact matching
        throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    CommandTarget commandTarget = null;/*  w  ww .ja va  2 s.  c  om*/

    Map<String, CommandTarget> commandTargetsMap = commandManager.getCommands();
    // Reverse sort the command names because we should start from longer names
    // E.g. Consider commands "A", "A B" & user input as "A B --opt1=val1"
    // In this case, "A B" is the most probable match & should be matched first
    // which can be achieved by reversing natural order of sorting.
    Set<String> commandNamesReverseSorted = new TreeSet<String>(Collections.reverseOrder());
    commandNamesReverseSorted.addAll(commandTargetsMap.keySet());

    // Now we need to locate the CommandTargets from the entries in the map
    for (final String commandName : commandNamesReverseSorted) {
        if (userInput.startsWith(commandName) && commandWordsMatch(userInput, commandName)) {
            // This means that the user has entered the command & name matches exactly
            commandTarget = commandTargetsMap.get(commandName);
            if (commandTarget != null) {
                String remainingBuffer = StringUtils.removeStart(userInput, commandName);
                commandTarget = commandTarget.duplicate(commandName, remainingBuffer);
                break;
            }
        }
    }
    return commandTarget;
}

From source file:org.evosuite.testcase.TestFactory.java

/**
 * Delete the statement at position from the test case and remove all
 * references to it/* www .j  a va  2 s  . c om*/
 *
 * @param test
 * @param position
 * @return false if it was not possible to delete the statement
 * @throws ConstructionFailedException
 */
public boolean deleteStatement(TestCase test, int position) throws ConstructionFailedException {

    if (!ConstraintVerifier.canDelete(test, position)) {
        return false;
    }

    logger.debug("Deleting target statement - {}", position);

    Set<Integer> toDelete = new LinkedHashSet<>();
    recursiveDeleteInclusion(test, toDelete, position);

    List<Integer> pos = new ArrayList<>(toDelete);
    Collections.sort(pos, Collections.reverseOrder());

    for (Integer i : pos) {
        logger.debug("Deleting statement: {}", i);
        test.remove(i);
    }

    return true;
}

From source file:org.oscarehr.PMmodule.web.ClientManagerAction.java

private void setEditAttributes(ActionForm form, HttpServletRequest request, String demographicNo) {
    DynaActionForm clientForm = (DynaActionForm) form;
    LoggedInInfo loggedInInfo = LoggedInInfo.loggedInInfo.get();
    Integer facilityId = loggedInInfo.currentFacility.getId();
    ClientManagerFormBean tabBean = (ClientManagerFormBean) clientForm.get("view");
    Integer demographicId = Integer.valueOf(demographicNo);

    request.setAttribute("id", demographicNo);
    request.setAttribute("client", clientManager.getClientByDemographicNo(demographicNo));

    String providerNo = getProviderNo(request);

    // program domain
    List<Program> programDomain = new ArrayList<Program>();

    for (Iterator<?> i = providerManager.getProgramDomain(providerNo).iterator(); i.hasNext();) {
        ProgramProvider programProvider = (ProgramProvider) i.next();
        programDomain.add(programManager.getProgram(programProvider.getProgramId()));
    }/*from w w w .j a  v  a2  s .co m*/

    request.setAttribute("programDomain", programDomain);

    // check role permission
    HttpSession se = request.getSession();
    List admissions = admissionManager.getCurrentAdmissions(Integer.valueOf(demographicNo));
    for (Iterator it = admissions.iterator(); it.hasNext();) {
        Admission admission = (Admission) it.next();
        String inProgramId = String.valueOf(admission.getProgramId());
        String inProgramType = admission.getProgramType();
        if ("service".equalsIgnoreCase(inProgramType)) {
            se.setAttribute("performDischargeService", new Boolean(caseManagementManager
                    .hasAccessRight("perform discharges", "access", providerNo, demographicNo, inProgramId)));
            se.setAttribute("performAdmissionService", new Boolean(caseManagementManager
                    .hasAccessRight("perform admissions", "access", providerNo, demographicNo, inProgramId)));

        } else if ("bed".equalsIgnoreCase(inProgramType)) {
            se.setAttribute("performDischargeBed", new Boolean(caseManagementManager
                    .hasAccessRight("perform discharges", "access", providerNo, demographicNo, inProgramId)));
            se.setAttribute("performAdmissionBed", new Boolean(caseManagementManager
                    .hasAccessRight("perform admissions", "access", providerNo, demographicNo, inProgramId)));
            se.setAttribute("performBedAssignments",
                    new Boolean(caseManagementManager.hasAccessRight("perform bed assignments", "access",
                            providerNo, demographicNo, inProgramId)));

        }
    }

    // tab override - from survey module
    String tabOverride = (String) request.getAttribute("tab.override");

    if (tabOverride != null && tabOverride.length() > 0) {
        tabBean.setTab(tabOverride);
    }

    if (tabBean.getTab().equals("Summary")) {
        /* survey module */
        request.setAttribute("survey_list", surveyManager.getAllFormsForCurrentProviderAndCurrentFacility());
        request.setAttribute("surveys",
                surveyManager.getFormsForCurrentProviderAndCurrentFacility(demographicNo));

        // request.setAttribute("admissions", admissionManager.getCurrentAdmissions(Integer.valueOf(demographicNo)));
        // only allow bed/service programs show up.(not external program)
        List<Admission> currentAdmissionList = admissionManager.getCurrentAdmissionsByFacility(demographicId,
                facilityId);
        ArrayList<AdmissionForDisplay> bedServiceList = new ArrayList<AdmissionForDisplay>();
        for (Admission admission1 : currentAdmissionList) {
            if (!"External".equalsIgnoreCase(programManager.getProgram(admission1.getProgramId()).getType())) {
                bedServiceList.add(new AdmissionForDisplay(admission1));
            }
        }
        addRemoteAdmissions(bedServiceList, demographicId);
        request.setAttribute("admissions", bedServiceList);

        Intake mostRecentQuickIntake = genericIntakeManager
                .getMostRecentQuickIntakeByFacility(Integer.valueOf(demographicNo), facilityId);
        request.setAttribute("mostRecentQuickIntake", mostRecentQuickIntake);

        HealthSafety healthsafety = healthSafetyManager
                .getHealthSafetyByDemographic(Long.valueOf(demographicNo));
        request.setAttribute("healthsafety", healthsafety);

        request.setAttribute("referrals", getReferralsForSummary(Integer.parseInt(demographicNo), facilityId));

        // FULL OCAN Staff/Client Assessment
        OcanStaffForm ocanStaffForm = ocanStaffFormDao.findLatestByFacilityClient(facilityId,
                Integer.valueOf(demographicNo), "FULL");
        if (ocanStaffForm != null) {
            if (ocanStaffForm.getAssessmentStatus() != null
                    && ocanStaffForm.getAssessmentStatus().equals("In Progress"))
                request.setAttribute("ocanStaffForm", ocanStaffForm);
        } else {
            request.setAttribute("ocanStaffForm", null);
        }

        // SELF+CORE OCAN Staff/Client Assessment
        OcanStaffForm selfOcanStaffForm = ocanStaffFormDao.findLatestByFacilityClient(facilityId,
                Integer.valueOf(demographicNo), "SELF");
        if (selfOcanStaffForm != null) {
            if (selfOcanStaffForm.getAssessmentStatus() != null
                    && selfOcanStaffForm.getAssessmentStatus().equals("In Progress")) {
                request.setAttribute("selfOcanStaffForm", selfOcanStaffForm);
            }
        } else {
            request.setAttribute("selfOcanStaffForm", null);
        }

        // CORE OCAN Staff/Client Assessment
        OcanStaffForm coreOcanStaffForm = ocanStaffFormDao.findLatestByFacilityClient(facilityId,
                Integer.valueOf(demographicNo), "CORE");
        if (coreOcanStaffForm != null) {
            if (coreOcanStaffForm.getAssessmentStatus() != null
                    && coreOcanStaffForm.getAssessmentStatus().equals("In Progress")) {
                request.setAttribute("coreOcanStaffForm", coreOcanStaffForm);
            }
        } else {
            request.setAttribute("coreOcanStaffForm", null);
        }

        // CDS
        CdsClientForm cdsClientForm = cdsClientFormDao.findLatestByFacilityClient(facilityId,
                Integer.valueOf(demographicNo));
        request.setAttribute("cdsClientForm", cdsClientForm);
    }

    /* history */
    if (tabBean.getTab().equals("History")) {
        ArrayList<AdmissionForDisplay> allResults = new ArrayList<AdmissionForDisplay>();

        List<Admission> addLocalAdmissions = admissionManager.getAdmissionsByFacility(demographicId,
                facilityId);
        for (Admission admission : addLocalAdmissions)
            allResults.add(new AdmissionForDisplay(admission));

        addRemoteAdmissions(allResults, demographicId);

        request.setAttribute("admissionHistory", allResults);
        request.setAttribute("referralHistory", getReferralsForHistory(demographicId, facilityId));
    }

    List<?> currentAdmissions = admissionManager.getCurrentAdmissions(Integer.valueOf(demographicNo));

    for (int x = 0; x < currentAdmissions.size(); x++) {
        Admission admission = (Admission) currentAdmissions.get(x);

        if (isInDomain(admission.getProgramId().longValue(), providerManager.getProgramDomain(providerNo))) {
            request.setAttribute("isInProgramDomain", Boolean.TRUE);
            break;
        }
    }

    /* bed reservation view */
    BedDemographic bedDemographic = bedDemographicManager
            .getBedDemographicByDemographic(Integer.valueOf(demographicNo), facilityId);
    request.setAttribute("bedDemographic", bedDemographic);

    RoomDemographic roomDemographic = getRoomDemographicManager()
            .getRoomDemographicByDemographic(Integer.valueOf(demographicNo), facilityId);

    if (roomDemographic != null) {
        Integer roomIdInt = roomDemographic.getId().getRoomId();
        Room room = null;
        if (roomIdInt != null) {
            room = getRoomManager().getRoom(roomIdInt);
        }
        if (room != null) {
            roomDemographic.setRoom(room);
        }
    }
    request.setAttribute("roomDemographic", roomDemographic);

    if (tabBean.getTab().equals("Bed/Room Reservation")) {

        boolean isRefreshRoomDropDown = false;
        if (request.getAttribute("isRefreshRoomDropDown") != null
                && request.getAttribute("isRefreshRoomDropDown").equals("Y")) {
            isRefreshRoomDropDown = true;
        } else {
            isRefreshRoomDropDown = false;
        }

        String roomId = request.getParameter("roomId");
        if (roomDemographic != null && roomId == null) {
            roomId = roomDemographic.getId().getRoomId().toString();
        }

        // set bed program id
        Admission bedProgramAdmission = admissionManager
                .getCurrentBedProgramAdmission(Integer.valueOf(demographicNo));
        Integer bedProgramId = null;
        if (bedProgramAdmission != null) {
            bedProgramId = (bedProgramAdmission != null) ? bedProgramAdmission.getProgramId() : null;
        }
        request.setAttribute("bedProgramId", bedProgramId);

        Bed reservedBed = null;

        if (bedDemographic == null) {
            bedDemographic = BedDemographic.create(Integer.valueOf(demographicNo),
                    bedDemographicManager.getDefaultBedDemographicStatus(), providerNo);

            if (roomDemographic != null) {
                bedDemographic.setReservationStart(roomDemographic.getAssignStart());
                bedDemographic.setReservationEnd(roomDemographic.getAssignEnd());
            }

            reservedBed = null;

        } else {

            reservedBed = bedManager.getBed(bedDemographic.getBedId());
        }

        if (isRefreshRoomDropDown) {
            bedDemographic.setRoomId(Integer.valueOf(roomId));
        }

        clientForm.set("bedDemographic", bedDemographic);

        Room[] availableRooms = getRoomManager().getAvailableRooms(facilityId, bedProgramId, Boolean.TRUE,
                demographicNo);

        request.setAttribute("availableRooms", availableRooms);

        if ((isRefreshRoomDropDown && roomId != null) || (reservedBed == null && !"0".equals(roomId))) {
            request.setAttribute("roomId", roomId);
        } else if (reservedBed != null) {
            request.setAttribute("roomId", reservedBed.getRoomId().toString());
        } else {
            request.setAttribute("roomId", "0");
        }
        request.setAttribute("isAssignedBed", String.valueOf(
                getRoomManager().isAssignedBed((String) request.getAttribute("roomId"), availableRooms)));

        // retrieve an array of beds associated with this roomId
        Bed[] unreservedBeds = null;

        if (isRefreshRoomDropDown && request.getAttribute("unreservedBeds") != null) {
            unreservedBeds = (Bed[]) request.getAttribute("unreservedBeds");

        } else if (reservedBed != null) {

            // unreservedBeds = bedManager.getBedsByRoomProgram(availableRooms, bedProgramId, false);
            unreservedBeds = bedManager.getCurrentPlusUnreservedBedsByRoom(reservedBed.getRoomId(),
                    bedDemographic.getId().getBedId(), false);
        }

        clientForm.set("unreservedBeds", unreservedBeds);

        // set bed demographic statuses
        clientForm.set("bedDemographicStatuses", bedDemographicManager.getBedDemographicStatuses());
    }
    /* forms */
    if (tabBean.getTab().equals("Forms")) {
        request.setAttribute("regIntakes",
                genericIntakeManager.getRegIntakes(Integer.valueOf(demographicNo), facilityId));
        request.setAttribute("quickIntakes",
                genericIntakeManager.getQuickIntakes(Integer.valueOf(demographicNo), facilityId));
        // request.setAttribute("indepthIntakes", genericIntakeManager.getIndepthIntakes(Integer.valueOf(demographicNo), facilityId));
        request.setAttribute("indepthIntakes",
                genericIntakeManager.getIntakesByType(Integer.valueOf(demographicNo), facilityId, 2));
        request.setAttribute("generalIntakes",
                genericIntakeManager.getIntakesByType(Integer.valueOf(demographicNo), facilityId, 3));
        request.setAttribute("programIntakes",
                genericIntakeManager.getProgramIntakes(Integer.valueOf(demographicNo), facilityId));
        request.setAttribute("programsWithIntake",
                genericIntakeManager.getProgramsWithIntake(Integer.valueOf(demographicNo)));

        request.setAttribute("indepthIntakeNodes", genericIntakeManager.getIntakeNodesByType(2));
        request.setAttribute("generalIntakeNodes", genericIntakeManager.getIntakeNodesByType(3));

        /* survey module */
        request.setAttribute("survey_list", surveyManager.getAllFormsForCurrentProviderAndCurrentFacility());
        request.setAttribute("surveys",
                surveyManager.getFormsForCurrentProviderAndCurrentFacility(demographicNo));

        /* consent forms */
        int clientId = Integer.parseInt(demographicNo);
        List<IntegratorConsent> consentTemp = integratorConsentDao.findByFacilityAndDemographic(facilityId,
                clientId);
        TreeMap<Date, HashMap<String, Object>> consents = new TreeMap<Date, HashMap<String, Object>>(
                Collections.reverseOrder());
        for (IntegratorConsent x : consentTemp) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("createdDate",
                    DateFormatUtils.ISO_DATETIME_FORMAT.format(x.getCreatedDate()).replace('T', ' '));
            Provider provider = providerDao.getProvider(x.getProviderNo());
            map.put("provider", provider.getFormattedName());
            map.put("consentId", x.getId());

            consents.put(x.getCreatedDate(), map);
        }

        request.setAttribute("consents", consents.values());

        // CDS forms
        List<CdsClientForm> cdsForms = cdsClientFormDao.findByFacilityClient(facilityId, clientId);
        request.setAttribute("cdsForms", cdsForms);

        // FULL OCAN Forms
        List<OcanStaffForm> ocanStaffForms = ocanStaffFormDao.findByFacilityClient(facilityId, clientId,
                "FULL");
        request.setAttribute("ocanStaffForms", ocanStaffForms);

        // SELF+CORE OCAN Forms
        List<OcanStaffForm> selfOcanStaffForms = ocanStaffFormDao.findByFacilityClient(facilityId, clientId,
                "SELF");
        request.setAttribute("selfOcanStaffForms", selfOcanStaffForms);

        // CORE OCAN Forms
        List<OcanStaffForm> coreOcanStaffForms = ocanStaffFormDao.findByFacilityClient(facilityId, clientId,
                "CORE");
        request.setAttribute("coreOcanStaffForms", coreOcanStaffForms);

    }

    /* refer */
    if (tabBean.getTab().equals("Refer")) {
        request.setAttribute("referrals",
                clientManager.getActiveReferrals(demographicNo, String.valueOf(facilityId)));

        if (loggedInInfo.currentFacility.isIntegratorEnabled()) {
            try {
                ArrayList<RemoteReferral> results = new ArrayList<RemoteReferral>();

                // get local data
                List<RemoteReferral> remoteReferralsFromDB = remoteReferralDao
                        .findByFacilityIdDemogprahicId(facilityId, demographicId);
                results.addAll(remoteReferralsFromDB);

                // get remote Data
                ReferralWs referralWs = CaisiIntegratorManager.getReferralWs();

                Integer currentRemoteFacilityId = CaisiIntegratorManager.getCurrentRemoteFacility()
                        .getIntegratorFacilityId();
                List<Referral> referrals = referralWs.getLinkedReferrals(Integer.parseInt(demographicNo));

                if (referrals != null) {
                    for (Referral remoteReferral : referrals) {
                        if (currentRemoteFacilityId.equals(remoteReferral.getSourceIntegratorFacilityId()))
                            continue;

                        RemoteReferral temp = new RemoteReferral();
                        CachedFacility cachedFacility = CaisiIntegratorManager
                                .getRemoteFacility(remoteReferral.getDestinationIntegratorFacilityId());
                        temp.setReferredToFacilityName(cachedFacility.getName());

                        FacilityIdIntegerCompositePk pk = new FacilityIdIntegerCompositePk();
                        pk.setIntegratorFacilityId(remoteReferral.getDestinationIntegratorFacilityId());
                        pk.setCaisiItemId(remoteReferral.getDestinationCaisiProgramId());
                        CachedProgram cachedProgram = CaisiIntegratorManager.getRemoteProgram(pk);
                        temp.setReferredToProgramName(cachedProgram.getName());

                        temp.setReferalDate(remoteReferral.getReferralDate());

                        Provider tempProvider = providerDao
                                .getProvider(remoteReferral.getSourceCaisiProviderId());
                        temp.setReferringProviderNo(tempProvider.getFormattedName());

                        temp.setReasonForReferral(remoteReferral.getReasonForReferral());
                        temp.setPresentingProblem(remoteReferral.getPresentingProblem());

                        results.add(temp);
                    }
                }

                Comparator<RemoteReferral> tempComparator = new Comparator<RemoteReferral>() {
                    @Override
                    public int compare(RemoteReferral o1, RemoteReferral o2) {
                        if (o1.getReferalDate() == null && o2.getReferalDate() == null)
                            return (0);
                        if (o1.getReferalDate() == null)
                            return (-1);
                        if (o2.getReferalDate() == null)
                            return (1);
                        return (o1.getReferalDate().compareTo(o2.getReferalDate()));
                    }
                };

                Collections.sort(results, tempComparator);

                request.setAttribute("remoteReferrals", results);
            } catch (Exception e) {
                logger.error("Unexpected Error.", e);
            }
        }
    }

    /* service restrictions */
    if (tabBean.getTab().equals("Service Restrictions")) {
        // request.setAttribute("serviceRestrictions", clientRestrictionManager.getActiveRestrictionsForClient(Integer.valueOf(demographicNo), new Date()));
        request.setAttribute("serviceRestrictions", clientRestrictionManager
                .getActiveRestrictionsForClient(Integer.valueOf(demographicNo), facilityId, new Date()));

        request.setAttribute("serviceRestrictionList", lookupManager.LoadCodeList("SRT", true, null, null));
    }

    /* discharge */
    if (tabBean.getTab().equals("Discharge")) {
        request.setAttribute("communityPrograms", programManager.getCommunityPrograms());
        request.setAttribute("serviceAdmissions",
                admissionManager.getCurrentServiceProgramAdmission(Integer.valueOf(demographicNo)));
        request.setAttribute("temporaryAdmissions",
                admissionManager.getCurrentTemporaryProgramAdmission(Integer.valueOf(demographicNo)));
        request.setAttribute("current_bed_program",
                admissionManager.getCurrentBedProgramAdmission(Integer.valueOf(demographicNo)));
        request.setAttribute("current_community_program",
                admissionManager.getCurrentCommunityProgramAdmission(Integer.valueOf(demographicNo)));
        request.setAttribute("dischargeReasons", lookupManager.LoadCodeList("DRN", true, null, null));
        request.setAttribute("dischargeReasons2", lookupManager.LoadCodeList("DR2", true, null, null));
    }

    /* Relations */
    DemographicRelationship demoRelation = new DemographicRelationship();
    ArrayList<Hashtable<String, Object>> relList = demoRelation
            .getDemographicRelationshipsWithNamePhone(demographicNo, facilityId);
    List<JointAdmission> list = clientManager.getDependents(new Long(demographicNo));
    JointAdmission clientsJadm = clientManager.getJointAdmission(new Long(demographicNo));
    int familySize = list.size() + 1;
    if (familySize > 1) {
        request.setAttribute("groupHead", "yes");
    }
    if (clientsJadm != null) {
        request.setAttribute("dependentOn", clientsJadm.getHeadClientId());
        List<JointAdmission> depList = clientManager.getDependents(clientsJadm.getHeadClientId());
        familySize = depList.size() + 1;
        Demographic headClientDemo = clientManager.getClientByDemographicNo("" + clientsJadm.getHeadClientId());
        request.setAttribute("groupName", headClientDemo.getFormattedName() + " Group");
    }

    if (relList != null && relList.size() > 0) {
        for (Hashtable h : relList) {
            String demographic = (String) h.get("demographicNo");
            Long demoLong = new Long(demographic);
            JointAdmission demoJadm = clientManager.getJointAdmission(demoLong);

            // IS PERSON JOINTLY ADMITTED WITH ME, They will either have the same HeadClient or be my headClient
            if (clientsJadm != null && clientsJadm.getHeadClientId().longValue() == demoLong) { // they're my head client
                h.put("jointAdmission", "head");
            } else if (demoJadm != null && clientsJadm != null
                    && clientsJadm.getHeadClientId().longValue() == demoJadm.getHeadClientId().longValue()) {
                // They depend on the same person i do!
                h.put("jointAdmission", "dependent");
            } else if (demoJadm != null
                    && demoJadm.getHeadClientId().longValue() == new Long(demographicNo).longValue()) {
                // They depend on me
                h.put("jointAdmission", "dependent");
            }
            // Can this person be added to my depended List
            if (clientsJadm == null && demoJadm == null && clientManager.getDependents(demoLong).size() == 0) {
                // yes if - i am not dependent on anyone
                // - this person is not dependent on someone
                // - this person is not a head of a family already
                h.put("dependentable", "yes");
            }
            if (demoJadm != null) { // DEPENDS ON SOMEONE
                h.put("dependentOn", demoJadm.getHeadClientId());
                if (demoJadm.getHeadClientId().longValue() == new Long(demographicNo).longValue()) {
                    h.put("dependent", demoJadm.getTypeId());
                }
            } else if (clientsJadm != null && clientsJadm.getHeadClientId().longValue() == demoLong) { // HEAD PERSON WON'T DEPEND ON ANYONE
                h.put("dependent", new Long(0));
            }
        }
        request.setAttribute("relations", relList);
        request.setAttribute("relationSize", familySize);

    }
}

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;//  ww  w. ja  va 2s . c om
    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);
}

From source file:snpviewer.SnpViewer.java

public void removeSamples(ActionEvent event) {
    FXMLLoader loader = new FXMLLoader(getClass().getResource("RemoveSamplesInterface.fxml"));
    try {//from  w  w  w .  j a  v  a 2s .  c  o m
        Pane pane = (Pane) loader.load();
        RemoveSamplesInterfaceController removeController = (RemoveSamplesInterfaceController) loader
                .getController();
        Scene scene = new Scene(pane);
        Stage stage = new Stage();
        stage.setScene(scene);
        scene.getStylesheets().add(SnpViewer.class.getResource("SnpViewerStyleSheet.css").toExternalForm());
        stage.getIcons().add(new Image(this.getClass().getResourceAsStream("icon.png")));
        stage.setTitle("Remove Samples");
        removeController.setSamples(affObserve, unObserve);
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.showAndWait();
        List<Integer> indicesToRemove = removeController.getSamplesToRemove();
        //System.out.println(indicesToRemove.toString());
        if (indicesToRemove.isEmpty()) {
            return;
        }
        ArrayList<Integer> affsToRemove = new ArrayList<>();
        ArrayList<Integer> unsToRemove = new ArrayList<>();
        for (Integer r : indicesToRemove) {
            if (r < affObserve.size()) {//index corresponds to affFiles
                affsToRemove.add(r);
            } else {//index corresponds to unFiles
                r -= affObserve.size();
                unsToRemove.add(r);
            }
        }
        ArrayList<File> dirsToDelete = new ArrayList<>();
        if (!affsToRemove.isEmpty()) {
            Collections.sort(affsToRemove, Collections.reverseOrder());
            for (int i : affsToRemove) {
                dirsToDelete.add(affObserve.get(i).getOutputDirectory());
                affObserve.remove(i);
            }
        }
        if (!unsToRemove.isEmpty()) {
            Collections.sort(unsToRemove, Collections.reverseOrder());
            for (int i : unsToRemove) {
                dirsToDelete.add(unObserve.get(i).getOutputDirectory());
                unObserve.remove(i);
            }
        }
        if (affObserve.isEmpty() && unObserve.isEmpty()) {
            resetView();
        } else {
            refreshView(null, false);
        }
        saveProject();
        for (File dir : dirsToDelete) {
            FileUtils.deleteDirectory(dir);
        }
    } catch (Exception ex) {
        Dialogs.showErrorDialog(null,
                "Sample removal failed - please see " + "details for stack trace and report this error.",
                "Remove Samples Failed!", "SnpViewer", ex);
    }
}

From source file:snpviewer.SnpViewer.java

public void addInputFiles(final boolean isAffected) {
    setProgressMode(true);/*  w ww.j ava 2 s  .c o  m*/
    FileChooser fileChooser = new FileChooser();
    fileChooser.getExtensionFilters()
            .add(new FileChooser.ExtensionFilter("Text Files", "*.txt", "AutoSNPa Files", "*.xls"));
    fileChooser.setTitle("Select one or more input (birdseed) files");
    List<File> chosen = fileChooser.showOpenMultipleDialog(null);
    if (chosen == null) {
        setProgressMode(false);
        return;
    }
    cancelButton.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent actionEvent) {
            setProgressMode(false);
        };
    });
    ArrayList<File> inputFiles = new ArrayList<>();
    inputFiles.addAll(chosen);
    ArrayList<File> duplicates = new ArrayList<>();
    ArrayList<Integer> indicesToRemove = new ArrayList<>();
    for (int i = 0; i < inputFiles.size(); i++) {
        for (SnpFile s : affFiles) {
            if (inputFiles.get(i).getName().equals(s.getInputFileName())) {
                duplicates.add(inputFiles.get(i));
                indicesToRemove.add(i);
            }
        }
        for (SnpFile s : unFiles) {
            if (inputFiles.get(i).getName().equals(s.getInputFileName())) {
                duplicates.add(inputFiles.get(i));
                indicesToRemove.add(i);
            }
        }
    }
    if (!duplicates.isEmpty()) {
        StringBuilder duplicateString = new StringBuilder();
        for (File d : duplicates) {
            duplicateString.append(d.getName()).append("\n");
        }
        Collections.sort(indicesToRemove, Collections.reverseOrder());
        for (int i : indicesToRemove) {
            inputFiles.remove(i);
        }
        DialogResponse response = Dialogs.showWarningDialog(null,
                "This project already includes the following file(s) with "
                        + "matching names to the file(s) you have just tried to add:" + "\n\n" + duplicateString
                        + "\nIf you want to change the affected "
                        + "status of a file please remove it first.  Any remaining "
                        + "(non-duplicate) files will be processed if you click 'OK'.",
                "Duplicate Input File", "SnpViewer", Dialogs.DialogOptions.OK_CANCEL);
        if (!response.equals(DialogResponse.OK)) {
            setProgressMode(false);
            return;
        }
    }
    if (inputFiles.isEmpty()) {
        setProgressMode(false);
        return;
    }
    final Iterator iter = inputFiles.iterator();
    File input = (File) iter.next();
    int fileCounter = 1;
    if (snpViewSaveDirectory == null) {
        Dialogs.showWarningDialog(null, "Before processing input files " + "please create a project",
                "Create Project", "SNP Viewer");

        boolean success = startNewProject();

        if (!success) {
            setProgressMode(false);
            return;
        }
    }

    addInputFilesWithIterator(isAffected, input, iter, fileCounter, inputFiles.size());
}

From source file:org.apache.jackrabbit.oak.plugins.index.lucene.LucenePropertyIndexTest.java

private static List<String> getSortedPaths(List<Tuple> tuples, OrderDirection dir) {
    if (OrderDirection.DESC == dir) {
        Collections.sort(tuples, Collections.reverseOrder());
    } else {//from w ww. j  a v  a  2 s. co  m
        Collections.sort(tuples);
    }
    List<String> paths = Lists.newArrayListWithCapacity(tuples.size());
    for (Tuple t : tuples) {
        paths.add(t.path);
    }
    return paths;
}

From source file:com.krawler.spring.iphone.iphoneController.java

private JSONArray getData(String[] arrName, Float[] value, int cnt) {
    JSONArray jarr = null;/*w ww.ja v a 2s.co  m*/
    try {
        jarr = new JSONArray();
        Float[] vArr = new Float[cnt];
        float divisor = 1;
        int temp = cnt;
        while (temp > 0) {
            temp = temp / 10;
            divisor = divisor * 10;
        }
        String[] nArr = new String[cnt];
        for (int i = 0; i < cnt; i++) {
            int ind = value[i].toString().indexOf(".");
            float cvalue = Float.parseFloat(value[i].toString().substring(0, ind));
            float lval = (float) (cvalue + (float) (i / divisor));
            vArr[i] = lval;
            nArr[i] = arrName[i];
        }
        Arrays.sort(vArr, Collections.reverseOrder());
        int otherValue = 0;
        for (int i = 0; i < cnt; i++) {
            JSONObject jobj = new JSONObject();
            float cval = Float.parseFloat(vArr[i].toString().substring(0, vArr[i].toString().indexOf(".")));
            int index = Math.round((vArr[i] - cval) * divisor);
            int cvalue = (int) cval;
            if (cnt == 10) {
                jobj.put("name", nArr[index]);
                jobj.put("value", cvalue);
                jarr.put(jobj);
            } else if (i < 9) {
                jobj.put("name", nArr[index]);
                jobj.put("value", cvalue);
                jarr.put(jobj);
            } else {
                otherValue = otherValue + cvalue;
                if (i == (cnt - 1)) {
                    jobj.put("name", "Others");
                    jobj.put("value", otherValue);
                    jarr.put(jobj);
                }
            }
        }
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        String exname = ex.toString();
    }
    return jarr;
}

From source file:app.RunApp.java

/**
 * Select n top co-ocurrence labels/*w  ww  .  ja  v  a2s.c o  m*/
 * 
 * @param n Number of labels to select
 * @param selectInTable Indicates if the rows are selected in the table
 * @return List with the names of the selected labels
 */
public ArrayList<String> selectTopCoocurrenceLabels(int n, boolean selectInTable) {

    ArrayList<String> pairsString = new ArrayList<>();

    ArrayList<LabelsPairValue> pairs = new ArrayList<>();
    for (int i = 0; i < coocurrenceCoefficients.length; i++) {
        for (int j = 0; j < coocurrenceCoefficients.length; j++) {
            if (coocurrenceCoefficients[i][j] >= 0) {
                pairs.add(new LabelsPairValue(i, j, coocurrenceCoefficients[i][j]));
            }
        }
    }
    Collections.sort(pairs, Collections.reverseOrder());

    int numLabels = n;
    int currentSelectedLabels = 0;

    Vector<Integer> selectedLabels = new Vector<>();

    do {
        if (!selectedLabels.contains(pairs.get(0).label1)) {
            selectedLabels.add(pairs.get(0).label1);
            currentSelectedLabels++;
        }

        if (currentSelectedLabels < numLabels) {
            if (!selectedLabels.contains(pairs.get(0).label2)) {
                selectedLabels.add(pairs.get(0).label2);
                currentSelectedLabels++;
            }
        }

        pairs.remove(pairs.get(0));
    } while ((pairs.size() > 0) && (currentSelectedLabels < numLabels));

    String s = new String();

    for (int i = 0; i < selectedLabels.size(); i++) {
        s = jTableCoocurrences.getColumnName(selectedLabels.get(i));

        if (s != null) {
            pairsString.add(s);
        }
    }

    if (selectInTable) {
        tableCoOcurrenceLeft.clearSelection();

        String labelName;
        for (int i = 0; i < selectedLabels.size(); i++) {
            labelName = dataset.getLabelNames()[selectedLabels.get(i)];
            for (int r = 0; r < tableCoOcurrenceLeft.getRowCount(); r++) {
                if (tableCoOcurrenceLeft.getValueAt(r, 0).equals(labelName)) {
                    tableCoOcurrenceLeft.addRowSelectionInterval(r, r);
                }
            }
        }
    }
    return pairsString;
}

From source file:app.RunApp.java

/**
 * Select n top heatmap labels//from   ww w  .ja  v  a2 s  .c  o m
 * 
 * @param n Number of labels to select
 * @param selectInTable Indicates if the rows are selected in the table
 * @return List with the names of the selected labels
 */
public ArrayList<String> selectTopHeatmapLabels(int n, boolean selectInTable) {

    ArrayList<String> pairsString = new ArrayList<>();

    ArrayList<LabelsPairValue> pairs = new ArrayList<>();
    for (int i = 0; i < heatmapCoefficients.length; i++) {
        for (int j = 0; j < heatmapCoefficients.length; j++) {
            if (heatmapCoefficients[i][j] >= 0) {
                pairs.add(new LabelsPairValue(i, j, heatmapCoefficients[i][j]));
            }
        }
    }
    Collections.sort(pairs, Collections.reverseOrder());

    int numLabels = n;
    int currentSelectedLabels = 0;

    Vector<Integer> selectedLabels = new Vector<>();

    do {
        if (!selectedLabels.contains(pairs.get(0).label1)) {
            selectedLabels.add(pairs.get(0).label1);
            currentSelectedLabels++;
        }

        if (currentSelectedLabels < numLabels) {
            if (!selectedLabels.contains(pairs.get(0).label2)) {
                selectedLabels.add(pairs.get(0).label2);
                currentSelectedLabels++;
            }
        }

        pairs.remove(pairs.get(0));
    } while ((pairs.size() > 0) && (currentSelectedLabels < numLabels));

    String s;

    for (int i = 0; i < selectedLabels.size(); i++) {
        s = jTableHeatmap.getColumnName(selectedLabels.get(i));

        if (s != null) {
            pairsString.add(s);
        }
    }

    if (selectInTable) {
        tableHeatmapLeft.clearSelection();

        String labelName;
        for (int i = 0; i < selectedLabels.size(); i++) {
            //Get label name
            labelName = dataset.getLabelNames()[selectedLabels.get(i)];
            for (int r = 0; r < tableHeatmapLeft.getRowCount(); r++) {
                if (tableHeatmapLeft.getValueAt(r, 0).equals(labelName)) {
                    tableHeatmapLeft.addRowSelectionInterval(r, r);
                }
            }
        }
    }

    return pairsString;
}