Example usage for org.springframework.util StringUtils hasLength

List of usage examples for org.springframework.util StringUtils hasLength

Introduction

In this page you can find the example usage for org.springframework.util StringUtils hasLength.

Prototype

public static boolean hasLength(@Nullable String str) 

Source Link

Document

Check that the given String is neither null nor of length 0.

Usage

From source file:org.openmrs.api.impl.OrderServiceImpl.java

/**
 * @see org.openmrs.api.OrderService#voidOrder(org.openmrs.Order, java.lang.String)
 *//*from ww  w .  j a v a  2 s . c o  m*/
public Order voidOrder(Order order, String voidReason) throws APIException {
    if (!StringUtils.hasLength(voidReason)) {
        throw new IllegalArgumentException("voidReason cannot be empty or null");
    }

    Order previousOrder = order.getPreviousOrder();
    if (previousOrder != null && isDiscontinueOrReviseOrder(order)) {
        setProperty(previousOrder, "dateStopped", null);
    }

    return saveOrderInternal(order, null);
}

From source file:org.openmrs.hl7.handler.ORUR01Handler.java

/**
 * Bulk of the processing done here. Called by the main processMessage method
 *
 * @param oru the message to process//from w ww .  j a  v a  2 s  . c o  m
 * @return the processed message
 * @throws HL7Exception
 * @should process multiple NK1 segments
 */
@SuppressWarnings("deprecation")
private Message processORU_R01(ORU_R01 oru) throws HL7Exception {

    // TODO: ideally, we would branch or alter our behavior based on the
    // sending application.
    // String sendingApplication = getSendingApplication(oru);

    // validate message
    validate(oru);

    // extract segments for convenient use below
    MSH msh = getMSH(oru);
    PID pid = getPID(oru);
    List<NK1> nk1List = getNK1List(oru);
    PV1 pv1 = getPV1(oru);
    ORC orc = getORC(oru); // we're using the ORC assoc with first OBR to
    // hold data enterer and date entered for now

    // Obtain message control id (unique ID for message from sending
    // application)
    String messageControlId = msh.getMessageControlID().getValue();
    if (log.isDebugEnabled()) {
        log.debug("Found HL7 message in inbound queue with control id = " + messageControlId);
    }

    HL7Service hl7Service = Context.getHL7Service();

    // create the encounter
    Patient patient = getPatient(pid);
    if (log.isDebugEnabled()) {
        log.debug("Processing HL7 message for patient " + patient.getPatientId());
    }
    Encounter encounter = createEncounter(msh, patient, pv1, orc);

    // do the discharge to location logic
    try {
        updateHealthCenter(patient, pv1);
    } catch (Exception e) {
        log.error("Error while processing Discharge To Location (" + messageControlId + ")", e);
    }

    // process NK1 (relationship) segments
    for (NK1 nk1 : nk1List) {
        processNK1(patient, nk1);
    }

    // list of concepts proposed in the obs of this encounter.
    // these proposals need to be created after the encounter
    // has been created
    List<ConceptProposal> conceptProposals = new ArrayList<ConceptProposal>();

    // create observations
    if (log.isDebugEnabled()) {
        log.debug("Creating observations for message " + messageControlId + "...");
    }
    // we ignore all MEDICAL_RECORD_OBSERVATIONS that are OBRs.  We do not
    // create obs_groups for them
    List<Integer> ignoredConceptIds = new ArrayList<Integer>();

    String obrConceptId = Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_MEDICAL_RECORD_OBSERVATIONS, "1238");
    if (StringUtils.hasLength(obrConceptId)) {
        ignoredConceptIds.add(Integer.valueOf(obrConceptId));
    }

    // we also ignore all PROBLEM_LIST that are OBRs
    String obrProblemListConceptId = Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PROBLEM_LIST, "1284");
    if (StringUtils.hasLength(obrProblemListConceptId)) {
        ignoredConceptIds.add(Integer.valueOf(obrProblemListConceptId));
    }

    ORU_R01_PATIENT_RESULT patientResult = oru.getPATIENT_RESULT();
    int numObr = patientResult.getORDER_OBSERVATIONReps();
    for (int i = 0; i < numObr; i++) {
        if (log.isDebugEnabled()) {
            log.debug("Processing OBR (" + i + " of " + numObr + ")");
        }
        ORU_R01_ORDER_OBSERVATION orderObs = patientResult.getORDER_OBSERVATION(i);

        // the parent obr
        OBR obr = orderObs.getOBR();

        if (!StringUtils.hasText(obr.getUniversalServiceIdentifier().getIdentifier().getValue())) {
            throw new HL7Exception(Context.getMessageSourceService().getMessage("ORUR01.errorInvalidOBR ",
                    new Object[] { messageControlId }, null));
        }

        // if we're not ignoring this obs group, create an
        // Obs grouper object that the underlying obs objects will use
        Obs obsGrouper = null;
        Concept obrConcept = getConcept(obr.getUniversalServiceIdentifier(), messageControlId);
        if (obrConcept != null && !ignoredConceptIds.contains(obrConcept.getId())) {
            // maybe check for a parent obs group from OBR-29 Parent ?

            // create an obs for this obs group too
            obsGrouper = new Obs();
            obsGrouper.setConcept(obrConcept);
            obsGrouper.setPerson(encounter.getPatient());
            obsGrouper.setEncounter(encounter);
            Date datetime = getDatetime(obr);
            if (datetime == null) {
                datetime = encounter.getEncounterDatetime();
            }
            obsGrouper.setObsDatetime(datetime);
            obsGrouper.setLocation(encounter.getLocation());
            obsGrouper.setCreator(encounter.getCreator());

            // set comments if there are any
            StringBuilder comments = new StringBuilder();
            ORU_R01_ORDER_OBSERVATION parent = (ORU_R01_ORDER_OBSERVATION) obr.getParent();
            int totalNTEs = parent.getNTEReps();
            for (int iNTE = 0; iNTE < totalNTEs; iNTE++) {
                for (FT obxComment : parent.getNTE(iNTE).getComment()) {
                    if (comments.length() > 0) {
                        comments.append(" ");
                    }
                    comments.append(obxComment.getValue());
                }
            }
            // only set comments if there are any
            if (StringUtils.hasText(comments.toString())) {
                obsGrouper.setComment(comments.toString());
            }

            // add this obs as another row in the obs table
            encounter.addObs(obsGrouper);
        }

        // loop over the obs and create each object, adding it to the encounter
        int numObs = orderObs.getOBSERVATIONReps();
        HL7Exception errorInHL7Queue = null;
        for (int j = 0; j < numObs; j++) {
            if (log.isDebugEnabled()) {
                log.debug("Processing OBS (" + j + " of " + numObs + ")");
            }

            OBX obx = orderObs.getOBSERVATION(j).getOBX();
            try {
                log.debug("Parsing observation");
                Obs obs = parseObs(encounter, obx, obr, messageControlId);
                if (obs != null) {

                    // if we're backfilling an encounter, don't use
                    // the creator/dateCreated from the encounter
                    if (encounter.getEncounterId() != null) {
                        obs.setCreator(getEnterer(orc));
                        obs.setDateCreated(new Date());
                    }

                    // set the obsGroup on this obs
                    if (obsGrouper != null) {
                        // set the obs to the group.  This assumes the group is already
                        // on the encounter and that when the encounter is saved it will
                        // propagate to the children obs
                        obsGrouper.addGroupMember(obs);
                    } else {
                        // set this obs on the encounter object that we
                        // will be saving later
                        log.debug("Obs is not null. Adding to encounter object");
                        encounter.addObs(obs);
                        log.debug("Done with this obs");
                    }
                }
            } catch (ProposingConceptException proposingException) {
                Concept questionConcept = proposingException.getConcept();
                String value = proposingException.getValueName();
                //if the sender never specified any text for the proposed concept
                if (!StringUtils.isEmpty(value)) {
                    conceptProposals.add(createConceptProposal(encounter, questionConcept, value));
                } else {
                    errorInHL7Queue = new HL7Exception(
                            Context.getMessageSourceService().getMessage("Hl7.proposed.concept.name.empty"),
                            proposingException);
                    break;//stop any further processing of current message
                }

            } catch (HL7Exception e) {
                errorInHL7Queue = e;
            } finally {
                // Handle obs-level exceptions
                if (errorInHL7Queue != null) {
                    throw new HL7Exception(Context.getMessageSourceService().getMessage(
                            "ORUR01.error.improperlyFormattedOBX",
                            new Object[] { PipeParser.encode(obx, new EncodingCharacters('|', "^~\\&")) },
                            null), HL7Exception.DATA_TYPE_ERROR, errorInHL7Queue);
                }
            }
        }

    }

    if (log.isDebugEnabled()) {
        log.debug("Finished creating observations");
        log.debug("Current thread: " + Thread.currentThread());
        log.debug("Creating the encounter object");
    }
    Context.getEncounterService().saveEncounter(encounter);

    // Notify HL7 service that we have created a new encounter, allowing
    // features/modules to trigger on HL7-generated encounters.
    // -This can be removed once we have a obs_group table and all
    // obs can be created in memory as part of the encounter *before* we
    // call EncounterService.createEncounter().  For now, making obs groups
    // requires that one obs be created (in the database) before others can
    // be linked to it, forcing us to save the encounter prematurely."
    //
    // NOTE: The above referenced fix is now done.  This method is
    // deprecated and will be removed in the next release.  All modules
    // should modify their AOP methods to hook around
    // EncounterService.createEncounter(Encounter).
    hl7Service.encounterCreated(encounter);

    // loop over the proposed concepts and save each to the database
    // now that the encounter is saved
    for (ConceptProposal proposal : conceptProposals) {
        Context.getConceptService().saveConceptProposal(proposal);
    }

    return oru;

}

From source file:org.openmrs.module.diagnosiscapturerwanda.util.DiagnosisUtil.java

/**
 * calculate BMI.  Ripped directly out of default openmrs portlet controller
 *///from w ww.  ja  va2s.  com
public static String bmiAsString(Patient p, Visit visit) {

    String bmiAsString = "?";

    if (visit != null) {
        Date[] visitDates = DiagnosisUtil.getStartAndEndOfDay(visit.getStartDatetime());
        Date[] visitDatesStop = DiagnosisUtil.getStartAndEndOfDay(visit.getStopDatetime());

        AdministrationService as = Context.getAdministrationService();
        ConceptService cs = Context.getConceptService();
        List<Obs> patientObs = Context.getObsService().getObservationsByPerson(p);
        Obs latestWeight = null;
        Obs latestHeight = null;

        try {
            String weightString = as.getGlobalProperty("concept.weight");
            ConceptNumeric weightConcept = null;
            if (StringUtils.hasLength(weightString))
                weightConcept = cs
                        .getConceptNumeric(cs.getConcept(Integer.valueOf(weightString)).getConceptId());
            String heightString = as.getGlobalProperty("concept.height");
            ConceptNumeric heightConcept = null;
            if (StringUtils.hasLength(heightString))
                heightConcept = cs
                        .getConceptNumeric(cs.getConcept(Integer.valueOf(heightString)).getConceptId());
            for (Obs obs : patientObs) {
                if (obs.getConcept().equals(weightConcept)) {
                    if ((obs.getObsDatetime().after(visitDates[0])
                            && obs.getObsDatetime().before(visitDatesStop[1]))
                            || obs.getObsDatetime().compareTo(visitDates[0]) == 0
                            || obs.getObsDatetime().compareTo(visitDatesStop[0]) == 0) {
                        latestWeight = obs;
                    }
                } else if (obs.getConcept().equals(heightConcept)) {
                    if (p.getAge(visit.getStartDatetime()) > 15) {
                        if (latestHeight == null
                                || obs.getObsDatetime().compareTo(latestHeight.getObsDatetime()) > 0
                                        && p.getAge(obs.getObsDatetime()) > 15)
                            latestHeight = obs;
                    } else if ((obs.getObsDatetime().after(visitDates[0])
                            && obs.getObsDatetime().before(visitDatesStop[1]))
                            || obs.getObsDatetime().compareTo(visitDates[0]) == 0
                            || obs.getObsDatetime().compareTo(visitDatesStop[0]) == 0) {
                        latestHeight = obs;
                    }
                }
            }
            if (latestWeight != null && latestHeight != null) {
                double weightInKg;
                double heightInM;
                if (weightConcept.getUnits().equals("kg"))
                    weightInKg = latestWeight.getValueNumeric();
                else if (weightConcept.getUnits().equals("lb"))
                    weightInKg = latestWeight.getValueNumeric() * 0.45359237;
                else
                    throw new IllegalArgumentException(
                            "Can't handle units of weight concept: " + weightConcept.getUnits());
                if (heightConcept.getUnits().equals("cm"))
                    heightInM = latestHeight.getValueNumeric() / 100;
                else if (heightConcept.getUnits().equals("m"))
                    heightInM = latestHeight.getValueNumeric();
                else if (heightConcept.getUnits().equals("in"))
                    heightInM = latestHeight.getValueNumeric() * 0.0254;
                else
                    throw new IllegalArgumentException(
                            "Can't handle units of height concept: " + heightConcept.getUnits());
                double bmi = weightInKg / (heightInM * heightInM);
                String temp = "" + bmi;
                bmiAsString = temp.substring(0, temp.indexOf('.') + 2);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return "";
        }
    }
    return bmiAsString;
}

From source file:org.openmrs.module.ModuleFactory.java

/**
 * Execute the given sql diff section for the given module
 * //from  ww  w.  j a  va  2  s .c om
 * @param module the module being executed on
 * @param version the version of this sql diff
 * @param sql the actual sql statements to run (separated by semi colons)
 */
private static void runDiff(Module module, String version, String sql) {
    AdministrationService as = Context.getAdministrationService();

    String key = module.getModuleId() + ".database_version";
    GlobalProperty gp = as.getGlobalPropertyObject(key);

    boolean executeSQL = false;

    // check given version against current version
    if (gp != null && StringUtils.hasLength(gp.getPropertyValue())) {
        String currentDbVersion = gp.getPropertyValue();
        if (log.isDebugEnabled()) {
            log.debug("version:column " + version + ":" + currentDbVersion);
            log.debug("compare: " + ModuleUtil.compareVersion(version, currentDbVersion));
        }
        if (ModuleUtil.compareVersion(version, currentDbVersion) > 0) {
            executeSQL = true;
        }
    } else {
        executeSQL = true;
    }

    // version is greater than the currently installed version. execute this update.
    if (executeSQL) {
        try {
            Context.addProxyPrivilege(PrivilegeConstants.SQL_LEVEL_ACCESS);
            log.debug("Executing sql: " + sql);
            String[] sqlStatements = sql.split(";");
            for (String sqlStatement : sqlStatements) {
                if (sqlStatement.trim().length() > 0) {
                    as.executeSQL(sqlStatement, false);
                }
            }
        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.SQL_LEVEL_ACCESS);
        }

        // save the global property
        try {
            Context.addProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);

            String description = "DO NOT MODIFY.  Current database version number for the "
                    + module.getModuleId() + " module.";

            if (gp == null) {
                log.info("Global property " + key + " was not found. Creating one now.");
                gp = new GlobalProperty(key, version, description);
                as.saveGlobalProperty(gp);
            } else if (!gp.getPropertyValue().equals(version)) {
                log.info("Updating global property " + key + " to version: " + version);
                gp.setDescription(description);
                gp.setPropertyValue(version);
                as.saveGlobalProperty(gp);
            } else {
                log.error("Should not be here. GP property value and sqldiff version should not be equal");
            }

        } finally {
            Context.removeProxyPrivilege(PrivilegeConstants.MANAGE_GLOBAL_PROPERTIES);
        }

    }

}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java

public void generateDataFile(File outFile, String[] ignoreTables) {
    // TODO totally breaks if someone isn't using mysql as the backend
    // TODO get custom location of mysql instead of just relying on path?
    // TODO make this linux compatible
    String[] props = getConnectionProperties();
    String username = props[0];//www  .ja va 2s  . c om
    String password = props[1];
    String database = props[2];
    String host = props[3];
    String port = props[4];
    try {
        if (!outFile.exists())
            outFile.createNewFile();
    } catch (IOException io) {
        log.warn(io.toString());
    }

    List<String> commands = new ArrayList<String>();
    commands.add("mysqldump");
    commands.add("-u" + username);
    commands.add("-p" + password);
    commands.add("-h" + host);
    commands.add("-P" + port);
    commands.add("--hex-blob");
    commands.add("-q");
    commands.add("-e");
    commands.add("--single-transaction");
    commands.add("-r");
    commands.add(outFile.getAbsolutePath());
    commands.add(database);

    // mark the tables to ignore
    for (String table : ignoreTables) {
        table = table.trim();
        if (StringUtils.hasLength(table)) {
            commands.add("--ignore-table");
            commands.add(database + "." + table);
        }
    }

    String output;
    if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM)
        output = execCmd(outFile.getParentFile(), commands.toArray(new String[] {}));
    else
        output = execCmd(null, commands.toArray(new String[] {}));

    if (output != null && output.length() > 0) {
        log.debug("Exec called: " + Arrays.asList(commands));
        log.debug("Output of exec: " + output);
    }

}

From source file:org.openmrs.module.sync.web.controller.ConfigServerFormController.java

@RequestMapping(value = "/module/sync/configServer", method = RequestMethod.POST, params = "action=saveNewChild")
protected String onSaveNewChild(@RequestParam String nickname, @RequestParam String uuid,
        @RequestParam(required = false) String username, @RequestParam(required = false) String password,
        @RequestParam String passwordRetype, @RequestParam(required = false) Boolean shouldEmail,
        @RequestParam String adminEmail, HttpSession httpSession, @ModelAttribute("server") RemoteServer server,
        Errors errors, @RequestParam(required = false) List<String> notSendTo,
        @RequestParam(required = false) List<String> notReceiveFrom) throws Exception {

    if (!Context.isAuthenticated())
        throw new APIAuthenticationException("Not authenticated!");

    //if the user provided a username, then the passwords are required
    if (StringUtils.hasText(username)) {
        if (!StringUtils.hasText(password) || !StringUtils.hasText(passwordRetype)) {
            errors.rejectValue("password", "sync.config.server.error.passwordRequired");
        } else if (!password.equals(passwordRetype))
            errors.rejectValue("password", "error.password.match");
    }/*from w w  w  .  java  2  s. c o m*/

    if (!StringUtils.hasLength(nickname))
        errors.rejectValue("nickname", "sync.config.server.error.nicknameRequired");

    if (errors.hasErrors())
        return "/module/sync/configServerForm";

    log.debug("in onSave for new child");

    MessageSourceService mss = Context.getMessageSourceService();
    SyncService syncService = Context.getService(SyncService.class);

    server.setServerType(RemoteServerType.CHILD);
    server.setNickname(nickname);
    server.setUuid(uuid);

    if (StringUtils.hasText(username)) {
        // create a new user in either A) 1.5.x or B) 1.6+
        User user = null;

        if (Person.class.isAssignableFrom(User.class)) {
            // if we're in a pre-1.6 environment, User extends Person
            user = new User();
            // if 1.6+ the User.setGender method does not exist, so if we 
            // don't do this by reflection we will have a compile-time error
            // (and gender is a required field)
            Method setGenderMethod = User.class.getMethod("setGender", String.class);
            setGenderMethod.invoke(user, SyncConstants.DEFAULT_CHILD_SERVER_USER_GENDER);

            user.setUsername(username);

            PersonName name = new PersonName();
            name.setFamilyName(nickname);
            name.setGivenName(mss.getMessage(SyncConstants.DEFAULT_CHILD_SERVER_USER_NAME));
            user.addName(name);
        } else {
            // create a new user in a 1.6+ environemnt where
            // User does NOT extend Person
            Person person = new Person();
            person.setGender(SyncConstants.DEFAULT_CHILD_SERVER_USER_GENDER);
            person.setBirthdate(new Date());
            PersonName name = new PersonName();
            name.setFamilyName(nickname);
            name.setGivenName(mss.getMessage(SyncConstants.DEFAULT_CHILD_SERVER_USER_NAME));
            person.addName(name);
            Context.getPersonService().savePerson(person);

            user = new User(person);
            user.setUsername(username);
        }

        String defaultRole = Context.getAdministrationService().getGlobalProperty("sync.default_role");
        if (defaultRole != null) {
            String[] roles = defaultRole.split(",");
            for (String role : roles) {
                Role r = Context.getUserService().getRole(role.trim());
                if (r != null)
                    user.addRole(r);
            }
        }

        // create in database
        try {
            Context.getUserService().saveUser(user, password);
            server.setChildUsername(user.getUsername());
        } catch (Exception e) {
            log.error("Unable to create new user to associate with child server", e);

            //Am using the exception message because it is already localized. 
            //You can look at OpenmrsUtil.validatePassword()
            errors.rejectValue("username", e.getMessage());

            return "/module/sync/configServerForm";
        }
    }

    server.setAddress("N/A");
    server.setPassword("N/A");
    server.setUsername("N/A");

    saveOrUpdateServerClasses(server, notSendTo, notReceiveFrom);

    server = syncService.saveRemoteServer(server);

    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "sync.config.server.saved");

    if (server.getServerId() != null)
        return "redirect:/module/sync/configServer.form?serverId=" + server.getServerId();
    else
        return "redirect:/module/sync/config.list";
}

From source file:org.openmrs.module.sync.web.controller.ConfigServerFormController.java

@RequestMapping(value = "/module/sync/configServer", method = RequestMethod.POST, params = "action=editChild")
protected String onSaveCurrentChild(@RequestParam String nickname, @RequestParam String uuid,
        HttpSession httpSession, @ModelAttribute("server") RemoteServer server, Errors errors,
        @RequestParam(required = false) List<String> notSendTo,
        @RequestParam(required = false) List<String> notReceiveFrom) throws Exception {

    if (!Context.isAuthenticated())
        throw new APIAuthenticationException("Not authenticated!");

    if (!StringUtils.hasLength(nickname))
        errors.rejectValue("nickname", "sync.config.server.error.nicknameRequired");

    if (errors.hasErrors())
        return "/module/sync/configServerForm";

    server.setNickname(nickname);/*  w ww.  j  a  v  a  2  s  . c o  m*/
    server.setUuid(uuid);

    saveOrUpdateServerClasses(server, notSendTo, notReceiveFrom);

    server = Context.getService(SyncService.class).saveRemoteServer(server);

    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "sync.config.server.saved");

    if (server.getServerId() != null)
        return "redirect:/module/sync/configServer.form?serverId=" + server.getServerId();
    else
        return "redirect:/module/sync/config.list";

}

From source file:org.openmrs.module.sync.web.controller.ConfigServerFormController.java

@RequestMapping(value = "/module/sync/configServer", method = RequestMethod.POST, params = "action=saveParent")
protected String onSaveParent(@RequestParam String nickname, @RequestParam String address,
        @RequestParam String username, @RequestParam String password,
        @RequestParam(required = false) Boolean started, @RequestParam(required = false) Integer repeatInterval,
        HttpSession httpSession, @ModelAttribute("server") RemoteServer server, Errors errors,
        @RequestParam(required = false) List<String> notSendTo,
        @RequestParam(required = false) List<String> notReceiveFrom) throws Exception {

    if (!Context.isAuthenticated())
        throw new APIAuthenticationException("Not authenticated!");

    if (!StringUtils.hasLength(nickname))
        errors.rejectValue("nickname", "sync.config.server.error.nicknameRequired");

    if (!StringUtils.hasLength(address))
        errors.rejectValue("address", "sync.config.server.error.addressRequired");

    if (started == null) {
        started = false; // if they didn't check the box, the value is false
        repeatInterval = 0;//from  w  w  w . ja  va  2 s  .c  om
    }

    if (started && repeatInterval < 1)
        errors.rejectValue("address", "sync.config.server.error.invalidRepeat");

    if (errors.hasErrors())
        return "/module/sync/configServerForm";

    // interval needs to be in seconds, but we asked the user for minutes. multiply by 60 to convert to minutes
    repeatInterval = repeatInterval * 60;

    server.setServerType(RemoteServerType.PARENT);
    server.setNickname(nickname);

    // just in case - we want to make sure there is ONLY ever 1 parent
    if (server.getServerType().equals(RemoteServerType.PARENT)) {
        RemoteServer parent = Context.getService(SyncService.class).getParentServer();
        if (parent != null && parent.getServerId() != server.getServerId()) {
            throw new APIException(
                    "Oh no! There is another server already stored in the database as the parent: server id : "
                            + parent.getServerId());
        }
    }

    server.setAddress(address);
    server.setPassword(password);
    server.setUsername(username);

    saveOrUpdateServerClasses(server, notSendTo, notReceiveFrom);

    server = Context.getService(SyncService.class).saveRemoteServer(server);

    saveOrUpdateTask(server, started, repeatInterval);

    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "sync.config.parent.saved");

    if (server.getServerId() != null)
        return "redirect:/module/sync/configServer.form?serverId=" + server.getServerId();
    else
        return "redirect:/module/sync/config.list";
}

From source file:org.openmrs.scheduler.SchedulerServiceTest.java

/**
 * Helper method to append the given text to the "output" static variable map
 * <br/>//from   w ww  .j  av  a 2s.  co m
 * Map will contain string like "text, text1, text2"
 * 
 * @param outputKey the key for the "output" map
 * @param the text to append to the value in the output map with the given key
 */
public synchronized static void appendOutput(String outputKey, String appendText) {
    if (StringUtils.hasLength(output.get(outputKey)))
        output.put(outputKey, output.get(outputKey) + ", " + appendText);
    else
        output.put(outputKey, appendText);
}

From source file:org.openmrs.util.LocaleUtility.java

/**
 * Gets the default locale specified as a global property.
 *
 * @return default locale object.//  w w w.j  a  v  a 2  s .c  o  m
 * @since 1.5
 * @should not return null if global property does not exist
 * @should not fail with empty global property value
 * @should not fail with bogus global property value
 * @should return locale object for global property
 * @should not cache locale when session is not open
 */
public static Locale getDefaultLocale() {
    if (defaultLocaleCache == null) {
        if (Context.isSessionOpen()) {
            try {
                String locale = Context.getAdministrationService()
                        .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE);

                if (StringUtils.hasLength(locale)) {
                    try {
                        defaultLocaleCache = fromSpecification(locale);
                    } catch (Exception t) {
                        log.warn("Unable to parse default locale global property value: " + locale, t);
                    }
                }
            } catch (Exception e) {
                // swallow most of the stack trace for most users
                log.warn("Unable to get locale global property value. " + e.getMessage());
                log.trace("Unable to get locale global property value", e);
            }

            // if we weren't able to load the locale from the global property,
            // use the default one
            if (defaultLocaleCache == null) {
                defaultLocaleCache = fromSpecification(
                        OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE);
            }
        } else {
            // if session is not open, return the default locale without caching
            return fromSpecification(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE);
        }

    }

    return defaultLocaleCache;
}