Example usage for java.lang String compareToIgnoreCase

List of usage examples for java.lang String compareToIgnoreCase

Introduction

In this page you can find the example usage for java.lang String compareToIgnoreCase.

Prototype

public int compareToIgnoreCase(String str) 

Source Link

Document

Compares two strings lexicographically, ignoring case differences.

Usage

From source file:com.piusvelte.sonet.core.SelectFriends.java

protected void loadFriends() {
    mFriends.clear();//  ww  w. java  2s . c  om
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            SonetCrypto sonetCrypto = SonetCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = sonetCrypto.Decrypt(account.getString(0));
                mSecret = sonetCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = SonetHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute(mAccountId);
}

From source file:org.rdv.ui.TimeSlider.java

/**
 * Paint the components. Also paint the slider and the markers.
 *///from ww w . j  a v a  2s.  c om
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

    Insets insets = getInsets();

    g.setColor(Color.lightGray);
    g.fillRect(insets.left + 6, insets.top + 4, getWidth() - insets.left - 12 - insets.right, 3);

    if (isEnabled()) {
        g.setColor(Color.gray);
        int startX = getXFromTime(start);
        int endX = getXFromTime(end);
        g.fillRect(startX, insets.top + 4, endX - startX, 3);
    }

    for (EventMarker marker : markers) {
        double markerTime = Double.parseDouble(marker.getProperty("timestamp"));
        if (markerTime >= minimum && markerTime <= maximum) {
            int x = getXFromTime(markerTime);
            if (x == -1) {
                continue;
            }

            Image markerImage;

            String markerType = marker.getProperty("type");
            if (markerType.compareToIgnoreCase("annotation") == 0) {
                markerImage = annotationMarkerImage;
            } else if (markerType.compareToIgnoreCase("start") == 0) {
                markerImage = startMarkerImage;
            } else if (markerType.compareToIgnoreCase("stop") == 0) {
                markerImage = stopMarkerImage;
            } else {
                markerImage = defaultMarkerImage;
            }

            g.drawImage(markerImage, x - 1, insets.top, null);
        }
    }
}

From source file:com.shafiq.myfeedle.core.SelectFriends.java

protected void loadFriends() {
    mFriends.clear();/*from www  .  ja v  a 2  s . c o m*/
    //      SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND, Entities.ESID}, new int[]{R.id.profile, R.id.name, R.id.selected});
    SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
            new String[] { Entities.FRIEND, Entities.ESID }, new int[] { R.id.name, R.id.selected });
    setListAdapter(sa);
    final ProgressDialog loadingDialog = new ProgressDialog(this);
    final AsyncTask<Long, String, Boolean> asyncTask = new AsyncTask<Long, String, Boolean>() {
        @Override
        protected Boolean doInBackground(Long... params) {
            boolean loadList = false;
            MyfeedleCrypto myfeedleCrypto = MyfeedleCrypto.getInstance(getApplicationContext());
            // load the session
            Cursor account = getContentResolver().query(Accounts.getContentUri(SelectFriends.this),
                    new String[] { Accounts.TOKEN, Accounts.SECRET, Accounts.SERVICE }, Accounts._ID + "=?",
                    new String[] { Long.toString(params[0]) }, null);
            if (account.moveToFirst()) {
                mToken = myfeedleCrypto.Decrypt(account.getString(0));
                mSecret = myfeedleCrypto.Decrypt(account.getString(1));
                mService = account.getInt(2);
            }
            account.close();
            String response;
            switch (mService) {
            case TWITTER:
                break;
            case FACEBOOK:
                if ((response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpGet(
                        String.format(FACEBOOK_FRIENDS, FACEBOOK_BASE_URL, Saccess_token, mToken)))) != null) {
                    try {
                        JSONArray friends = new JSONObject(response).getJSONArray(Sdata);
                        for (int i = 0, l = friends.length(); i < l; i++) {
                            JSONObject f = friends.getJSONObject(i);
                            HashMap<String, String> newFriend = new HashMap<String, String>();
                            newFriend.put(Entities.ESID, f.getString(Sid));
                            newFriend.put(Entities.PROFILE, String.format(FACEBOOK_PICTURE, f.getString(Sid)));
                            newFriend.put(Entities.FRIEND, f.getString(Sname));
                            // need to alphabetize
                            if (mFriends.isEmpty())
                                mFriends.add(newFriend);
                            else {
                                String fullName = f.getString(Sname);
                                int spaceIdx = fullName.lastIndexOf(" ");
                                String newFirstName = null;
                                String newLastName = null;
                                if (spaceIdx == -1)
                                    newFirstName = fullName;
                                else {
                                    newFirstName = fullName.substring(0, spaceIdx++);
                                    newLastName = fullName.substring(spaceIdx);
                                }
                                List<HashMap<String, String>> newFriends = new ArrayList<HashMap<String, String>>();
                                for (int i2 = 0, l2 = mFriends.size(); i2 < l2; i2++) {
                                    HashMap<String, String> oldFriend = mFriends.get(i2);
                                    if (newFriend == null) {
                                        newFriends.add(oldFriend);
                                    } else {
                                        fullName = oldFriend.get(Entities.FRIEND);
                                        spaceIdx = fullName.lastIndexOf(" ");
                                        String oldFirstName = null;
                                        String oldLastName = null;
                                        if (spaceIdx == -1)
                                            oldFirstName = fullName;
                                        else {
                                            oldFirstName = fullName.substring(0, spaceIdx++);
                                            oldLastName = fullName.substring(spaceIdx);
                                        }
                                        if (newFirstName == null) {
                                            newFriends.add(newFriend);
                                            newFriend = null;
                                        } else {
                                            int comparison = oldFirstName.compareToIgnoreCase(newFirstName);
                                            if (comparison == 0) {
                                                // compare firstnames
                                                if (newLastName == null) {
                                                    newFriends.add(newFriend);
                                                    newFriend = null;
                                                } else if (oldLastName != null) {
                                                    comparison = oldLastName.compareToIgnoreCase(newLastName);
                                                    if (comparison == 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    } else if (comparison > 0) {
                                                        newFriends.add(newFriend);
                                                        newFriend = null;
                                                    }
                                                }
                                            } else if (comparison > 0) {
                                                newFriends.add(newFriend);
                                                newFriend = null;
                                            }
                                        }
                                        newFriends.add(oldFriend);
                                    }
                                }
                                if (newFriend != null)
                                    newFriends.add(newFriend);
                                mFriends = newFriends;
                            }
                        }
                        loadList = true;
                    } catch (JSONException e) {
                        Log.e(TAG, e.toString());
                    }
                }
                break;
            case MYSPACE:
                break;
            case LINKEDIN:
                break;
            case FOURSQUARE:
                break;
            case IDENTICA:
                break;
            case GOOGLEPLUS:
                break;
            case CHATTER:
                break;
            }
            return loadList;
        }

        @Override
        protected void onPostExecute(Boolean loadList) {
            if (loadList) {
                //               SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend, new String[]{Entities.PROFILE, Entities.FRIEND}, new int[]{R.id.profile, R.id.name});
                SimpleAdapter sa = new SimpleAdapter(SelectFriends.this, mFriends, R.layout.friend,
                        new String[] { Entities.FRIEND, Entities.ESID },
                        new int[] { R.id.name, R.id.selected });
                sa.setViewBinder(mViewBinder);
                setListAdapter(sa);
            }
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
        }
    };
    loadingDialog.setMessage(getString(R.string.loading));
    loadingDialog.setCancelable(true);
    loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            if (!asyncTask.isCancelled())
                asyncTask.cancel(true);
        }
    });
    loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    loadingDialog.show();
    asyncTask.execute(mAccountId);
}

From source file:org.iexhub.services.GetPatientDataService.java

@GET
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public Response getPatientData(@Context HttpHeaders headers) {
    log.info("Entered getPatientData service");

    boolean tls = false;

    tls = (IExHubConfig.getProperty("XdsBRegistryEndpointURI") == null) ? false
            : ((IExHubConfig.getProperty("XdsBRegistryEndpointURI").toLowerCase().contains("https") ? true
                    : false));/*  w  w  w  . ja  v a2s  .c om*/
    GetPatientDataService.testMode = IExHubConfig.getProperty("TestMode", GetPatientDataService.testMode);
    GetPatientDataService.testJSONDocumentPathname = IExHubConfig.getProperty("TestJSONDocumentPathname",
            GetPatientDataService.testJSONDocumentPathname);
    GetPatientDataService.cdaToJsonTransformXslt = IExHubConfig.getProperty("CDAToJSONTransformXSLT",
            GetPatientDataService.cdaToJsonTransformXslt);
    GetPatientDataService.iExHubDomainOid = IExHubConfig.getProperty("IExHubDomainOID",
            GetPatientDataService.iExHubDomainOid);
    GetPatientDataService.iExHubAssigningAuthority = IExHubConfig.getProperty("IExHubAssigningAuthority",
            GetPatientDataService.iExHubAssigningAuthority);
    GetPatientDataService.xdsBRepositoryUniqueId = IExHubConfig.getProperty("XdsBRepositoryUniqueId",
            GetPatientDataService.xdsBRepositoryUniqueId);

    String retVal = "";
    GetPatientDataResponse patientDataResponse = new GetPatientDataResponse();
    StringBuilder jsonOutput = new StringBuilder();

    if (!testMode) {
        try {
            if (xdsB == null) {
                log.info("Instantiating XdsB connector...");
                xdsB = new XdsB(null, null, tls);
                log.info("XdsB connector successfully started");
            }
        } catch (Exception e) {
            log.error("Error encountered instantiating XdsB connector, " + e.getMessage());
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }

        try {
            MultivaluedMap<String, String> headerParams = headers.getRequestHeaders();
            String ssoAuth = headerParams.getFirst("ssoauth");
            log.info("HTTP headers successfully retrieved");

            // Extract patient ID, query start date, and query end date.  Expected format from the client is
            //   "PatientId={0}&LastName={1}&FirstName={2}&MiddleName={3}&DateOfBirth={4}&PatientGender={5}&MotherMaidenName={6}&AddressStreet={7}&AddressCity={8}&AddressState={9}&AddressPostalCode={10}&OtherIDsScopingOrganization={11}&StartDate={12}&EndDate={13}"
            String[] splitPatientId = ssoAuth.split("&LastName=");
            String patientId = (splitPatientId[0].split("=").length == 2) ? splitPatientId[0].split("=")[1]
                    : null;

            String[] parts = splitPatientId[1].split("&");
            String lastName = (parts[0].length() > 0) ? parts[0] : null;
            String firstName = (parts[1].split("=").length == 2) ? parts[1].split("=")[1] : null;
            String middleName = (parts[2].split("=").length == 2) ? parts[2].split("=")[1] : null;
            String dateOfBirth = (parts[3].split("=").length == 2) ? parts[3].split("=")[1] : null;
            String gender = (parts[4].split("=").length == 2) ? parts[4].split("=")[1] : null;
            String motherMaidenName = (parts[5].split("=").length == 2) ? parts[5].split("=")[1] : null;
            String addressStreet = (parts[6].split("=").length == 2) ? parts[6].split("=")[1] : null;
            String addressCity = (parts[7].split("=").length == 2) ? parts[7].split("=")[1] : null;
            String addressState = (parts[8].split("=").length == 2) ? parts[8].split("=")[1] : null;
            String addressPostalCode = (parts[9].split("=").length == 2) ? parts[9].split("=")[1] : null;
            String otherIDsScopingOrganization = (parts[10].split("=").length == 2) ? parts[10].split("=")[1]
                    : null;
            String startDate = (parts[11].split("=").length == 2) ? parts[11].split("=")[1] : null;
            String endDate = (parts[12].split("=").length == 2) ? parts[12].split("=")[1] : null;

            log.info("HTTP headers successfully parsed, now calling XdsB registry...");

            // Determine if a complete patient ID (including OID and ISO specification) was provided.  If not, then append IExHubDomainOid and IExAssigningAuthority...
            if (!patientId.contains("^^^&")) {
                patientId = "'" + patientId + "^^^&" + GetPatientDataService.iExHubDomainOid + "&"
                        + GetPatientDataService.iExHubAssigningAuthority + "'";
            }

            AdhocQueryResponse registryResponse = xdsB.registryStoredQuery(patientId,
                    (startDate != null) ? DateFormat.getDateInstance().format(startDate) : null,
                    (endDate != null) ? DateFormat.getDateInstance().format(endDate) : null);

            log.info("Call to XdsB registry successful");

            // Determine if registry server returned any errors...
            if ((registryResponse.getRegistryErrorList() != null)
                    && (registryResponse.getRegistryErrorList().getRegistryError().length > 0)) {
                for (RegistryError_type0 error : registryResponse.getRegistryErrorList().getRegistryError()) {
                    StringBuilder errorText = new StringBuilder();
                    if (error.getErrorCode() != null) {
                        errorText.append("Error code=" + error.getErrorCode() + "\n");
                    }
                    if (error.getCodeContext() != null) {
                        errorText.append("Error code context=" + error.getCodeContext() + "\n");
                    }

                    // Error code location (i.e., stack trace) only to be logged to IExHub error file
                    patientDataResponse.getErrorMsgs().add(errorText.toString());

                    if (error.getLocation() != null) {
                        errorText.append("Error location=" + error.getLocation());
                    }

                    log.error(errorText.toString());
                }
            }

            // Try to retrieve documents...
            RegistryObjectListType registryObjectList = registryResponse.getRegistryObjectList();
            IdentifiableType[] documentObjects = registryObjectList.getIdentifiable();
            if ((documentObjects != null) && (documentObjects.length > 0)) {
                log.info("Documents found in the registry, retrieving them from the repository...");

                HashMap<String, String> documents = new HashMap<String, String>();
                for (IdentifiableType identifiable : documentObjects) {
                    if (identifiable.getClass().equals(ExtrinsicObjectType.class)) {
                        // Determine if the "home" attribute (homeCommunityId in XCA parlance) is present...
                        String home = ((((ExtrinsicObjectType) identifiable).getHome() != null)
                                && (((ExtrinsicObjectType) identifiable).getHome().getPath().length() > 0))
                                        ? ((ExtrinsicObjectType) identifiable).getHome().getPath()
                                        : null;

                        ExternalIdentifierType[] externalIdentifiers = ((ExtrinsicObjectType) identifiable)
                                .getExternalIdentifier();

                        // Find the ExternalIdentifier that has the "XDSDocumentEntry.uniqueId" value...
                        String uniqueId = null;
                        for (ExternalIdentifierType externalIdentifier : externalIdentifiers) {
                            String val = externalIdentifier.getName().getInternationalStringTypeSequence()[0]
                                    .getLocalizedString().getValue().getFreeFormText();
                            if ((val != null) && (val.compareToIgnoreCase("XDSDocumentEntry.uniqueId") == 0)) {
                                log.info("Located XDSDocumentEntry.uniqueId ExternalIdentifier, uniqueId="
                                        + uniqueId);
                                uniqueId = externalIdentifier.getValue().getLongName();
                                break;
                            }
                        }

                        if (uniqueId != null) {
                            documents.put(uniqueId, home);
                            log.info("Document ID added: " + uniqueId + ", homeCommunityId: " + home);
                        }
                    } else {
                        String home = ((identifiable.getHome() != null)
                                && (identifiable.getHome().getPath().length() > 0))
                                        ? identifiable.getHome().getPath()
                                        : null;
                        documents.put(identifiable.getId().getPath(), home);
                        log.info("Document ID added: " + identifiable.getId().getPath() + ", homeCommunityId: "
                                + home);
                    }
                }

                log.info("Invoking XdsB repository connector retrieval...");
                RetrieveDocumentSetResponse documentSetResponse = xdsB
                        .retrieveDocumentSet(xdsBRepositoryUniqueId, documents, patientId);
                log.info("XdsB repository connector retrieval succeeded");

                // Invoke appropriate map(s) to process documents in documentSetResponse...
                if (documentSetResponse.getRetrieveDocumentSetResponse()
                        .getRetrieveDocumentSetResponseTypeSequence_type0() != null) {
                    DocumentResponse_type0[] docResponseArray = documentSetResponse
                            .getRetrieveDocumentSetResponse().getRetrieveDocumentSetResponseTypeSequence_type0()
                            .getDocumentResponse();
                    if (docResponseArray != null) {
                        jsonOutput.append("{\"Documents\":[");
                        boolean first = true;
                        try {
                            for (DocumentResponse_type0 document : docResponseArray) {
                                if (!first) {
                                    jsonOutput.append(",");
                                }
                                first = false;

                                log.info("Processing document ID="
                                        + document.getDocumentUniqueId().getLongName());

                                String mimeType = docResponseArray[0].getMimeType().getLongName();
                                if (mimeType.compareToIgnoreCase("text/xml") == 0) {
                                    final String filename = this.testOutputPath + "/"
                                            + document.getDocumentUniqueId().getLongName() + ".xml";
                                    log.info("Persisting document to filesystem, filename=" + filename);
                                    DataHandler dh = document.getDocument();
                                    File file = new File(filename);
                                    FileOutputStream fileOutStream = new FileOutputStream(file);
                                    dh.writeTo(fileOutStream);
                                    fileOutStream.close();

                                    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
                                    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
                                    Document doc = dBuilder.parse(new FileInputStream(filename));
                                    XPath xPath = XPathFactory.newInstance().newXPath();

                                    //set namespace to xpath
                                    xPath.setNamespaceContext(new NamespaceContext() {
                                        private final String uri = "urn:hl7-org:v3";
                                        private final String prefix = "hl7";

                                        @Override
                                        public String getNamespaceURI(String prefix) {
                                            return this.prefix.equals(prefix) ? uri : null;
                                        }

                                        @Override
                                        public String getPrefix(String namespaceURI) {
                                            return this.uri.equals(namespaceURI) ? this.prefix : null;
                                        }

                                        @Override
                                        public Iterator getPrefixes(String namespaceURI) {
                                            return null;
                                        }
                                    });

                                    NodeList nodes = (NodeList) xPath.evaluate(
                                            "/hl7:ClinicalDocument/hl7:templateId", doc.getDocumentElement(),
                                            XPathConstants.NODESET);

                                    boolean templateFound = false;
                                    if (nodes.getLength() > 0) {
                                        log.info("Searching for /ClinicalDocument/templateId, document ID="
                                                + document.getDocumentUniqueId().getLongName());

                                        for (int i = 0; i < nodes.getLength(); ++i) {
                                            String val = ((Element) nodes.item(i)).getAttribute("root");
                                            if ((val != null) && (val.compareToIgnoreCase(
                                                    "2.16.840.1.113883.10.20.22.1.2") == 0)) {
                                                log.info("/ClinicalDocument/templateId node found, document ID="
                                                        + document.getDocumentUniqueId().getLongName());

                                                log.info("Invoking XSL transform, document ID="
                                                        + document.getDocumentUniqueId().getLongName());

                                                DocumentBuilderFactory factory = DocumentBuilderFactory
                                                        .newInstance();
                                                factory.setNamespaceAware(true);
                                                DocumentBuilder builder = factory.newDocumentBuilder();
                                                Document mappedDoc = builder.parse(new File(filename));
                                                DOMSource source = new DOMSource(mappedDoc);

                                                TransformerFactory transformerFactory = TransformerFactory
                                                        .newInstance();

                                                Transformer transformer = transformerFactory
                                                        .newTransformer(new StreamSource(
                                                                GetPatientDataService.cdaToJsonTransformXslt));
                                                final String jsonFilename = this.testOutputPath + "/"
                                                        + document.getDocumentUniqueId().getLongName()
                                                        + ".json";
                                                File jsonFile = new File(jsonFilename);
                                                FileOutputStream jsonFileOutStream = new FileOutputStream(
                                                        jsonFile);
                                                StreamResult result = new StreamResult(jsonFileOutStream);
                                                transformer.transform(source, result);
                                                jsonFileOutStream.close();

                                                log.info("Successfully transformed CCDA to JSON, filename="
                                                        + jsonFilename);

                                                jsonOutput.append(new String(readAllBytes(get(jsonFilename))));

                                                templateFound = true;
                                            }
                                        }
                                    }

                                    if (!templateFound) {
                                        // Document doesn't match the template ID - add to error list...
                                        patientDataResponse.getErrorMsgs().add(
                                                "Document retrieved doesn't match required template ID - document ID="
                                                        + document.getDocumentUniqueId().getLongName());
                                    }
                                } else {
                                    patientDataResponse.getErrorMsgs()
                                            .add("Document retrieved is not XML - document ID="
                                                    + document.getDocumentUniqueId().getLongName());
                                }
                            }
                        } catch (Exception e) {
                            log.error("Error encountered, " + e.getMessage());
                            throw e;
                        }
                    }
                }

                if (jsonOutput.length() > 0) {
                    jsonOutput.append("]}");
                }
            }
        } catch (Exception e) {
            log.error("Error encountered, " + e.getMessage());
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }
    } else {
        // Return test document when testMode is true
        try {
            retVal = FileUtils.readFileToString(new File(GetPatientDataService.testJSONDocumentPathname));
            return Response.status(Response.Status.OK).entity(retVal).type(MediaType.APPLICATION_JSON).build();
        } catch (Exception e) {
            throw new UnexpectedServerException("Error - " + e.getMessage());
        }
    }

    return Response.status(Response.Status.OK).entity(jsonOutput.toString()).type(MediaType.APPLICATION_JSON)
            .build();
}

From source file:org.openmrs.module.tracpatienttransfer.web.controller.ExitPatientFromCareListController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ModelAndView mav = new ModelAndView();

    List<Integer> res;
    List<Integer> numberOfPages;

    if (Context.getAuthenticatedUser() == null)
        return new ModelAndView(new RedirectView(request.getContextPath() + "/login.htm"));

    if (!TracPatientTransferConfigurationUtil.isConfigured())
        return new ModelAndView(
                new RedirectView(request.getContextPath() + "/module/mohtracportal/configuration.form"));

    // load utils for the page
    loadUtils(mav);/*from ww  w . j a v  a  2 s. c om*/

    ObsService os = Context.getObsService();
    PatientTransferService service = Context.getService(PatientTransferService.class);

    int pageSize = TracPatientTransferConfigurationUtil.getNumberOfRecordPerPage();
    String pageNumber = request.getParameter("page");

    // rebuilding the existing parameters
    rebuildExistingParameters(request, mav);

    List<Obs> data = new ArrayList<Obs>();

    if (pageNumber == null) {
        mav.setViewName(getViewName() + "?page=1");
    } else
        mav.setViewName(getViewName());

    Integer locationId = null, conceptId = null;
    try {
        conceptId = (request.getParameter("reason") != null
                && request.getParameter("reason").trim().compareTo("") != 0)
                        ? Integer.parseInt(request.getParameter("reason"))
                        : null;
        locationId = (request.getParameter("location") != null
                && request.getParameter("location").trim().compareTo("") != 0)
                        ? Integer.parseInt(request.getParameter("location"))
                        : null;

        if (pageNumber.compareToIgnoreCase("1") == 0 || pageNumber.compareToIgnoreCase("") == 0) {

            res = new ArrayList<Integer>();
            res = service.getObsWithConceptReasonOfExit(conceptId, locationId);
            request.getSession().setAttribute("epfc_res", res);

            // data collection
            for (int i = 0; i < pageSize; i++) {
                if (res.size() == 0)
                    break;
                if (i >= res.size() - 1) {
                    data.add(os.getObs(res.get(i)));
                    break;
                } else
                    data.add(os.getObs(res.get(i)));
            }

            // paging
            int n = (res.size() == ((int) (res.size() / pageSize)) * pageSize) ? (res.size() / pageSize)
                    : ((int) (res.size() / pageSize)) + 1;
            numberOfPages = new ArrayList<Integer>();
            for (int i = 1; i <= n; i++) {
                numberOfPages.add(i);
            }
            request.getSession().setAttribute("epfc_numberOfPages", numberOfPages);

        } else {
            res = (ArrayList<Integer>) request.getSession().getAttribute("epfc_res");
            numberOfPages = (ArrayList<Integer>) request.getSession().getAttribute("epfc_numberOfPages");

            for (int i = (pageSize * (Integer.parseInt(pageNumber) - 1)); i < pageSize
                    * (Integer.parseInt(pageNumber)); i++) {
                if (i >= res.size())
                    break;
                else
                    data.add(os.getObs(res.get(i)));
            }
        }

        // page infos
        Object[] pagerInfos = new Object[3];
        pagerInfos[0] = (res.size() == 0) ? 0 : (pageSize * (Integer.parseInt(pageNumber) - 1)) + 1;
        pagerInfos[1] = (pageSize * (Integer.parseInt(pageNumber)) <= res.size())
                ? pageSize * (Integer.parseInt(pageNumber))
                : res.size();
        pagerInfos[2] = res.size();

        String pageInf = MohTracUtil.getMessage("tracpatienttransfer.pagingInfo.showingResults", pagerInfos);

        mav.addObject("numberOfPages", numberOfPages);
        mav.addObject("obsList", data);
        mav.addObject("pageSize", pageSize);
        mav.addObject("pageInfos", pageInf);

        if (Integer.valueOf(pageNumber) > 1)
            mav.addObject("prevPage", (Integer.valueOf(pageNumber)) - 1);
        else
            mav.addObject("prevPage", -1);
        if (Integer.valueOf(pageNumber) < numberOfPages.size())
            mav.addObject("nextPage", (Integer.valueOf(pageNumber)) + 1);
        else
            mav.addObject("nextPage", -1);
        mav.addObject("lastPage", ((numberOfPages.size() >= 1) ? numberOfPages.size() : 1));

        String locationTitle = (locationId != null)
                ? MohTracUtil.getMessage("Encounter.location", null) + " : "
                        + Context.getLocationService().getLocation(locationId).getName()
                : "";
        String reasonOfExitTitle = (conceptId != null)
                ? MohTracUtil.getMessage("tracpatienttransfer.general.reasonofexit.title", null) + " : "
                        + TransferOutInPatientTag.getConceptNameById("" + conceptId)
                : "";

        String title = reasonOfExitTitle
                + ((reasonOfExitTitle.trim().compareTo("") == 0 || locationTitle.trim().compareTo("") == 0) ? ""
                        : " ; ")
                + locationTitle;
        title = (title.trim().compareTo("") == 0)
                ? MohTracUtil.getMessage("tracpatienttransfer.general.allexit.title", null)
                : title;
        mav.addObject("title", title);

        FileExporter fexp = new FileExporter();

        if (request.getParameter("export") != null
                && request.getParameter("export").compareToIgnoreCase("csv") == 0) {
            fexp.exportToCSVFile(request, response, res, "list_of_patients_exited_from_care.csv",
                    "List of Patients exited from care");
        }
        if (request.getParameter("export") != null
                && request.getParameter("export").compareToIgnoreCase("pdf") == 0) {
            fexp.exportToPDF(request, response, res, "list_of_patients_exited_from_care.pdf",
                    "List of Patients exited from care");
        }

        Integer nullVal = null;
        mav.addObject("nullVal", nullVal);

    } catch (Exception ex) {
        String msg = getMessageSourceAccessor().getMessage("tracpatienttransfer.error.onloaddata");
        request.getSession().setAttribute(WebConstants.OPENMRS_ERROR_ATTR, msg);
        ex.printStackTrace();
    }

    return mav;
}

From source file:org.kuali.student.enrollment.class2.courseoffering.helper.impl.ActivityOfferingScheduleHelperImpl.java

/**
 * This method retrieves a list of matching end times for days and startime entered by the user. This loads
 * only the standard timeslots.//from  ww  w .ja v a 2s. c om
 *
 * @param days
 * @param startTime
 * @param timeSlotType
 * @return
 * @throws Exception
 */
public List<String> getEndTimes(String days, String startTime, String timeSlotType) throws Exception {

    if (StringUtils.isBlank(timeSlotType)) {
        return new ArrayList<String>();
    }

    List<Integer> daysArray = SchedulingServiceUtil.weekdaysString2WeekdaysList(days);
    TimeOfDayInfo timeOfDayInfo = TimeOfDayHelper.makeTimeOfDayInfoFromTimeString(startTime);
    List<TimeSlotInfo> timeSlotInfos = CourseOfferingManagementUtil.getSchedulingService()
            .getTimeSlotsByDaysAndStartTime(timeSlotType, daysArray, timeOfDayInfo, createContextInfo());
    List<String> endTimes = new ArrayList<String>();

    for (TimeSlotInfo ts : timeSlotInfos) {
        TimeOfDayInfo st = ts.getStartTime();
        if (st != null) {
            endTimes.add(TimeOfDayHelper.makeFormattedTimeForAOSchedules(ts.getEndTime()));
        }
    }

    Collections.sort(endTimes, new Comparator<String>() {
        @Override
        public int compare(String time1, String time2) {

            String startam = StringUtils.substringAfter(time1, " ");
            String starttime = StringUtils.substringBefore(time1, " ");
            String endam = StringUtils.substringAfter(time2, " ");
            String endtime = StringUtils.substringBefore(time2, " ");

            return startam.compareToIgnoreCase(endam) + starttime.compareToIgnoreCase(endtime);
        }
    });

    return endTimes;
}

From source file:com.swordlord.jalapeno.datarow.DataRowBase.java

public void setRelation(DataRowBase targetRow) {
    /*/*w ww  .ja  v  a2  s.  com*/
     * // call extensions, if any if(uuidEPDBCommon != null) {
     * List<IDBCommon> listPlugins = getExtensionObjects(uuidEPDBCommon);
     * 
     * for(IDBCommon plug : listPlugins) { try {
     * plug.setRelation(targetObject, this); } catch(Exception ex) {
     * Controller.instance().getLogger().info(plug);
     * Controller.instance().getLogger().error(ex); } } }
     */

    // Find relation information
    String strTargetName = targetRow.getName();

    String strSourceClassName = getClassName();

    Collection<ObjEntity> entities = getObjectContext().getEntityResolver().getObjEntities();

    Iterator<ObjEntity> itEntities = entities.iterator();
    while (itEntities.hasNext()) {
        ObjEntity entity = itEntities.next();
        if (strSourceClassName.compareTo(entity.getClassName()) == 0) {
            // we found the source entity, now lets find all relations from
            // this entity
            Collection<ObjRelationship> relations = entity.getRelationships();
            Iterator<ObjRelationship> itRelations = relations.iterator();
            while (itRelations.hasNext()) {
                ObjRelationship relation = itRelations.next();
                if (strTargetName.compareToIgnoreCase(relation.getTargetEntityName()) == 0) {
                    // Switch ObjectContext before setting relation
                    // problem is that different rows exist in different
                    // contexts (different gozer frames)
                    //DataRowBase row = (DataRowBase) getObjectContext().localObject( targetRow.getObjectId(), targetRow);

                    DataRowBase row = (DataRowBase) getObjectContext().localObject(targetRow);

                    // set the relation
                    if (relation.isToMany()) {
                        addToManyTarget(relation.getName(), row, true);
                    } else {
                        setToOneTarget(relation.getName(), row, true);
                    }

                    // This is an ugly hack to set the property as well, not
                    // only the relation.
                    // we have to do this since Cayenne otherwise can't
                    // persist because of a validation error (ID missing)
                    // TODO: Clean this up. Cayenne has to do something
                    // along this before persisting
                    // so lets look up how they work out that problem and
                    // copy it to here.
                    if (relation.isToPK()) {
                        this.setProperty(targetRow.getKeyName(), targetRow.getKey().toString());
                    } else {
                        targetRow.setProperty(this.getKeyName(), this.getKey().toString());
                    }

                    break;
                }
            }
        }
    }
}

From source file:org.lockss.exporter.biblio.BibliographicUtil.java

/**
 * Determines whether a String appears to represent a range. In general, a
 * range is considered to be two strings which are both either numeric
 * (representing an integer or a Roman numeral) or non-numeric,
 * separated by a hyphen '-' and with optional whitespace.
 * The second value is expected to be numerically or lexically greater than
 * or equal to the first. For example, "s1-4" would not qualify as either a
 * numeric or a non-numeric range, while "I-4" ("I" being a Roman number) and
 * the string range "a-baa" would. Numerical ordering is checked if the
 * strings are numerical, otherwise case-insensitive lexical ordering is
 * checked./*from   www . java 2  s.c  om*/
 * <p>
 * A numeric range must have two numeric values separated by a '-', while a
 * non-numeric range has two non-numeric values. In theory a string like
 * "s1-4" could represent a range, as could "1-s4", but it is impossible to
 * say whether either of these represents a genuine range with
 * different-format endpoints, or a single identifier. This is why the
 * condition is imposed that the strings either side of the hyphen must be
 * both numeric, or both non-numeric and of roughly the same format.
 * That is, either they are both parsable as integers, or they both involve
 * non-digit tokens that cannot be parsed as integers.
 * <p>
 * To allow for identifiers that themselves incorporate a hyphen, the input
 * string is only split around the centremost hyphen. If there is an even
 * number of hyphens, the input string is assumed not to represent a parsable
 * range.
 * <p>
 * Further restrictions are enforced upon non-numerical strings that may be
 * considered valid endpoints of a range; if one side of a possible range can
 * be parsed as a normalised Roman number, the string will be considered a
 * range <i>only if</i> the tokens either side of the hyphen are the same
 * length and case, <i>and</i> they are lexically either equal or increasing.
 * <p>
 * Note that the motive for this method was to identify volume ranges, but
 * it should work just as well for other ranges that have the same kind of
 * characteristics, such as issue ranges, and numerical ranges.
 *
 * @param range the input String
 * @return <tt>true</tt> if the input string represents a range
 */
public static boolean isRange(String range) {
    if (range == null)
        return false;
    // Check if it is a numerical range
    if (NumberUtil.isNumericalRange(range))
        return true;
    // We are now dealing with either a non-range, or at least one non-numerical
    // endpoint. Find the range-separating hyphen.
    int hyphenPos = NumberUtil.findRangeHyphen(range);
    if (hyphenPos < 0)
        return false;
    // Split string at middlemost hyphen
    String s1 = range.substring(0, hyphenPos).trim();
    String s2 = range.substring(hyphenPos + 1).trim();
    // Check format of strings
    if (changeOfFormats(s1, s2))
        return false;
    // Check if one side of the hyphen can be interpreted as a Roman number;
    // we already know that it is not a numerical range (both sides numerical).
    // If one side only might be Roman numerical, and is either a different size
    // or case to the other side, or suggests a descending alphabetical range,
    // return false (not a range)
    if ((NumberUtil.isNumber(s1) || NumberUtil.isNumber(s2))
            && (s1.length() != s2.length() || !areSameCasing(s1, s2) || s1.compareTo(s2) > 0))
        return false;

    // Normalise the Roman tokens and test lexically
    if (normaliseIdentifier(s2).compareToIgnoreCase(normaliseIdentifier(s1)) >= 0)
        return true;
    // Check lexical order as a last resort
    return (s2.compareToIgnoreCase(s1) >= 0);
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.ProductDetails.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Payer.ResultStates state = payer.handleResult(requestCode, resultCode, data);

    if (state == Payer.ResultStates.SUCCESS) {
        setContentView(R.layout.details_instead_thanks_page);
        ((TextView) findViewById(R.id.title)).setText(Statics.widgetName);
        findViewById(R.id.back_btn).setOnClickListener(new View.OnClickListener() {
            @Override//from   ww w.  j ava2  s . c  o  m
            public void onClick(View view) {
                finish();
            }
        });
        thanksPage = true;

        return;
    } else if (state == Payer.ResultStates.NOT_SUCCESS) {
        return;
    }

    switch (requestCode) {
    case FACEBOOK_AUTHORIZATION_ACTIVITY: {
        if (resultCode == RESULT_OK)
            shareFacebook();
        //                else if (resultCode == RESULT_CANCELED)
        //                    Toast.makeText(ProductDetails.this, getResources().getString(R.string.alert_facebook_auth_error), Toast.LENGTH_SHORT).show();
    }
        break;
    case TWITTER_AUTHORIZATION_ACTIVITY: {
        if (resultCode == RESULT_OK)
            shareTwitter();
        //                else if (resultCode == RESULT_CANCELED)
        //                    Toast.makeText(ProductDetails.this, getResources().getString(R.string.alert_twitter_auth_error), Toast.LENGTH_SHORT).show();
    }
        break;

    case TWITTER_PUBLISH_ACTIVITY: {
        if (resultCode == RESULT_OK) {
            Toast.makeText(ProductDetails.this,
                    getResources().getString(R.string.directoryplugin_twitter_posted_success),
                    Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(ProductDetails.this,
                    getResources().getString(R.string.directoryplugin_twitter_posted_error), Toast.LENGTH_LONG)
                    .show();
        }
    }
        break;

    case FACEBOOK_PUBLISH_ACTIVITY: {
        if (resultCode == RESULT_OK) {
            Toast.makeText(ProductDetails.this,
                    getResources().getString(R.string.directoryplugin_facebook_posted_success),
                    Toast.LENGTH_LONG).show();
        } else if (resultCode == RESULT_CANCELED) {
            Toast.makeText(ProductDetails.this,
                    getResources().getString(R.string.directoryplugin_facebook_posted_error), Toast.LENGTH_LONG)
                    .show();
        }
    }
        break;

    case AUTHORIZATION_FB: {
        if (resultCode == RESULT_OK) {

            List<String> userLikes = null;
            try {
                userLikes = FacebookAuthorizationActivity.getUserOgLikes();
                if (userLikes != null)
                    for (String likeUrl : userLikes) {
                        if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) {
                            likedbyMe = true;
                            break;
                        }
                    }

                if (!likedbyMe) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (FacebookAuthorizationActivity.like(product.imageURL)) {
                                    String likeCountStr = likeCount.getText().toString();
                                    try {
                                        final int res = Integer.parseInt(likeCountStr);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                likeCount.setText(Integer.toString(res + 1));
                                                Toast.makeText(ProductDetails.this,
                                                        getString(R.string.like_success), Toast.LENGTH_SHORT)
                                                        .show();
                                                enableLikeButton(false);
                                            }
                                        });
                                    } catch (NumberFormatException e) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                Toast.makeText(ProductDetails.this,
                                                        getString(R.string.like_error), Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        });
                                    }
                                }
                            } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) {

                            } catch (FacebookAuthorizationActivity.FacebookAlreadyLiked facebookAlreadyLiked) {
                                facebookAlreadyLiked.printStackTrace();
                            }
                        }
                    }).start();
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            enableLikeButton(false);
                            Toast.makeText(ProductDetails.this, getString(R.string.already_liked),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) {

            }
        }
    }
        break;
    }
}