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

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

Introduction

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

Prototype

public static String substringBefore(String str, String separator) 

Source Link

Document

Gets the substring before the first occurrence of a separator.

Usage

From source file:com.qualogy.qafe.gwt.server.event.assembler.AbstractEventRenderer.java

private void fillBuiltInComponentGVO(BuiltInComponentGVO builtInComponentGVO, String string) {
    String componentIdInComponentData = StringUtils.substringBefore(string, "[");
    String componentAttributesInComponentData = StringUtils.substringBetween(string, "[", "]");
    String[] componentAttributes = StringUtils.split(componentAttributesInComponentData, ",");
    List<String> attributes = new ArrayList<String>();
    for (int k = 0; componentAttributes != null && k < componentAttributes.length; k++) {
        attributes.add(componentAttributes[k]);
    }/*  ww  w .  ja v a 2 s. c  o  m*/
    builtInComponentGVO.setAttributes(attributes);
    builtInComponentGVO.setComponentId(componentIdInComponentData);
}

From source file:com.cloudera.hive.udf.functions.ParseKeyValueTuple.java

/**
 * Processes the input string into a KeyValue Map utilizing the fieldDelimiter and keyValSeparator.</br>
 * Only considers valid pairs(has keyValSeparator) with non-empty/null keys that are in keyNames.
 * <p>/*from   w w w .j a v  a2 s . co m*/
 * Note: The key is the string before the first occurrence of keyValSeparator and the value is everything after.</br>
 * Note: If a key occurs twice the last value seen will be represented.
 *
 * @param inputString     the string to be processed
 * @param fieldDelimiter  separator between KeyValue pairs
 * @param keyValSeparator separator between key and value
 * @param keyNames        used to filter values inserted
 * @return the key value map for keyNames
 */
private Map<String, String> getKeyValMap(final String inputString, final String fieldDelimiter,
        final String keyValSeparator, final List<String> keyNames) {
    final Set<String> uniqueKeyNames = new HashSet<String>(keyNames); // Optimize in the case of duplicate key names
    final Map<String, String> keyValMap = new HashMap<String, String>(uniqueKeyNames.size()); //Initialized with the expected size
    final Iterable<String> splitIterable = Splitter.on(fieldDelimiter).omitEmptyStrings().split(inputString); //Iterator to prevent excessive allocation
    int count = 0; // Counter to break out when we have seen all of the uniqueKeyNames
    for (final String keyValPair : splitIterable) {
        final String key = StringUtils.substringBefore(keyValPair, keyValSeparator);
        final String value = StringUtils.substringAfter(keyValPair, keyValSeparator);
        // Only consider valid pairs with non-empty/null keys that are in uniqueKeyNames
        if (StringUtils.contains(keyValPair, keyValSeparator) && !StringUtils.isEmpty(key)
                && uniqueKeyNames.contains(key)) {
            final String prev = keyValMap.put(key, value);
            if (prev == null) {
                count++;
            } else if (!mapWarned) { // Otherwise a key was replaced
                LOG.warn(
                        "At least 1 inputString had a duplicate key for a keyName. The second value will be represented. Additional warnings for a duplicate key will be suppressed.");
                mapWarned = true;
            }
            if (count >= uniqueKeyNames.size()) {
                break; // We have seen all of the keyNames needed
            }
        }
    }
    return keyValMap;
}

From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.MSSQLLoginComposite.java

@Override
public boolean connection() {
    if (!isValidate())
        return false;

    String dbUrl = "";
    String strHost = textHost.getText();
    if (StringUtils.contains(strHost, "\\")) {

        String strIp = StringUtils.substringBefore(strHost, "\\");
        String strInstance = StringUtils.substringAfter(strHost, "\\");

        dbUrl = String.format(DBDefine.MSSQL_DEFAULT.getDB_URL_INFO(), strIp, textPort.getText(),
                textDatabase.getText()) + ";instance=" + strInstance;
    } else if (StringUtils.contains(strHost, "/")) {

        String strIp = StringUtils.substringBefore(strHost, "/");
        String strInstance = StringUtils.substringAfter(strHost, "/");

        dbUrl = String.format(DBDefine.MSSQL_DEFAULT.getDB_URL_INFO(), strIp, textPort.getText(),
                textDatabase.getText()) + ";instance=" + strInstance;

    } else {/*from w  ww . j av a2 s.com*/
        dbUrl = String.format(DBDefine.MSSQL_DEFAULT.getDB_URL_INFO(), textHost.getText(), textPort.getText(),
                textDatabase.getText());
    }
    if (logger.isDebugEnabled())
        logger.debug("[db url]" + dbUrl);

    userDB = new UserDBDAO();
    userDB.setTypes(DBDefine.MSSQL_DEFAULT.getDBToString());
    userDB.setUrl(dbUrl);
    userDB.setDb(textDatabase.getText());
    userDB.setGroup_name(comboGroup.getText().trim());
    userDB.setDisplay_name(textDisplayName.getText());
    userDB.setOperation_type(DBOperationType.getNameToType(comboOperationType.getText()).toString());
    userDB.setHost(textHost.getText());
    userDB.setPasswd(textPassword.getText());
    userDB.setPort(textPort.getText());
    userDB.setUsers(textUser.getText());

    //  ?? ??
    if (oldUserDB != null) {
        if (!MessageDialog.openConfirm(null, "Confirm", Messages.SQLiteLoginComposite_13)) //$NON-NLS-1$
            return false;

        if (!checkDatabase(userDB))
            return false;

        try {
            TadpoleSystem_UserDBQuery.updateUserDB(userDB, oldUserDB, SessionManager.getSeq());
        } catch (Exception e) {
            logger.error(Messages.SQLiteLoginComposite_8, e);
            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
            ExceptionDetailsErrorDialog.openError(getShell(), "Error", Messages.SQLiteLoginComposite_5, //$NON-NLS-1$
                    errStatus);

            return false;
        }

        //  ?? .
    } else {

        int intVersion = 0;

        try {
            SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
            //  ? .
            DBInfoDAO dbInfo = (DBInfoDAO) sqlClient.queryForObject("findDBInfo"); //$NON-NLS-1$
            intVersion = Integer.parseInt(StringUtils.substringBefore(dbInfo.getProductversion(), "."));

        } catch (Exception e) {
            logger.error("MSSQL Connection", e); //$NON-NLS-1$
            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
            ExceptionDetailsErrorDialog.openError(getShell(), "Error", Messages.MSSQLLoginComposite_8, //$NON-NLS-1$
                    errStatus);

            return false;
        }

        try {
            if (intVersion <= 8) {
                userDB.setTypes(DBDefine.MSSQL_8_LE_DEFAULT.getDBToString());
            }

            TadpoleSystem_UserDBQuery.newUserDB(userDB, SessionManager.getSeq());
        } catch (Exception e) {
            logger.error("MSSQL", e); //$NON-NLS-1$
            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
            ExceptionDetailsErrorDialog.openError(getShell(), "Error", Messages.MSSQLLoginComposite_10, //$NON-NLS-1$
                    errStatus);
        }
    }

    return true;
}

From source file:eionet.cr.web.action.factsheet.FactsheetActionBean.java

/**
 * helper method to eliminate code duplication.
 *
 * @return Pair<Boolean, String> feedback messages
 * @throws HarvestException//from   w  w w  .  ja va 2 s  . c  om
 *             if harvesting fails
 * @throws DAOException
 *             if query fails
 */
private Pair<Boolean, String> harvestNow() throws HarvestException, DAOException {

    String message = null;
    if (isUserLoggedIn()) {
        if (!StringUtils.isBlank(uri) && URLUtil.isURL(uri)) {

            /* add this url into HARVEST_SOURCE table */

            HarvestSourceDAO dao = factory.getDao(HarvestSourceDAO.class);
            HarvestSourceDTO dto = new HarvestSourceDTO();
            dto.setUrl(StringUtils.substringBefore(uri, "#"));
            dto.setEmails("");
            dto.setIntervalMinutes(
                    Integer.valueOf(GeneralConfig.getProperty(GeneralConfig.HARVESTER_REFERRALS_INTERVAL,
                            String.valueOf(HarvestSourceDTO.DEFAULT_REFERRALS_INTERVAL))));
            dto.setPrioritySource(false);
            dto.setOwner(null);
            dao.addSourceIgnoreDuplicate(dto);

            /* issue an instant harvest of this url */

            OnDemandHarvester.Resolution resolution = OnDemandHarvester.harvest(dto.getUrl(), getUserName());

            /* give feedback to the user */

            if (resolution.equals(OnDemandHarvester.Resolution.ALREADY_HARVESTING)) {
                message = "The resource is currently being harvested by another user or background harvester!";
            } else if (resolution.equals(OnDemandHarvester.Resolution.UNCOMPLETE)) {
                message = "The harvest hasn't finished yet, but continues in the background!";
            } else if (resolution.equals(OnDemandHarvester.Resolution.COMPLETE)) {
                message = "The harvest has been completed!";
            } else if (resolution.equals(OnDemandHarvester.Resolution.SOURCE_UNAVAILABLE)) {
                message = "The resource was not available!";
            } else if (resolution.equals(OnDemandHarvester.Resolution.NO_STRUCTURED_DATA)) {
                message = "The resource contained no RDF data!";
                // else if (resolution.equals(InstantHarvester.Resolution.RECENTLY_HARVESTED))
                // message = "Source redirects to another source that has recently been harvested! Will not harvest.";
            } else {
                message = "No feedback given from harvest!";
            }
        }
        return new Pair<Boolean, String>(false, message);
    } else {
        return new Pair<Boolean, String>(true, getBundle().getString("not.logged.in"));
    }
}

From source file:ch.algotrader.service.ManagementServiceImpl.java

private OrderStatusVO convert(final OrderDetailsVO entry) {

    Order order = entry.getOrder();/*from   w ww.ja v  a2  s . co m*/
    ch.algotrader.entity.trade.OrderStatusVO execStatus = entry.getOrderStatus();

    ch.algotrader.vo.client.OrderStatusVO orderStatusVO = new OrderStatusVO();
    orderStatusVO.setSide(order.getSide());
    orderStatusVO.setQuantity(order.getQuantity());
    orderStatusVO
            .setType(StringUtils.substringBefore(ClassUtils.getShortClassName(order.getClass()), "OrderImpl"));
    orderStatusVO.setName(order.getSecurity().toString());
    orderStatusVO.setStrategy(order.getStrategy().toString());
    orderStatusVO.setAccount(order.getAccount() != null ? order.getAccount().toString() : "");
    orderStatusVO
            .setExchange(order.getEffectiveExchange() != null ? order.getEffectiveExchange().toString() : "");
    orderStatusVO.setTif(order.getTif() != null ? order.getTif().toString() : "");
    orderStatusVO.setIntId(order.getIntId());
    orderStatusVO.setExtId(order.getExtId());
    orderStatusVO.setStatus(execStatus.getStatus());
    orderStatusVO.setFilledQuantity(execStatus.getFilledQuantity());
    orderStatusVO.setRemainingQuantity(execStatus.getRemainingQuantity());
    orderStatusVO.setDescription(order.getExtDescription());

    return orderStatusVO;
}

From source file:edu.cornell.kfs.coa.document.validation.impl.AccountReversionRule.java

/**
 * Validates that the sub fund group code on the reversion account is valid as defined by the allowed values in
 * SELECTION_4 system parameter./*from  w ww.  ja  v a 2  s  . co m*/
 * 
 * @param acctReversion
 * @return true if valid, false otherwise
 */
protected boolean validateAccountSubFundGroup(AccountReversion acctReversion) {
    boolean valid = true;

    String subFundGroups = SpringContext.getBean(ParameterService.class)
            .getParameterValueAsString(Reversion.class, CUKFSConstants.Reversion.SELECTION_4);
    String propertyName = StringUtils.substringBefore(subFundGroups, "=");
    List<String> ruleValues = Arrays.asList(StringUtils.substringAfter(subFundGroups, "=").split(";"));

    if (ObjectUtils.isNotNull(ruleValues) && ruleValues.size() > 0) {

        GlobalVariables.getMessageMap().addToErrorPath("document.newMaintainableObject");

        if (ObjectUtils.isNotNull(acctReversion.getAccount())) {
            String accountSubFundGroupCode = acctReversion.getAccount().getSubFundGroupCode();

            if (ruleValues.contains(accountSubFundGroupCode)) {
                valid = false;
                GlobalVariables.getMessageMap().putError(CUKFSPropertyConstants.ACCT_REVERSION_ACCT_NUMBER,
                        RiceKeyConstants.ERROR_DOCUMENT_INVALID_VALUE_DENIED_VALUES_PARAMETER,
                        new String[] {
                                getDataDictionaryService().getAttributeLabel(SubFundGroup.class,
                                        KFSPropertyConstants.SUB_FUND_GROUP_CODE),
                                accountSubFundGroupCode,
                                getParameterAsStringForMessage(CUKFSConstants.Reversion.SELECTION_4),
                                getParameterValuesForMessage(ruleValues),
                                getDataDictionaryService().getAttributeLabel(AccountReversion.class,
                                        CUKFSPropertyConstants.ACCT_REVERSION_ACCT_NUMBER) });
            }
        }

        if (ObjectUtils.isNotNull(acctReversion.getBudgetReversionAccount())) {
            String budgetAccountSubFundGroupCode = acctReversion.getBudgetReversionAccount()
                    .getSubFundGroupCode();

            if (ruleValues.contains(budgetAccountSubFundGroupCode)) {
                valid = false;
                GlobalVariables.getMessageMap().putError(
                        CUKFSPropertyConstants.ACCT_REVERSION_BUDGET_REVERSION_ACCT_NUMBER,
                        RiceKeyConstants.ERROR_DOCUMENT_INVALID_VALUE_DENIED_VALUES_PARAMETER,
                        new String[] {
                                getDataDictionaryService().getAttributeLabel(SubFundGroup.class,
                                        KFSPropertyConstants.SUB_FUND_GROUP_CODE),
                                budgetAccountSubFundGroupCode,
                                getParameterAsStringForMessage(CUKFSConstants.Reversion.SELECTION_4),
                                getParameterValuesForMessage(ruleValues),
                                getDataDictionaryService().getAttributeLabel(AccountReversion.class,
                                        CUKFSPropertyConstants.ACCT_REVERSION_BUDGET_REVERSION_ACCT_NUMBER) });
            }
        }

        if (ObjectUtils.isNotNull(acctReversion.getCashReversionAccount())) {
            String cashAccountSubFundGroupCode = acctReversion.getCashReversionAccount().getSubFundGroupCode();

            if (ruleValues.contains(cashAccountSubFundGroupCode)) {
                valid = false;
                GlobalVariables.getMessageMap().putError(
                        CUKFSPropertyConstants.ACCT_REVERSION_CASH_REVERSION_ACCT_NUMBER,
                        RiceKeyConstants.ERROR_DOCUMENT_INVALID_VALUE_ALLOWED_VALUES_PARAMETER,
                        new String[] {
                                getDataDictionaryService().getAttributeLabel(SubFundGroup.class,
                                        KFSPropertyConstants.SUB_FUND_GROUP_CODE),
                                cashAccountSubFundGroupCode,
                                getParameterAsStringForMessage(CUKFSConstants.Reversion.SELECTION_4),
                                getParameterValuesForMessage(ruleValues),
                                getDataDictionaryService().getAttributeLabel(AccountReversion.class,
                                        CUKFSPropertyConstants.ACCT_REVERSION_CASH_REVERSION_ACCT_NUMBER) });
            }
        }

        GlobalVariables.getMessageMap().removeFromErrorPath("document.newMaintainableObject");
    }

    return valid;
}

From source file:com.contrastsecurity.ide.eclipse.ui.internal.model.RecommendationTab.java

private void insertTextBlock(Composite composite, String text) {

    if (text != null && !text.isEmpty()) {
        String[] links = StringUtils.substringsBetween(text, Constants.OPEN_TAG_LINK, Constants.CLOSE_TAG_LINK);

        if (links != null && links.length > 0) {

            String[] textBlocks = StringUtils.substringsBetween(text, Constants.CLOSE_TAG_LINK,
                    Constants.OPEN_TAG_LINK);

            String textBlockFirst = StringUtils.substringBefore(text, Constants.OPEN_TAG_LINK);
            String textBlockLast = StringUtils.substringAfterLast(text, Constants.CLOSE_TAG_LINK);

            createStyledTextBlock(composite, parseMustache(textBlockFirst));

            for (int i = 0; i < links.length; i++) {

                int indexOfDelimiter = links[i].indexOf(Constants.LINK_DELIM);
                String formattedLink = "<a href=\"" + links[i].substring(0, indexOfDelimiter) + "\">"
                        + links[i].substring(indexOfDelimiter + Constants.LINK_DELIM.length()) + "</a>";
                createLink(composite, formattedLink);

                if (textBlocks != null && textBlocks.length > 0 && i < links.length - 1) {
                    createStyledTextBlock(composite, parseMustache(textBlocks[i]));
                }/* ww  w.  jav  a  2  s  . c om*/
            }
            createStyledTextBlock(composite, parseMustache(textBlockLast));
        } else {
            createStyledTextBlock(composite, parseMustache(text));
        }
    }
}

From source file:cn.orignzmn.shopkepper.common.utils.excel.ImportExcel.java

/**
 * ??/*from  ww  w. ja  v a 2 s .  c  o  m*/
 * @param cls 
 * @param groups 
 */
public <E> List<E> getDataList(Class<E> cls, Map<String, Object> inportInfo, int... groups)
        throws InstantiationException, IllegalAccessException {
    List<Object[]> annotationList = Lists.newArrayList();
    // Get annotation field 
    Field[] fs = cls.getDeclaredFields();
    ExcelSheet esarr = cls.getAnnotation(ExcelSheet.class);
    String annTitle = "";
    if (esarr == null)
        return Lists.newArrayList();
    annTitle = esarr.value();
    for (Field f : fs) {
        ExcelField ef = f.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, f });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, f });
            }
        }
    }
    // Get annotation method
    Method[] ms = cls.getDeclaredMethods();
    for (Method m : ms) {
        ExcelField ef = m.getAnnotation(ExcelField.class);
        if (ef != null && (ef.type() == 0 || ef.type() == 2)) {
            if (groups != null && groups.length > 0) {
                boolean inGroup = false;
                for (int g : groups) {
                    if (inGroup) {
                        break;
                    }
                    for (int efg : ef.groups()) {
                        if (g == efg) {
                            inGroup = true;
                            annotationList.add(new Object[] { ef, m });
                            break;
                        }
                    }
                }
            } else {
                annotationList.add(new Object[] { ef, m });
            }
        }
    }
    // Field sorting
    Collections.sort(annotationList, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return new Integer(((ExcelField) o1[0]).sort()).compareTo(new Integer(((ExcelField) o2[0]).sort()));
        };
    });
    //log.debug("Import column count:"+annotationList.size());
    // Get excel data
    List<E> dataList = Lists.newArrayList();
    //???
    if (!"".equals(annTitle)) {
        String title = StringUtils.trim(this.getCellValue(this.getRow(0), 0).toString());
        if (!annTitle.equals(title)) {
            inportInfo.put("success", false);
            inportInfo.put("message", "??");
            return Lists.newArrayList();
        }
    }
    for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
        E e = (E) cls.newInstance();
        int column = 0;
        Row row = this.getRow(i);

        StringBuilder sb = new StringBuilder();
        for (Object[] os : annotationList) {
            Object val = this.getCellValue(row, column++);
            if (val != null) {
                ExcelField ef = (ExcelField) os[0];
                // If is dict type, get dict value
                //               if (StringUtils.isNotBlank(ef.dictType())){
                //                  val = DictUtils.getDictValue(val.toString(), ef.dictType(), "");
                //                  //log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
                //               }
                // Get param type and type cast
                Class<?> valType = Class.class;
                if (os[1] instanceof Field) {
                    valType = ((Field) os[1]).getType();
                } else if (os[1] instanceof Method) {
                    Method method = ((Method) os[1]);
                    if ("get".equals(method.getName().substring(0, 3))) {
                        valType = method.getReturnType();
                    } else if ("set".equals(method.getName().substring(0, 3))) {
                        valType = ((Method) os[1]).getParameterTypes()[0];
                    }
                }
                //log.debug("Import value type: ["+i+","+column+"] " + valType);
                try {
                    if (valType == String.class) {
                        String s = String.valueOf(val.toString());
                        if (StringUtils.endsWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            val = String.valueOf(val.toString());
                        }
                    } else if (valType == Integer.class) {
                        val = Double.valueOf(val.toString()).intValue();
                    } else if (valType == Long.class) {
                        val = Double.valueOf(val.toString()).longValue();
                    } else if (valType == Double.class) {
                        val = Double.valueOf(val.toString());
                    } else if (valType == Float.class) {
                        val = Float.valueOf(val.toString());
                    } else if (valType == Date.class) {
                        val = DateUtil.getJavaDate((Double) val);
                    } else {
                        if (ef.fieldType() != Class.class) {
                            val = ef.fieldType().getMethod("getValue", String.class).invoke(null,
                                    val.toString());
                        } else {
                            val = Class
                                    .forName(this.getClass().getName().replaceAll(
                                            this.getClass().getSimpleName(),
                                            "fieldtype." + valType.getSimpleName() + "Type"))
                                    .getMethod("getValue", String.class).invoke(null, val.toString());
                        }
                    }
                } catch (Exception ex) {
                    log.info("Get cell value [" + i + "," + column + "] error: " + ex.toString());
                    val = null;
                }
                // set entity value
                if (os[1] instanceof Field) {
                    Reflections.invokeSetter(e, ((Field) os[1]).getName(), val);
                } else if (os[1] instanceof Method) {
                    String mthodName = ((Method) os[1]).getName();
                    if ("get".equals(mthodName.substring(0, 3))) {
                        mthodName = "set" + StringUtils.substringAfter(mthodName, "get");
                    }
                    Reflections.invokeMethod(e, mthodName, new Class[] { valType }, new Object[] { val });
                }
            }
            sb.append(val + ", ");
        }
        dataList.add(e);
        log.debug("Read success: [" + i + "] " + sb.toString());
    }
    return dataList;
}

From source file:com.hangum.tadpole.rdb.core.dialog.dbconnect.composite.MSSQLLoginComposite.java

@Override
public boolean saveDBData() {
    if (!testConnection(false))
        return false;

    //  ?? ??//  www.  j  ava2  s. c o m
    if (getDataActionStatus() == DATA_STATUS.MODIFY) {
        if (!MessageDialog.openConfirm(null, Messages.get().Confirm, Messages.get().SQLiteLoginComposite_13))
            return false; //$NON-NLS-1$

        try {
            TadpoleSystem_UserDBQuery.updateUserDB(userDB, oldUserDB, SessionManager.getUserSeq());
        } catch (Exception e) {
            logger.error("MSSQL connection", e);
            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
            ExceptionDetailsErrorDialog.openError(getShell(), Messages.get().Error,
                    Messages.get().SQLiteLoginComposite_5, errStatus); //$NON-NLS-1$

            return false;
        }

        //  ?? .
    } else {

        if (userDB.getDBDefine() == DBDefine.MSSQL_DEFAULT) {
            int intVersion = 0;

            try {
                SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
                //  ? .
                DBInfoDAO dbInfo = (DBInfoDAO) sqlClient.queryForObject("findDBInfo"); //$NON-NLS-1$
                intVersion = Integer.parseInt(StringUtils.substringBefore(dbInfo.getProductversion(), "."));

                if (intVersion <= 8) {
                    userDB.setDbms_type(DBDefine.MSSQL_8_LE_DEFAULT.getDBToString());
                }
            } catch (Exception e) {
                logger.error("MSSQL Connection", e); //$NON-NLS-1$
                Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
                ExceptionDetailsErrorDialog.openError(getShell(), Messages.get().Error,
                        Messages.get().MSSQLLoginComposite_8, errStatus); //$NON-NLS-1$

                return false;
            }
        }

        try {
            TadpoleSystem_UserDBQuery.newUserDB(userDB, SessionManager.getUserSeq());
        } catch (Exception e) {
            logger.error("MSSQL connection save", e); //$NON-NLS-1$
            Status errStatus = new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e); //$NON-NLS-1$
            ExceptionDetailsErrorDialog.openError(getShell(), Messages.get().Error,
                    Messages.get().MSSQLLoginComposite_10, errStatus); //$NON-NLS-1$

            return false;
        }
    }

    return true;
}

From source file:com.amalto.core.server.StorageAdminImpl.java

private Storage internalCreateStorage(String dataModelName, String storageName, String dataSourceName,
        StorageType storageType) {/*from w w  w.  ja v a2s. c  o  m*/
    ServerContext instance = ServerContext.INSTANCE;
    String registeredStorageName = storageName;
    // May get request for "StorageName/Concept", but for SQL it does not make any sense.
    // See com.amalto.core.storage.StorageWrapper.createCluster()
    storageName = StringUtils.substringBefore(storageName, "/"); //$NON-NLS-1$
    dataModelName = StringUtils.substringBefore(dataModelName, "/"); //$NON-NLS-1$
    if (getRegisteredStorage(registeredStorageName, storageType) != null) {
        LOGGER.warn("Storage for '" + storageName
                + "' already exists. This is probably normal. If you want MDM to recreate it from scratch, delete the container and restart.");
        return get(storageName, storageType);
    }
    // Replace all container name, so re-read the configuration.
    DataSourceDefinition definition = instance.get().getDefinition(dataSourceName, storageName);
    if (!instance.get().hasDataSource(dataSourceName, storageName, storageType)) {
        LOGGER.warn("Can not initialize " + storageType + " storage for '" + storageName + "': data source '"
                + dataSourceName + "' configuration is incomplete.");
        return null;
    }
    // Create storage
    Storage dataModelStorage = instance.getLifecycle().createStorage(storageName, storageType, definition);
    MetadataRepositoryAdmin metadataRepositoryAdmin = instance.get().getMetadataRepositoryAdmin();
    boolean hasDataModel = metadataRepositoryAdmin.exist(dataModelName);
    if (!hasDataModel) {
        throw new UnsupportedOperationException("Data model '" + dataModelName
                + "' must exist before container '" + storageName + "' can be created.");
    }
    if (storageType == StorageType.STAGING && dataModelName.endsWith(STAGING_SUFFIX)) {
        dataModelName += STAGING_SUFFIX;
    }
    MetadataRepository metadataRepository = metadataRepositoryAdmin.get(dataModelName);
    Set<Expression> indexedExpressions = metadataRepositoryAdmin.getIndexedExpressions(dataModelName);
    try {
        dataModelStorage.prepare(metadataRepository, indexedExpressions, true, autoClean);
    } catch (Exception e) {
        throw new RuntimeException("Could not create storage for container '" + storageName + "' ("
                + storageType + ") using data model '" + dataModelName + "'.", e);
    }
    switch (storageType) {
    case MASTER:
        registerStorage(registeredStorageName, dataModelStorage);
        break;
    case STAGING:
        registerStorage(registeredStorageName, new StagingStorage(dataModelStorage));
        break;
    default:
        throw new IllegalArgumentException("No support for storage type '" + storageType + "'.");
    }
    if (LOGGER.isDebugEnabled()) {
        StringBuilder capabilitiesAsString = new StringBuilder();
        int capabilities = dataModelStorage.getCapabilities();
        capabilitiesAsString.append(" TRANSACTION"); //$NON-NLS-1$
        if ((capabilities & Storage.CAP_TRANSACTION) == Storage.CAP_TRANSACTION) {
            capabilitiesAsString.append("(+)"); //$NON-NLS-1$
        } else {
            capabilitiesAsString.append("(-)"); //$NON-NLS-1$
        }
        capabilitiesAsString.append(" FULL TEXT"); //$NON-NLS-1$
        if ((capabilities & Storage.CAP_FULL_TEXT) == Storage.CAP_FULL_TEXT) {
            capabilitiesAsString.append("(+)"); //$NON-NLS-1$
        } else {
            capabilitiesAsString.append("(-)"); //$NON-NLS-1$
        }
        capabilitiesAsString.append(" INTEGRITY"); //$NON-NLS-1$
        if ((capabilities & Storage.CAP_INTEGRITY) == Storage.CAP_INTEGRITY) {
            capabilitiesAsString.append("(+)"); //$NON-NLS-1$
        } else {
            capabilitiesAsString.append("(-)"); //$NON-NLS-1$
        }
        LOGGER.debug("Storage capabilities:" + capabilitiesAsString);
    }
    return dataModelStorage;
}