Example usage for org.apache.commons.lang BooleanUtils toBoolean

List of usage examples for org.apache.commons.lang BooleanUtils toBoolean

Introduction

In this page you can find the example usage for org.apache.commons.lang BooleanUtils toBoolean.

Prototype

public static boolean toBoolean(String str) 

Source Link

Document

Converts a String to a boolean (optimised for performance).

'true', 'on' or 'yes' (case insensitive) will return true.

Usage

From source file:org.lexevs.dao.database.operation.transitivity.DefaultTransitivityBuilder.java

protected boolean isTransitive(String codingSchemeUri, String version, String code, String namespace) {
    AssociationEntity associationEntity = this.databaseServiceManager.getEntityService()
            .getAssociationEntity(codingSchemeUri, version, code, namespace);
    return (associationEntity != null && BooleanUtils.toBoolean(associationEntity.getIsTransitive()));
}

From source file:org.lexevs.dao.database.service.Author.EntityRevisionTest.java

@Test
public void testDependentAndModifyEntity() throws Exception {
    Entity julyEntity = entityService.resolveEntityByRevision("urn:oid:22.22.0.2", "2.0", "midas002",
            "Automobiles", "testRelease2010July_testEntity");

    assertNotNull(julyEntity);/* ww w.j a  v  a2 s  . c  o  m*/

    assertFalse(BooleanUtils.toBoolean(julyEntity.getIsAnonymous()));
    assertFalse(BooleanUtils.toBoolean(julyEntity.getIsDefined()));
    assertEquals(julyEntity.getDefinitionCount(), 2);

    Entity septEntity = entityService.resolveEntityByRevision("urn:oid:22.22.0.2", "2.0", "midas002",
            "Automobiles", "testRelease2010Sep_testEntity");

    assertNotNull(septEntity);

    assertTrue(septEntity.getIsAnonymous());
    assertTrue(septEntity.getIsDefined());

    assertEquals(septEntity.getDefinitionCount(), 3);
}

From source file:org.lexevs.system.constants.SystemVariables.java

private Properties loadPropsFile(Logger logger) throws Exception {
    try {/*from w  ww  . j  a v  a2 s .  c  o  m*/
        PropertiesUtility.systemVariable = LG_CONFIG_FILE_SYSTEM_VARIABLE;
        String location = PropertiesUtility.locatePropFile(
                "config" + System.getProperty("file.separator") + CONFIG_FILE_NAME, this.getClass().getName(),
                logger);

        //If in in-memory (testing) mode, we can allow this, as config will be handled elsewhere.
        //If not in in-memory testing mode, throw an error if the config fiel isn't found.
        boolean inMemory = BooleanUtils.toBoolean(System.getProperty(ALL_IN_MEMORY_SYSTEM_VARIABLE));

        if (StringUtils.isBlank(location) && !inMemory) {
            throw new InitializationException("\n============================================"
                    + "\nError finding the LexBIG Configuration File."
                    + "\n============================================"
                    + "\nThe LexGrid system attempts to automatically locate this file in one of two ways:"
                    + "\n" + "\nOPTION 1 - AutoSearch"
                    + "\nIt determines the folder that the LexGrid classes are located (either in"
                    + "\na jar file, or a folder containing class files).  For this example, lets assume"
                    + "\nthat the jar file containing LexGrid was found at 'C:\\LexGrid\\LexBIG\\lib\\lbRuntime.jar'"
                    + "\nThen the path it starts with will be 'C:\\LexGrid\\LexBIG\\lib\\'.  Lets call this"
                    + "\nlocation 'A'.  Starting from location A, it checks for the following sub-path:"
                    + "\n'resources\\config\\config.props'.  Lets call this path 'B'.  If a file exists"
                    + "\n'A\\B', the search is over.  If this file is not found - it goes up one directory"
                    + "\nfrom A, and checks for B again.  So, now it is checking \"A\\..\\B\". - which is"
                    + "\n'C:\\LexGrid\\LexBIG\\resources\\config\\config.props'.  This process continues until"
                    + "\nit finds the file, reaches the root of the file system, or it has gone up 10 levels."
                    + "\nAt that point, it quits and and the startup fails." + "\n"
                    + "\nOPTION 2 - System Variable"
                    + "\nYou may skip the auto search by setting the System Config variable 'LG_CONFIG_FILE'"
                    + "\nto the full absolute path of the config.props file."
                    + "\nExample - if you were starting from the command line, you would add this parameter to"
                    + "\nthe java command to set the 'System Property'"
                    + "\n-DLG_CONFIG_FILE=\"C:\\LexGrid\\LexBIG\\resources\\config\\config.props\"");
        }

        Properties props = new Properties();

        logger.debug("Reading properties from " + location);
        props.load(new FileInputStream(new File(location)));
        props.put("CONFIG_FILE_LOCATION", location);
        return props;
    } catch (Exception e) {
        logger.fatal("There was a problem finding or reading the properties file", e);
        throw e;
    }
}

From source file:org.lexevs.system.constants.SystemVariables.java

/**
 * Inits the.//from w  ww.  jav a 2 s .co m
 * 
 * @param logger the logger
 * @param props the props
 * 
 * @throws Exception the exception
 */
private void init(Logger logger, Properties props) throws Exception {
    // Read in the config file
    try {
        configFileLocation_ = props.getProperty("CONFIG_FILE_LOCATION");
        sqlServers_ = new Hashtable<String, SQLConnectionInfo>();
        indexLocations_ = new HashSet<String>();

        logger.debug(
                "Reading registry, index location and db configuration information from the properties file");
        String relPathStart = System.getProperty("LG_BASE_PATH");
        if (relPathStart != null && relPathStart.length() > 0) {
            logger.debug("Relative Path root read from system variable '" + relPathStart + "'");
            relativePathStart_ = relPathStart;
            if (!isPathValid(relativePathStart_)) {
                logger.error("You provided an invalid relative path root as a system variable.  Ignoring.");
                relativePathStart_ = null;
            }
        }
        if (relativePathStart_ == null) {
            relPathStart = props.getProperty("LG_BASE_PATH");
            if (relPathStart != null && relPathStart.length() > 0) {
                logger.debug("Relative Path root read from config file '" + relPathStart + "'");
                relativePathStart_ = relPathStart;
                if (!isPathValid(relativePathStart_)) {
                    logger.error("You provided an invalid relative path root in the config file.  Ignoring.");
                    relativePathStart_ = null;
                }
            }
            if (relativePathStart_ == null) {
                // default to the location of the config file.
                relativePathStart_ = props.getProperty("CONFIG_FILE_LOCATION");
                logger.debug("Relative Path root defaulted to " + CONFIG_FILE_NAME + " location '"
                        + relativePathStart_ + "'");
            }
        }
        String tempJarFileLocation = getProperty(props, "JAR_FILE_LOCATION");
        StringTokenizer tokenizer = new StringTokenizer(tempJarFileLocation, ";");
        jarFileLocations_ = new String[tokenizer.countTokens()];
        int i = 0;
        while (tokenizer.hasMoreElements()) {
            jarFileLocations_[i++] = processRelativePath(tokenizer.nextToken());
        }
        autoLoadRegistryPath_ = processRelativePath(getProperty(props, "REGISTRY_FILE"));
        autoLoadIndexLocation_ = processRelativePath(getProperty(props, "INDEX_LOCATION"));
        autoLoadDBURL_ = getProperty(props, "DB_URL");

        if (getNullableProperty(props, "MAX_IN_VS_CACHE") == null) {
            max_value_set_cache = 500;
        } else {
            max_value_set_cache = getStringPropertyAsInt(props, "MAX_IN_VS_CACHE");
        }
        String tempSingleDb = getNullableProperty(props, "SINGLE_DB_MODE");

        autoLoadSingleDBMode = getNullableBoolean(tempSingleDb, true);

        String tempOverrideSingleDb = getNullableProperty(props, OVERRIDE_SINGLE_DB_PROP);

        overrideSingleDbMode = getNullableBoolean(tempOverrideSingleDb, false);

        singleTableMode = getNullableBoolean(getNullableProperty(props, SINGLE_TABLE_MODE_PROP),
                SINGLE_TABLE_MODE_DEFAULT);

        autoLoadDBPrefix_ = getProperty(props, "DB_PREFIX");

        // this one can be left out
        autoLoadDBParameters_ = props.getProperty("DB_PARAM");
        if (autoLoadDBParameters_ == null) {
            autoLoadDBParameters_ = "";
        } else {
            autoLoadDBURL_ = getAutoLoadDBURL() + getAutoLoadDBParameters();
        }
        autoLoadDBDriver_ = getProperty(props, "DB_DRIVER");
        autoLoadDBUsername_ = getProperty(props, "DB_USER");
        autoLoadDBPassword_ = getProperty(props, "DB_PASSWORD");

        //           graphdbUser = getProperty(props, "GRAPH_DB_USER");
        //           graphdbpwd = getProperty(props, "GRAPH_DB_PWD");
        //            graphdbUrl = getProperty(props, "GRAPH_DB_PATH");

        mysql_collation = getNullableProperty(props, "MYSQL_COLLATION", DEFAULT_MYSQL_COLLATION);

        String pwdEncrypted = getNullableProperty(props, "DB_PASSWORD_ENCRYPTED");
        if (pwdEncrypted != null && pwdEncrypted.equalsIgnoreCase("true"))
            autoLoadDBPassword_ = CryptoUtility.decrypt(autoLoadDBPassword_);

        File temp = new File(autoLoadIndexLocation_);
        if (!temp.exists()) {
            temp.mkdir();
        }
        indexLocations_.add(autoLoadIndexLocation_);

        logger.debug("Reading the Preconfigured SQL Server configurations from the properties file");
        loadSqlServerLocations(props);

        logger.debug("Reading the Prebuilt Lucene index configurations from the properties file");
        loadIndexLocations(props);

        logger.debug("Reading additional variables from the properties file");

        logLocation_ = processRelativePath(getProperty(props, "LOG_FILE_LOCATION"));

        isNormEnabled_ = false;
        // This has been disabled due to deployment complexity. Can be
        // re-enabled if necessary.
        // isNormEnabled_ = new
        // Boolean(props.getProperty("NORMALIZED_QUERIES_ENABLED")).booleanValue();
        // if (isNormEnabled_)
        // {
        // normConfigFile_ =
        // props.getProperty("LVG_NORM_CONFIG_FILE_ABSOLUTE");
        // }

        realDebugEnableValue_ = new Boolean(getProperty(props, "DEBUG_ENABLED")).booleanValue();
        if (!isDebugOverridden_) {
            isDebugEnabled_ = realDebugEnableValue_;
        }
        logger.info("Logging debug messages" + (isDebugEnabled_ == true ? " left on." : " turned off."));
        logger.setDebugEnabled(isDebugEnabled_);

        isAPILoggingEnabled = new Boolean(getProperty(props, "API_LOG_ENABLED")).booleanValue();
        logger.setAPILoggingEnabled(isAPILoggingEnabled);

        isMigrateOnStartupEnabled = getNullableBoolean("MOVE_REGISTRY_TO_DATABASE", false);
        logger.setAPILoggingEnabled(isMigrateOnStartupEnabled);

        String val = props.getProperty("SQL_LOG_ENABLED");
        if (val != null) {
            isSQLLoggingEnabled = new Boolean(val).booleanValue();
        }
        logger.info("Logging sql messages" + (isSQLLoggingEnabled == true ? " left on." : " turned off."));

        try {
            maxConnectionsPerDB_ = Integer.parseInt(getProperty(props, "MAX_CONNECTIONS_PER_DB"));
        } catch (NumberFormatException e) {
            logger.error("INVALID VALUE in config file for maxConnectionsPerDB - defaulting to 8");
            maxConnectionsPerDB_ = 8;
        }

        try {
            iteratorIdleTime_ = Integer.parseInt(getProperty(props, "ITERATOR_IDLE_TIME"));
        } catch (NumberFormatException e) {
            logger.error("INVALID VALUE in config file for ITERATOR_IDLE_TIME - defaulting to 5");
            iteratorIdleTime_ = 5;
        }

        try {
            maxResultSize_ = Integer.parseInt(getProperty(props, "MAX_RESULT_SIZE"));
        } catch (NumberFormatException e) {
            logger.error("INVALID VALUE in config file for MAX_RESULT_SIZE - defaulting to 1000");
            maxResultSize_ = 1000;
        }

        try {
            cacheSize_ = Integer.parseInt(getProperty(props, "CACHE_SIZE"));
        } catch (NumberFormatException e) {
            logger.error("INVALID VALUE in config file for CACHE_SIZE - defaulting to 200");
            cacheSize_ = 200;
        }

        try {
            maxResultSize_ = Integer.parseInt(getProperty(props, "MAX_RESULT_SIZE"));
        } catch (NumberFormatException e) {
            logger.error("INVALID VALUE in config file for MAX_RESULT_SIZE - defaulting to 1000");
            maxResultSize_ = 1000;
        }

        String luceneMaxClauses = getNullableProperty(props, LUCENE_MAX_CLAUSE_COUNT_PROP);
        if (luceneMaxClauses != null) {
            try {
                this.luceneMaxClauseCount = Integer.parseInt(luceneMaxClauses);
            } catch (NumberFormatException e) {
                logger.error("INVALID VALUE in config file for " + LUCENE_MAX_CLAUSE_COUNT_PROP);
            }
        }

        this.isSingleIndex = BooleanUtils
                .toBoolean(getNullableProperty(props, LUCENE_SINGLE_INDEX_PROP, LUCENE_SINGLE_INDEX_DEFAULT));

        this.primaryKeyStrategy = getNullableProperty(props, PRIMARY_KEY_STRATEGY_PROP,
                DEFAULT_PRIMARY_KEY_STRATEGY);

        this.currentPersistenceScheme = getNullableProperty(props, CURRENT_PERSISTENCE_SCHEME_PROP,
                DEFAULT_PERSISTENCE_SCHEME);

        emailErrors_ = new Boolean(getNullableProperty(props, "EMAIL_ERRORS", "false"));
        if (emailErrors_) {
            SMTPServer_ = getProperty(props, "SMTP_SERVER");
            emailTo_ = getProperty(props, "EMAIL_TO");
        }

        try {
            logChange_ = getProperty(props, "LOG_CHANGE");

            if (!logChange_.equals("daily") && !logChange_.equals("weekly") && !logChange_.equals("monthly")) {
                Integer.parseInt(logChange_);
            }
        } catch (NumberFormatException e) {
            logger.error("INVALID VALUE in config file for LOG_CHANGE - defaulting to 5");
            logChange_ = "5";
        }

        try {
            eraseLogsAfter_ = Integer.parseInt(getProperty(props, "ERASE_LOGS_AFTER"));
        } catch (NumberFormatException e) {
            logger.error("INVALID VALUE in config file for ERASE_LOGS_AFTER - defaulting to 5");
            eraseLogsAfter_ = 5;
        }

        if (autoLoadSingleDBMode)
            historyDBSchema_ = props.getProperty("HISTORY_DB_SCHEMA");

        logger.finishLogConfig(this);

    } catch (Exception e) {
        logger.fatal("There was a problem reading the properties", e);
        throw e;
    }
}

From source file:org.LexGrid.LexBIG.gui.edit.PropertyEditDialog.java

@Override
protected void initComponents(Composite composite) {
    composite.setLayout(new GridLayout(2, false));

    GridData gridData = new GridData(GridData.FILL_BOTH);
    composite.setLayoutData(gridData);//from  www .j a v a 2s. com

    super.addTextBox(PROPERTY_TEXT_KEY, composite, "Property Text: ", property.getValue().getContent());

    super.addTextBox(PROPERTY_FORMAT_KEY, composite, "Property Format: ", property.getValue().getDataType());

    Label propertyTypeLabel = new Label(composite, SWT.NONE);
    propertyTypeLabel.setText("Property Type: ");
    propertyType = super.comboBoxFactory(composite);
    propertyType.setTextLimit(100);

    int index = 0;
    for (PropertyType type : DaoUtility.propertyTypeToStringMap.keySet()) {
        propertyType.add(type.toString(), index);
        propertyIndexMap.put(type, index);
        index++;
    }

    PropertyType propType = DaoUtility.propertyStringToTypeMap.get(this.property.getPropertyType());
    propertyType.select(propertyIndexMap.get(propType));

    propertyType.addSelectionListener(new SelectionListener() {

        public void widgetDefaultSelected(SelectionEvent arg0) {
            //
        }

        public void widgetSelected(SelectionEvent arg0) {
            PropertyType selection = DaoUtility.propertyStringToTypeMap
                    .get(propertyType.getItem(propertyType.getSelectionIndex()));

            if (selection.equals(PropertyType.PRESENTATION)) {
                getCheckBox(IS_PREFERRED_KEY).setEnabled(true);
                getCheckBox(MATCH_IF_NO_CONTEXT_KEY).setEnabled(true);
            } else {
                getCheckBox(IS_PREFERRED_KEY).setEnabled(false);
                getCheckBox(MATCH_IF_NO_CONTEXT_KEY).setEnabled(false);
            }
        }
    });

    super.addTextBox(PROPERTY_NAME_KEY, composite, "Property Name: ", property.getPropertyName());

    boolean isPresentation = (property instanceof Presentation);

    Button isPrefTextBox = super.addCheckBox(IS_PREFERRED_KEY, composite, "Is Preferred: ", false);
    Button matchIfNoContextBox = super.addCheckBox(MATCH_IF_NO_CONTEXT_KEY, composite, "Match If No Context: ",
            false);

    if (isPresentation) {
        Presentation pres = (Presentation) property;
        isPrefTextBox.setSelection(BooleanUtils.toBoolean(pres.getIsPreferred()));
        matchIfNoContextBox.setSelection(BooleanUtils.toBoolean(pres.getMatchIfNoContext()));

    } else {
        isPrefTextBox.setEnabled(false);
        matchIfNoContextBox.setEnabled(false);
    }
}

From source file:org.LexGrid.LexBIG.Impl.loaders.postprocessor.HierarchyCheckingPostProcessor.java

/**
 * Check the AssociationEntity defined by the SupportedHierarchy(s).
 * //from  ww w  .  j  a va  2 s.c o m
 * @param uri the uri
 * @param version the version
 * 
 * @throws LBException the LB exception
 */
public void checkTransitivity(String uri, String version) throws LBException {
    LexBIGService lbs = LexBIGServiceImpl.defaultInstance();

    CodingSchemeService codingSchemeService = LexEvsServiceLocator.getInstance().getDatabaseServiceManager()
            .getCodingSchemeService();
    EntityService entityService = LexEvsServiceLocator.getInstance().getDatabaseServiceManager()
            .getEntityService();

    if (ServiceUtility.isSupplement(uri, version)) {
        LoggerFactory.getLogger().info("Skipping Coding Scheme Supplements.");
        return;
    }

    MappingExtension me = (MappingExtension) lbs.getGenericExtension("MappingExtension");
    if (me.isMappingCodingScheme(uri, Constructors.createCodingSchemeVersionOrTagFromVersion(version))) {
        LoggerFactory.getLogger().info("Skipping Mapping Schemes.");
        return;
    }

    CodingScheme codingScheme = codingSchemeService.getCodingSchemeByUriAndVersion(uri, version);

    for (SupportedHierarchy sh : codingScheme.getMappings().getSupportedHierarchy()) {
        String[] associationNames = sh.getAssociationNames();

        for (String associationName : associationNames) {

            LoggerFactory.getLogger()
                    .info("Checking if Transitive AssociationEntity exists: " + associationName);

            String entityCode = associationName;
            String entityNamespace = codingScheme.getCodingSchemeName();

            for (SupportedAssociation sa : codingScheme.getMappings().getSupportedAssociation()) {
                if (sa.getLocalId().equals(associationName)) {
                    if (StringUtils.isNotBlank(sa.getEntityCode())) {
                        entityCode = sa.getEntityCode();
                    }
                    if (StringUtils.isNotBlank(sa.getEntityCodeNamespace())) {
                        entityNamespace = sa.getEntityCodeNamespace();
                    }

                    if (StringUtils.isNotBlank(sa.getCodingScheme())) {
                        if (!sa.getCodingScheme().equals(codingScheme.getCodingSchemeName())) {
                            LoggerFactory.getLogger().info(
                                    "WARNING: AssociationEntity defined elsewhere... will locally if necessary.");
                        }
                    }
                }
            }

            AssociationEntity foundAssociationEntity = entityService.getAssociationEntity(uri, version,
                    entityCode, entityNamespace);

            if (foundAssociationEntity == null) {
                LoggerFactory.getLogger().info(" * Auto Adding AssociationEntity Code: " + entityCode
                        + " Namespace: " + entityNamespace);

                AssociationEntity ae = EntityFactory.createAssociation();
                ae.setEntityCode(entityCode);
                ae.setEntityCodeNamespace(entityNamespace);
                ae.setIsActive(true);
                ae.setIsAnonymous(true);
                ae.setIsNavigable(true);
                ae.setIsTransitive(true);

                entityService.insertEntity(uri, version, ae);
            } else {
                if (!BooleanUtils.toBoolean(foundAssociationEntity.getIsTransitive())) {
                    LoggerFactory.getLogger()
                            .info(" * AssociationEntity found, but is not set as Trasitive. Setting now...");

                    foundAssociationEntity.setIsTransitive(true);

                    entityService.updateEntity(uri, version, foundAssociationEntity);
                }
            }
        }
    }
}

From source file:org.LexGrid.LexBIG.Impl.testUtility.ServiceHolder.java

private ServiceHolder(boolean multiConfig) {

    try {/*ww  w . j a  v  a  2  s.  c  o  m*/
        if (multiConfig) {
            singleConfigMode_ = false;
            testConfigFolder_ = new File(System.getProperty("java.io.tmpdir")
                    + System.getProperty("file.separator") + "LexBIGTest-" + UUID.randomUUID().toString());

            // get rid of whatever is there.
            deleteFolder(testConfigFolder_);

            testConfigFolder_.mkdir();

            serverConfigs = TestServerConfigReader.getServerConfigs();

            configs_ = new Properties[serverConfigs.size()];

            for (int i = 0; i < serverConfigs.size(); i++) {
                configs_[i] = createPropertiesObject(serverConfigs.get(i), i, testConfigFolder_);
            }

            if (configs_.length > 0) {
                // clear the log files from the last run.
                File temp = new File(configs_[0].getProperty("LOG_FILE_LOCATION"), "LexBIG_full_log.txt");
                temp.delete();
                temp = new File(configs_[0].getProperty("LOG_FILE_LOCATION"), "LexBIG_load_log.txt");
                temp.delete();
            }
        } else {
            singleConfigMode_ = true;

            boolean inMemory = BooleanUtils
                    .toBoolean(System.getProperty(SystemVariables.ALL_IN_MEMORY_SYSTEM_VARIABLE));

            if (inMemory) {
                BaseInMemoryLexEvsTest.initInMemory();
            }

            if (StringUtils.isNotBlank(System.getProperty(LexBIGServiceTestFactory.LBS_TEST_FACTORY_ENV))) {
                lbsi_ = ((LexBIGServiceTestFactory) Class
                        .forName(System.getProperty(LexBIGServiceTestFactory.LBS_TEST_FACTORY_ENV))
                        .newInstance()).getLbs();
            } else {
                lbsi_ = LexBIGServiceImpl.defaultInstance();
            }
        }

    } catch (Exception e) {
        System.err.println("Problem reading Test config file");
        e.printStackTrace();
        System.exit(-1);
    }

}

From source file:org.lexgrid.valuesets.impl.LexEVSPickListDefinitionServicesImpl.java

private ResolvedPickListEntryList internalResolvePickListForTerm(String valueSetDefURI, boolean sortByText,
        AbsoluteCodingSchemeVersionReferenceList csVersionList, String versionTag) throws LBException {

    ResolvedPickListEntryList plList = new ResolvedPickListEntryList();
    LexEVSValueSetDefinitionServices vds = new LexEVSValueSetDefinitionServicesImpl();

    ResolvedValueSetDefinition rvdDef;/*  w ww .  j  a v a2  s .c o  m*/

    SortOptionList sortCriteria = null;
    if (BooleanUtils.isTrue(sortByText))
        sortCriteria = Constructors.createSortOptionList(new String[] { "entityDescription" });

    try {
        rvdDef = vds.resolveValueSetDefinition(new URI(valueSetDefURI), null, csVersionList, versionTag,
                sortCriteria);
    } catch (URISyntaxException e) {
        throw new LBException("Problem with ValueSet URI", e);
    }

    ResolvedConceptReferencesIterator rcrItr = rvdDef.getResolvedConceptReferenceIterator();

    while (rcrItr.hasNext()) {
        ResolvedConceptReference rcr = rcrItr.next();
        ResolvedPickListEntry rpl = new ResolvedPickListEntry();
        rpl.setEntityCode(rcr.getCode());
        rpl.setEntityCodeNamespace(rcr.getCodeNamespace());
        Entity entity = rcr.getEntity();
        if (entity != null) {
            Presentation[] presentations = entity.getPresentation();
            for (Presentation pres : presentations) {
                if (BooleanUtils.toBoolean(pres.isIsPreferred())) {
                    rpl.setPickText(pres.getValue().getContent());
                    rpl.setPropertyId(pres.getPropertyId());
                    plList.addResolvedPickListEntry(rpl);
                }
            }
        }
    }

    return plList;
}

From source file:org.lilyproject.rest.RecordTypeByIdResource.java

@PUT
@Produces("application/json")
@Consumes("application/json")
public Response put(@PathParam("id") String id, RecordType recordType, @Context UriInfo uriInfo) {
    SchemaId schemaId = idGenerator.getSchemaId(id);

    if (recordType.getId() != null && !recordType.getId().equals(schemaId)) {
        throw new ResourceException("ID in submitted record type does not match the id in URI.",
                BAD_REQUEST.getStatusCode());
    }/*from   w  w  w .ja v  a2s .  c om*/
    recordType.setId(schemaId);

    boolean refreshSubtypes = BooleanUtils.toBoolean(uriInfo.getQueryParameters().getFirst("refreshSubtypes"));

    ImportResult<RecordType> result;
    try {
        result = RecordTypeImport.importRecordType(recordType, ImportMode.UPDATE, IdentificationMode.ID, null,
                refreshSubtypes, typeManager);
    } catch (Exception e) {
        throw new ResourceException("Error creating or updating record type with id " + id, e,
                INTERNAL_SERVER_ERROR.getStatusCode());
    }

    recordType = result.getEntity();
    Response response;

    ImportResultType resultType = result.getResultType();
    switch (resultType) {
    case UPDATED:
    case UP_TO_DATE:
        response = Response.ok(Entity.create(recordType, uriInfo)).build();
        break;
    case CANNOT_UPDATE_DOES_NOT_EXIST:
        throw new ResourceException("Record type not found: " + id, NOT_FOUND.getStatusCode());
    default:
        throw new RuntimeException("Unexpected import result type: " + resultType);
    }

    return response;
}

From source file:org.lilyproject.rest.RecordTypeResource.java

@PUT
@Produces("application/json")
@Consumes("application/json")
public Response put(@PathParam("name") String name, RecordType recordType, @Context UriInfo uriInfo) {
    // Since the name can be updated, in this case we allow that the name in the submitted record type
    // is different from the name in the URI.
    QName qname = ResourceClassUtil.parseQName(name, uriInfo.getQueryParameters());

    boolean refreshSubtypes = BooleanUtils.toBoolean(uriInfo.getQueryParameters().getFirst("refreshSubtypes"));

    ImportResult<RecordType> result;
    try {// w  ww.  j av  a 2s . c om
        result = RecordTypeImport.importRecordType(recordType, ImportMode.CREATE_OR_UPDATE,
                IdentificationMode.NAME, qname, refreshSubtypes, typeManager);
    } catch (Exception e) {
        throw new ResourceException("Error creating or updating record type named " + qname, e,
                INTERNAL_SERVER_ERROR.getStatusCode());
    }

    recordType = result.getEntity();
    Response response;

    ImportResultType resultType = result.getResultType();
    switch (resultType) {
    case CREATED:
        URI uri = uriInfo.getBaseUriBuilder().path(RecordTypeResource.class)
                .queryParam("ns.n", recordType.getName().getNamespace())
                .build("n$" + recordType.getName().getName());
        response = Response.created(uri).entity(Entity.create(recordType, uriInfo)).build();
        break;
    case UPDATED:
    case UP_TO_DATE:
        if (!recordType.getName().equals(qname)) {
            // Reply with "301 Moved Permanently": see explanation in FieldTypeResource
            uri = uriInfo.getBaseUriBuilder().path(RecordTypeResource.class)
                    .queryParam("ns.n", recordType.getName().getNamespace())
                    .build("n$" + recordType.getName().getName());

            return Response.status(Response.Status.MOVED_PERMANENTLY).header("Location", uri.toString())
                    .entity(Entity.create(recordType, uriInfo)).build();
        } else {
            response = Response.ok(Entity.create(recordType, uriInfo)).build();
        }
        break;
    default:
        throw new RuntimeException("Unexpected import result type: " + resultType);
    }

    return response;
}