Example usage for org.apache.commons.lang StringUtils substring

List of usage examples for org.apache.commons.lang StringUtils substring

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils substring.

Prototype

public static String substring(String str, int start, int end) 

Source Link

Document

Gets a substring from the specified String avoiding exceptions.

Usage

From source file:org.openmrs.cwf.api.property.PropertyService.java

/**
 * Sets the value of a named user property.
 * /*ww  w  .j a va2  s .c  o  m*/
 * @param propertyName Name of the user property.
 * @param value The property value. Values in excess of 255 characters are chunked.
 */
private void setUserPropertyValue(String propertyName, String value) {
    User user = Context.getAuthenticatedUser();

    if (user == null) {
        return;
    }

    boolean changed = false;

    for (int i = 0; i < value.length(); i += 255) {
        changed = true;
        user.setUserProperty(propertyName, StringUtils.substring(value, i, i + 255));
        propertyName = getNextPropertyName(propertyName);
    }

    while (user.getUserProperty(propertyName, null) != null) {
        changed = true;
        user.removeUserProperty(propertyName);
        propertyName = getNextPropertyName(propertyName);
    }

    if (changed) {
        try {
            Context.addProxyPrivilege(PrivilegeConstants.EDIT_USERS);
            Context.getUserService().saveUser(user, null);
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.EDIT_USERS);
        }
    }
}

From source file:org.openmrs.module.pacsintegration.converter.OrderToPacsConverter.java

public String convertToPacsFormat(RadiologyOrder order, String orderControl) throws HL7Exception {

    // TODO: some kind of null checking and checking for invalid values

    ORM_O01 message = new ORM_O01();

    // handle the MSH component
    MSH msh = message.getMSH();/*from   w  w  w. java2s .c  om*/
    HL7Utils.populateMessageHeader(msh, new Date(), "ORM", "O01",
            adminService.getGlobalProperty(PacsIntegrationConstants.GP_SENDING_FACILITY));

    // handle the patient component
    PID pid = message.getPATIENT().getPID();
    pid.getPatientIDInternalID(0).getID()
            .setValue(order.getPatient().getPatientIdentifier(getPatientIdentifierType()).getIdentifier());
    pid.getPatientName().getFamilyName().setValue(StringUtils.substring(order.getPatient().getFamilyName(), 0,
            PacsIntegrationConstants.MAX_LENGTH_FAMILY_NAME));
    pid.getPatientName().getGivenName().setValue(StringUtils.substring(order.getPatient().getGivenName(), 0,
            PacsIntegrationConstants.MAX_LENGTH_GIVEN_NAME));
    pid.getDateOfBirth().getTimeOfAnEvent()
            .setValue(order.getPatient().getBirthdate() != null
                    ? HL7Utils.getHl7DateFormat().format(order.getPatient().getBirthdate())
                    : "");
    pid.getSex().setValue(order.getPatient().getGender());
    // TODO: do we need patient admission ID / account number

    PV1 pv1 = message.getPATIENT().getPATIENT_VISIT().getPV1();

    // TODO: do we need patient class
    if (order.getExamLocation() != null) {

        // set the location code if one has been specified
        String locationCode = getLocationCode(order.getExamLocation());
        if (StringUtils.isNotBlank(locationCode)) {
            pv1.getAssignedPatientLocation().getPointOfCare().setValue(locationCode);
        }

        pv1.getAssignedPatientLocation().getLocationType().setValue(order.getExamLocation().getName());
    }

    if (order.getEncounter() != null) {
        Set<Provider> referringProviders = order.getEncounter()
                .getProvidersByRole(emrApiProperties.getOrderingProviderEncounterRole());
        if (referringProviders != null && referringProviders.size() > 0) {
            // note that if there are multiple clinicians associated with the encounter, we only sent the first one
            Provider referringProvider = referringProviders.iterator().next();
            pv1.getReferringDoctor(0).getIDNumber().setValue(referringProvider.getIdentifier());
            pv1.getReferringDoctor(0).getFamilyName().setValue(referringProvider.getPerson().getFamilyName());
            pv1.getReferringDoctor(0).getGivenName().setValue(referringProvider.getPerson().getGivenName());
        }
    }

    ORC orc = message.getORDER().getORC();
    orc.getOrderControl().setValue(orderControl);

    OBR obr = message.getORDER().getORDER_DETAIL().getOBR();
    obr.getFillerOrderNumber().getEntityIdentifier().setValue(order.getOrderNumber());
    obr.getUniversalServiceIdentifier().getIdentifier().setValue(getProcedureCode(order));

    obr.getUniversalServiceIdentifier().getText()
            .setValue(StringUtils.substring(
                    order.getConcept().getFullySpecifiedName(getDefaultLocale()).getName(), 0,
                    PacsIntegrationConstants.MAX_LENGTH_PROCEDURE_TYPE_DESCRIPTION));

    // note that we are just sending modality here, not the device location
    obr.getPlacerField2().setValue(getModalityCode(order));
    obr.getQuantityTiming().getPriority().setValue(order.getUrgency().equals(Order.Urgency.STAT) ? "STAT" : "");
    obr.getScheduledDateTime().getTimeOfAnEvent()
            .setValue(HL7Utils.getHl7DateFormat().format(order.getDateActivated()));

    // break the reason for study up by lines
    if (StringUtils.isNotBlank(order.getClinicalHistory())) {
        int i = 0;
        for (String line : order.getClinicalHistory().split("\r\n")) {
            obr.getReasonForStudy(i).getText().setValue(line);
            i++;
        }
    }

    return parser.encode(message);
}

From source file:org.osaf.cosmo.calendar.EntityConverter.java

private void setCalendarAttributes(NoteItem note, VEvent event) {

    // UID (only set if master)
    if (event.getUid() != null && note.getModifies() == null)
        note.setIcalUid(event.getUid().getValue());

    // for now displayName is limited to 1024 chars
    if (event.getSummary() != null)
        note.setDisplayName(StringUtils.substring(event.getSummary().getValue(), 0, 1024));

    if (event.getDescription() != null)
        note.setBody(event.getDescription().getValue());

    // look for DTSTAMP
    if (event.getDateStamp() != null)
        note.setClientModifiedDate(event.getDateStamp().getDate());

    // look for absolute VALARM
    VAlarm va = ICalendarUtils.getDisplayAlarm(event);
    if (va != null && va.getTrigger() != null) {
        Trigger trigger = va.getTrigger();
        Date reminderTime = trigger.getDateTime();
        if (reminderTime != null)
            note.setReminderTime(reminderTime);
    }/*  www . j a  v a2s.  co  m*/

    // calculate triage status based on start date
    java.util.Date now = java.util.Calendar.getInstance().getTime();
    boolean later = event.getStartDate().getDate().after(now);
    int code = (later) ? TriageStatus.CODE_LATER : TriageStatus.CODE_DONE;

    TriageStatus triageStatus = note.getTriageStatus();

    // initialize TriageStatus if not present
    if (triageStatus == null) {
        triageStatus = TriageStatusUtil.initialize(entityFactory.createTriageStatus());
        note.setTriageStatus(triageStatus);
    }

    triageStatus.setCode(code);

    // check for X-OSAF-STARRED
    if ("TRUE".equals(ICalendarUtils.getXProperty(X_OSAF_STARRED, event))) {
        TaskStamp ts = StampUtils.getTaskStamp(note);
        if (ts == null)
            note.addStamp(entityFactory.createTaskStamp());
    }
}

From source file:org.osaf.cosmo.calendar.EntityConverter.java

private void setCalendarAttributes(NoteItem note, VToDo task) {

    // UID//ww w  .  j  av a2 s  . c o  m
    if (task.getUid() != null)
        note.setIcalUid(task.getUid().getValue());

    // for now displayName is limited to 1024 chars
    if (task.getSummary() != null)
        note.setDisplayName(StringUtils.substring(task.getSummary().getValue(), 0, 1024));

    if (task.getDescription() != null)
        note.setBody(task.getDescription().getValue());

    // look for DTSTAMP
    if (task.getDateStamp() != null)
        note.setClientModifiedDate(task.getDateStamp().getDate());

    // look for absolute VALARM
    VAlarm va = ICalendarUtils.getDisplayAlarm(task);
    if (va != null && va.getTrigger() != null) {
        Trigger trigger = va.getTrigger();
        Date reminderTime = trigger.getDateTime();
        if (reminderTime != null)
            note.setReminderTime(reminderTime);
    }

    // look for COMPLETED or STATUS:COMPLETED
    Completed completed = task.getDateCompleted();
    Status status = task.getStatus();
    TriageStatus ts = note.getTriageStatus();

    // Initialize TriageStatus if necessary
    if (completed != null || Status.VTODO_COMPLETED.equals(status)) {
        if (ts == null) {
            ts = TriageStatusUtil.initialize(entityFactory.createTriageStatus());
            note.setTriageStatus(ts);
        }

        // TriageStatus.code will be DONE
        note.getTriageStatus().setCode(TriageStatus.CODE_DONE);

        // TriageStatus.rank will be the COMPLETED date if present
        // or currentTime
        if (completed != null)
            note.getTriageStatus().setRank(TriageStatusUtil.getRank(completed.getDate().getTime()));
        else
            note.getTriageStatus().setRank(TriageStatusUtil.getRank(System.currentTimeMillis()));
    }

    // check for X-OSAF-STARRED
    if ("TRUE".equals(ICalendarUtils.getXProperty(X_OSAF_STARRED, task))) {
        TaskStamp taskStamp = StampUtils.getTaskStamp(note);
        if (taskStamp == null)
            note.addStamp(entityFactory.createTaskStamp());
    }
}

From source file:org.osaf.cosmo.calendar.EntityConverter.java

private void setCalendarAttributes(NoteItem note, VJournal journal) {
    // UID/*from w w w. j  av  a  2  s  .co  m*/
    if (journal.getUid() != null)
        note.setIcalUid(journal.getUid().getValue());

    // for now displayName is limited to 1024 chars
    if (journal.getSummary() != null)
        note.setDisplayName(StringUtils.substring(journal.getSummary().getValue(), 0, 1024));

    if (journal.getDescription() != null)
        note.setBody(journal.getDescription().getValue());

    // look for DTSTAMP
    if (journal.getDateStamp() != null)
        note.setClientModifiedDate(journal.getDateStamp().getDate());
}

From source file:org.osaf.cosmo.dao.hibernate.EventLogDaoImpl.java

private void updateDisplayName(HibEventLogEntry hibEntry, ItemEntry entry) {
    Item item = entry.getItem();//from w  w w  . jav a2s.  com
    String displayName = item.getDisplayName();

    // handle case of "missing" displayName
    if (displayName == null) {
        if (item instanceof NoteItem) {
            NoteItem note = (NoteItem) item;
            if (note.getModifies() != null)
                displayName = note.getModifies().getDisplayName();
        }
    }

    // limit to 255 chars
    hibEntry.setStrval1(StringUtils.substring(displayName, 0, 255));
}

From source file:org.patientview.patientview.model.Message.java

public String getSummary() {
    if (content.length() > SUMMARY_LENGTH) {
        return StringUtils.substring(content, 0, SUMMARY_LENGTH) + " ...";
    }//w  w  w .j  a  v  a2  s .c  om

    return content;
}

From source file:org.phoenicis.win32.registry.RegistryParser.java

public RegistryKey parseFile(File registryFile, String rootName) {
    try (BufferedReader bufferReader = new BufferedReader(new FileReader(registryFile))) {
        final RegistryKey root = new RegistryKey(rootName);
        RegistryKey lastNode = null;//from   w  w w  . jav a 2 s . c  o m
        int lineNumber = 1;
        for (String currentLine = bufferReader.readLine(); currentLine != null; currentLine = bufferReader
                .readLine()) {

            while (currentLine.trim().endsWith("\\")) {
                currentLine = StringUtils.substring(currentLine.trim(), 0, -1) + bufferReader.readLine().trim();
            }

            if (currentLine.startsWith(";") || currentLine.startsWith("#") || StringUtils.isBlank(currentLine)
                    || currentLine.startsWith("@")) {
                lineNumber++;
                continue;
            }

            if (currentLine.startsWith("[")) {
                lastNode = this.parseDirectoryLine(root, currentLine);
            } else if (lineNumber == 1) {
                lineNumber++;
                continue;
            } else if (lastNode == null) {
                throw new ParseException(String.format(PARSE_ERROR_MESSAGE, lineNumber), 0);
            } else {
                this.parseValueLine(lastNode, currentLine, lineNumber);
            }

            lineNumber++;
        }

        return root;
    } catch (IOException | ParseException e) {
        throw new IllegalArgumentException("Error while parsing the registry", e);
    }
}

From source file:org.redpill.alfresco.pdfapilot.worker.PdfaPilotWorker.java

private String getBasename(NodeRef node) {
    if (node == null || !_nodeService.exists(node)) {
        return "PPCTW_" + GUID.generate();
    }/* w  w w  .j a  va2 s  . c om*/

    try {
        String filename = (String) _nodeService.getProperty(node, ContentModel.PROP_NAME);

        String basename = FilenameUtils.getBaseName(filename);

        // TODO: Investigate if this is really needed
        // callas currently has a bug that makes it crash if the whole filepath is
        // longer than 260 characters
        basename = StringUtils.substring(basename, 0, 100);

        // 0x2013 is the long hyphen, not allowed here...
        char c = 0x2013;
        if (StringUtils.contains(basename, c)) {
            if (LOG.isTraceEnabled()) {
                LOG.trace("Long hyphen replaced with short one");
            }

            basename = StringUtils.replaceChars(basename, c, '-');
        }

        filename = basename;

        if (LOG.isTraceEnabled()) {
            LOG.trace("Filename before normalization");

            for (char character : filename.toCharArray()) {
                LOG.trace(character + " : " + (int) character);
            }
        }

        filename = Normalizer.normalize(filename, Form.NFKC);

        if (LOG.isTraceEnabled()) {
            LOG.trace("Filename after normalization");

            for (char character : filename.toCharArray()) {
                LOG.trace(character + " : " + (int) character);
            }
        }

        // pad the string with _ until it's at lest 3 characters long
        if (basename.length() < 3) {
            basename = StringUtils.rightPad(basename, 3, "_");
        }

        return basename;
    } catch (final Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.reusables.dbunit.autocomplete.AutoCompletionDataset.java

private Object generateValue(final AutoCompletionColumn column, final Object orgValue,
        final AutoCompletionRules rules) {
    if (orgValue instanceof String) {
        final String str = (String) orgValue;
        final String prefix = rules.getGenPrefixPlusSeparator();
        final String postfix = rules.getGenPostfix();

        if (str.length() > prefix.length() + postfix.length() && str.startsWith(prefix)
                && (StringUtils.isEmpty(postfix) || str.endsWith(postfix))) {
            final String orgValueStr = str;
            return StringUtils.substring(orgValueStr, prefix.length(), orgValueStr.length() - postfix.length());
        }/*  w w  w. j  av  a 2s. c o m*/
    }

    final Integer randomValue = getRandomValue(column);
    final String value = StringUtils.defaultString(column.getValue());

    switch (column.getType()) {
    case NUMBER:
        return randomValue != null ? randomValue : value;
    case FK:
    case PK:
    case STRING:
        return String.format("%s%s", value, ObjectUtils.toString(randomValue));
    }

    return ITable.NO_VALUE;
}