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

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

Introduction

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

Prototype

public static boolean startsWithIgnoreCase(String str, String prefix) 

Source Link

Document

Case insensitive check if a String starts with a specified prefix.

Usage

From source file:com.hangum.tadpole.rdb.core.editors.objects.table.TableDirectEditorComposite.java

/**
 * save table data/*from   ww w.jav a2 s  . c o  m*/
 */
private void saveTableData() {
    String strQuery = getChangeQuery();
    if ("".equals(strQuery)) //$NON-NLS-1$
        return;

    String strShowEditor = "";
    String[] querys = SQLTextUtil.delLineChar(strQuery).split(";"); //$NON-NLS-1$

    boolean isUpdateOrDelete = false;
    for (int i = 0; i < querys.length; i++) {
        if (logger.isDebugEnabled())
            logger.debug("exe query [" + querys[i] + "]"); //$NON-NLS-1$ //$NON-NLS-2$
        strShowEditor += querys[i] + ";" + PublicTadpoleDefine.LINE_SEPARATOR;

        if (StringUtils.startsWithIgnoreCase(querys[i], "update") || //$NON-NLS-1$
                StringUtils.startsWithIgnoreCase(querys[i], "delete")) //$NON-NLS-1$
            isUpdateOrDelete = true;
    }

    String changedSQL = "";

    int isUpdateed = IDialogConstants.CANCEL_ID;
    if (isUpdateOrDelete) {
        DBDefine selectDB = userDB.getDBDefine();
        if (selectDB == DBDefine.SQLite_DEFAULT || selectDB == DBDefine.CUBRID_DEFAULT
                || selectDB == DBDefine.MSSQL_DEFAULT || selectDB == DBDefine.MSSQL_8_LE_DEFAULT) {

            DirectChangeDialog dialog = new DirectChangeDialog(getShell(),
                    Messages.get().TableDirectEditorComposite_17, strShowEditor);
            isUpdateed = dialog.open();
            changedSQL = dialog.getSQL();
        } else {
            DirectChangeDialog dialog = new DirectChangeDialog(getShell(),
                    Messages.get().TableDirectEditorComposite_19, strShowEditor);
            isUpdateed = dialog.open();
            changedSQL = dialog.getSQL();
        }
    } else {
        DirectChangeDialog dialog = new DirectChangeDialog(getShell(),
                Messages.get().TableDirectEditorComposite_19, strShowEditor);
        isUpdateed = dialog.open();
        changedSQL = dialog.getSQL();
    }

    if (isUpdateed == IDialogConstants.CANCEL_ID)
        return;
    if ("".equals(changedSQL)) //$NON-NLS-1$
        return;

    querys = SQLTextUtil.delLineChar(changedSQL).split(";"); //$NON-NLS-1$
    try {
        RequestQuery reqQuery = new RequestQuery(userDB, changedSQL, OBJECT_TYPE.TABLES, QUERY_MODE.QUERY,
                EXECUTE_TYPE.ALL, true);
        ExecuteBatchSQL.runSQLExecuteBatch(Messages.get().MainEditor_21, Arrays.asList(querys), reqQuery,
                userDB, userDB.getRole_id(), 1000, SessionManager.getEMAIL());

        // ??    .
        initBusiness();
        initButtonCtrl();
    } catch (Exception e) {
        TDBErroDialog dialog = new TDBErroDialog(getShell(), "Update Fail",
                Messages.get().TableViewerEditPart_10 + e.getMessage());
        dialog.open();
    }
}

From source file:com.sfs.whichdoctor.dao.RelationshipDAOImpl.java

/**
 * Generates a map of supervisors based on their hierarchy. This function
 * ensures all required supervisor positions are filled.
 *
 * @param supervisors as a collection of RelationshipBeans
 *
 * @return the tree map< integer, relationship bean>
 *///www . j a  v a 2  s  . c o  m
private TreeMap<Integer, RelationshipBean> buildFullSupervisorMap(
        final Collection<RelationshipBean> supervisors) {

    TreeMap<Integer, RelationshipBean> fullSupervisorMap = new TreeMap<Integer, RelationshipBean>();

    TreeMap<Integer, RelationshipBean> btSupervisorMap = new TreeMap<Integer, RelationshipBean>();

    if (supervisors != null) {
        String relationshipClass = "";
        for (RelationshipBean relationship : supervisors) {
            if (StringUtils.startsWithIgnoreCase(relationship.getRelationshipClass(), "Basic")) {
                // Only one relationship per basic training hierarchy-level is allowed
                if (dataLogger.isDebugEnabled()) {
                    dataLogger.debug("Relationship: " + relationship.getRelationshipType());
                    dataLogger.debug("Hierarchy: " + relationship.getHierarchy());
                }
                relationshipClass = relationship.getRelationshipClass();
                btSupervisorMap.put(relationship.getHierarchy(), relationship);
            }
        }

        // If a basic training supervisor exists build a full map
        if (btSupervisorMap.size() > 0) {
            dataLogger.debug("At least one basic training supervisor exists");
            dataLogger.debug("Relationship class: " + relationshipClass);
            fullSupervisorMap = buildInheritedMap(relationshipClass, btSupervisorMap);
        }

        for (RelationshipBean relationship : supervisors) {
            if (!StringUtils.startsWithIgnoreCase(relationship.getRelationshipClass(), "Basic")) {
                String heirarchy = relationship.getHierarchy() + "00" + relationship.getReferenceGUID();
                int index = Integer.parseInt(heirarchy);
                fullSupervisorMap.put(index, relationship);
            }
        }
    }

    dataLogger.debug("Supervisor map size: " + fullSupervisorMap.size());

    return fullSupervisorMap;
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private HttpRequestBase buildHttpRequest(URI hostURI, HttpDispatcherProperties httpDispatcherProperties,
        ConnectorMessage connectorMessage, File tempFile, ContentType contentType, Charset charset)
        throws Exception {
    String method = httpDispatcherProperties.getMethod();
    boolean isMultipart = httpDispatcherProperties.isMultipart();
    Map<String, List<String>> headers = httpDispatcherProperties.getHeaders();
    Map<String, List<String>> parameters = httpDispatcherProperties.getParameters();

    Object content = null;//ww w .  j a v  a2 s  .c o m
    if (httpDispatcherProperties.isDataTypeBinary()) {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage, null, true);
    } else {
        content = getAttachmentHandlerProvider().reAttachMessage(httpDispatcherProperties.getContent(),
                connectorMessage);

        // If text mode is used and a specific charset isn't already defined, use the one from the connector properties
        if (contentType.getCharset() == null) {
            contentType = HttpMessageConverter.setCharset(contentType, charset);
        }
    }

    // populate the query parameters
    List<NameValuePair> queryParameters = new ArrayList<NameValuePair>(parameters.size());

    for (Entry<String, List<String>> parameterEntry : parameters.entrySet()) {
        for (String value : parameterEntry.getValue()) {
            logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + value + "]");
            queryParameters.add(new BasicNameValuePair(parameterEntry.getKey(), value));
        }
    }

    HttpRequestBase httpMethod = null;
    HttpEntity httpEntity = null;
    URIBuilder uriBuilder = new URIBuilder(hostURI);

    // create the method
    if ("GET".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpGet(uriBuilder.build());
    } else if ("POST".equalsIgnoreCase(method)) {
        if (isMultipart) {
            logger.debug("setting multipart file content");
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                FileUtils.writeStringToFile(tempFile, (String) content, contentType.getCharset(), false);
            } else {
                FileUtils.writeByteArrayToFile(tempFile, (byte[]) content, false);
            }

            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.addPart(tempFile.getName(),
                    new FileBody(tempFile, contentType, tempFile.getName()));
            httpEntity = multipartEntityBuilder.build();
        } else if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPost(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPost(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("PUT".equalsIgnoreCase(method)) {
        if (StringUtils.startsWithIgnoreCase(contentType.getMimeType(),
                ContentType.APPLICATION_FORM_URLENCODED.getMimeType())) {
            httpMethod = new HttpPut(uriBuilder.build());
            httpEntity = new UrlEncodedFormEntity(queryParameters, contentType.getCharset());
        } else {
            setQueryString(uriBuilder, queryParameters);
            httpMethod = new HttpPut(uriBuilder.build());

            if (content instanceof String) {
                httpEntity = new StringEntity((String) content, contentType);
            } else {
                httpEntity = new ByteArrayEntity((byte[]) content);
            }
        }
    } else if ("DELETE".equalsIgnoreCase(method)) {
        setQueryString(uriBuilder, queryParameters);
        httpMethod = new HttpDelete(uriBuilder.build());
    }

    if (httpMethod instanceof HttpEntityEnclosingRequestBase) {
        // Compress the request entity if necessary
        List<String> contentEncodingList = (List<String>) new CaseInsensitiveMap(headers)
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.toLowerCase().equals("gzip")
                        || contentEncoding.toLowerCase().equals("x-gzip"))) {
                    httpEntity = new GzipCompressingEntity(httpEntity);
                    break;
                }
            }
        }

        ((HttpEntityEnclosingRequestBase) httpMethod).setEntity(httpEntity);
    }

    // set the headers
    for (Entry<String, List<String>> headerEntry : headers.entrySet()) {
        for (String value : headerEntry.getValue()) {
            logger.debug("setting method header: [" + headerEntry.getKey() + ", " + value + "]");
            httpMethod.addHeader(headerEntry.getKey(), value);
        }
    }

    // Only set the Content-Type for entity-enclosing methods, but not if multipart is used
    if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method)) && !isMultipart) {
        httpMethod.setHeader(HTTP.CONTENT_TYPE, contentType.toString());
    }

    return httpMethod;
}

From source file:com.mirth.connect.connectors.http.HttpSender.java

private boolean isUsingFormUrlEncoded(String contentType) {
    return StringUtils.startsWithIgnoreCase(contentType, ContentType.APPLICATION_FORM_URLENCODED.getMimeType());
}

From source file:edu.monash.merc.system.parser.nextprot.NxXMLParser.java

@SuppressWarnings("unchecked")
private NXPeMsAntiEntryBean parseNXPeMSAntiAnn(Element protein) {

    NXPeMsAntiEntryBean peMsAntiEntryBean = new NXPeMsAntiEntryBean();

    List<PEEvidenceBean> peMsEvidenceBeans = new ArrayList<PEEvidenceBean>();
    Element xrefsEle = protein.getChild(ELE_XREFS);
    if (xrefsEle != null) {

        //PE MS ANTI ANN url
        String peMsAntiURL = null;

        //PE MS ANTI
        int peMsAntiCounter = 0;
        List<Element> xrefElements = xrefsEle.getChildren(ELE_XREF);
        for (Element xrefEle : xrefElements) {
            //create a pe ms evidence object
            PEEvidenceBean peMsAnnEvidenceBean = new PEEvidenceBean();

            String xrefDatabase = null;
            String xrefCategory = null;
            String xrefAccession = null;
            String xrefId = null;
            String xrefUrl = null;
            //database
            Attribute xrefDbAtt = xrefEle.getAttribute(ATTR_XREF_DATABASE);
            if (xrefDbAtt != null) {
                xrefDatabase = xrefDbAtt.getValue();

            }// w w  w. java2  s.  c o m

            //category
            Attribute xrefCategAtt = xrefEle.getAttribute(ATTR_XREF_CATEGORY);
            if (xrefCategAtt != null) {
                xrefCategory = xrefCategAtt.getValue();

            }

            //accession
            Attribute xrefAccessionAtt = xrefEle.getAttribute(ATTR_XREF_ACCESSION);
            if (xrefAccessionAtt != null) {
                xrefAccession = xrefAccessionAtt.getValue();
            }

            //id
            Attribute xrefIdAtt = xrefEle.getAttribute(ATTR_XREF_ID);
            if (xrefIdAtt != null) {
                xrefId = xrefIdAtt.getValue();
            }

            //url

            Element xrefUrlEle = xrefEle.getChild(ELE_XREF_URL);
            if (xrefEle != null) {
                xrefUrl = xrefUrlEle.getTextNormalize();
            }

            if (StringUtils.isNotBlank(xrefDatabase) && (StringUtils.isNotBlank(xrefCategory))) {
                //if category = Proteomic database and database = PRIDE
                if (StringUtils.equalsIgnoreCase(xrefDatabase, NXConts.XREF_DB_PRIDE)
                        && StringUtils.equalsIgnoreCase(xrefCategory, NXConts.XREF_CA_PROTEOMIC_DATABASES)) {
                    //set the color red
                    peMsAnnEvidenceBean.setColorLevel(ColorType.RED.color());
                    //set the link value
                    if (StringUtils.isNotBlank(xrefAccession)) {
                        peMsAnnEvidenceBean.setHyperlink(xrefUrl);
                    }
                    //added the evidence
                    String evidence = null;
                    evidence = xrefDatabase;
                    if (StringUtils.isNotBlank(xrefAccession)) {
                        evidence += " - " + xrefAccession;
                    }
                    if (StringUtils.isNotBlank(evidence)) {
                        peMsAnnEvidenceBean.setEvidenceValue(evidence);
                    }

                    //create a TPBDataTypeBean
                    TPBDataTypeBean tpbDataTypeBean = new TPBDataTypeBean();
                    //set the data type
                    tpbDataTypeBean.setDataType(DataType.PE_MS_ANN.type());
                    //set the traffic lights level to 3
                    tpbDataTypeBean.setLevel(TLLevel.TL3.level());
                    peMsAnnEvidenceBean.setTpbDataTypeBean(tpbDataTypeBean);
                    //add the PE MS Annotation for PRIDE
                    peMsEvidenceBeans.add(peMsAnnEvidenceBean);
                }
                //if category = Proteomic database and database = PeptideAtlas
                if (StringUtils.equalsIgnoreCase(xrefDatabase, NXConts.XREF_DB_PEPTIDE_ATLAS)
                        && StringUtils.equalsIgnoreCase(xrefCategory, NXConts.XREF_CA_PROTEOMIC_DATABASES)) {
                    //set the color yellow
                    peMsAnnEvidenceBean.setColorLevel(ColorType.YELLOW.color());
                    if (StringUtils.isNotBlank(xrefAccession)) {
                        peMsAnnEvidenceBean.setHyperlink(xrefUrl);
                    }
                    //added the evidence
                    String evidence = null;
                    evidence = xrefDatabase;
                    if (StringUtils.isNotBlank(xrefAccession)) {
                        evidence += " - " + xrefAccession;
                    }
                    if (StringUtils.isNotBlank(evidence)) {
                        peMsAnnEvidenceBean.setEvidenceValue(evidence);
                    }
                    //create a TPBDataTypeBean
                    TPBDataTypeBean tpbDataTypeBean = new TPBDataTypeBean();
                    //set the data type
                    tpbDataTypeBean.setDataType(DataType.PE_MS_ANN.type());
                    //set the traffic lights level to 3
                    tpbDataTypeBean.setLevel(TLLevel.TL3.level());
                    peMsAnnEvidenceBean.setTpbDataTypeBean(tpbDataTypeBean);
                    //add pe ms annotation for PeptideAtlas
                    peMsEvidenceBeans.add(peMsAnnEvidenceBean);
                }
            }

            //find the PE ANTI ANN
            if (StringUtils.isNotBlank(xrefDatabase) && StringUtils.isNotBlank(xrefCategory)
                    && StringUtils.isNotBlank(xrefAccession)) {
                if (StringUtils.equalsIgnoreCase(xrefDatabase, NXConts.XREF_DB_HPA)
                        && StringUtils.equalsIgnoreCase(xrefCategory, NXConts.XREF_CA_ANTIBODY_DATABASES)) {
                    //  System.out.println("===================> PE ANTI Ann:  Accession: " + xrefAccession);
                    if (StringUtils.startsWithIgnoreCase(xrefAccession, NXConts.XREF_AC_PREFIX_ENSG)) {
                        if (StringUtils.isNotBlank(xrefUrl)) {
                            peMsAntiURL = StringUtils.removeEndIgnoreCase(xrefUrl,
                                    NXConts.XREF_AC_ENSG_URL_END_PART);
                            // System.out.println("================== URL: " + peMsAntiURL);
                        }
                    }

                    if (StringUtils.startsWithIgnoreCase(xrefAccession, NXConts.XREF_AC_PREFIX_HPA)
                            || StringUtils.startsWithIgnoreCase(xrefAccession, NXConts.XREF_AC_PREFIX_CAB)) {
                        if (StringUtils.isBlank(peMsAntiURL)) {
                            peMsAntiURL = xrefUrl;
                        }
                        peMsAntiCounter++;
                    }
                }
            }

        }

        //add the PE MS Ann Evidences if Any
        peMsAntiEntryBean.setPeMsAnnEvidenceBeans(peMsEvidenceBeans);

        //PE ANTI ANN
        if (peMsAntiCounter > 0) {
            //create a pe anti evidence object
            PEEvidenceBean peAntiAnnEvidenceBean = new PEEvidenceBean();
            if (peMsAntiCounter == 1) {
                peAntiAnnEvidenceBean.setColorLevel(ColorType.RED.color());
            }
            if (peMsAntiCounter > 1) {
                peAntiAnnEvidenceBean.setColorLevel(ColorType.YELLOW.color());
            }
            peAntiAnnEvidenceBean.setEvidenceValue(peMsAntiCounter + " " + NXConts.XREF_HPA_ANTIBODY_DESC);
            if (StringUtils.isNotBlank(peMsAntiURL)) {
                peAntiAnnEvidenceBean.setHyperlink(peMsAntiURL);
            }
            //create a TPBDataTypeBean
            TPBDataTypeBean tpbDataTypeBean = new TPBDataTypeBean();
            //set the data type
            tpbDataTypeBean.setDataType(DataType.PE_ANTI_ANN.type());
            //set the traffic lights level to 3
            tpbDataTypeBean.setLevel(TLLevel.TL3.level());
            peAntiAnnEvidenceBean.setTpbDataTypeBean(tpbDataTypeBean);
            //set the pe anti ann object
            peMsAntiEntryBean.setPeAntiAnnEvidenceBean(peAntiAnnEvidenceBean);
        }
    }
    return peMsAntiEntryBean;
}

From source file:com.hangum.tadpole.rdb.core.editors.main.composite.ResultSetComposite.java

/**
 *  ./*  w  w  w  .  ja v  a 2s .  co m*/
 * 
 * @param reqQuery
 */
public boolean executeCommand(final RequestQuery reqQuery) {
    //  ?  ?? 
    if (jobQueryManager != null) {
        if (Job.RUNNING == jobQueryManager.getState()) {
            if (logger.isDebugEnabled())
                logger.debug("\t\t================= return already running query job "); //$NON-NLS-1$
            executeErrorProgress(reqQuery, new Exception(Messages.get().ResultSetComposite_1),
                    Messages.get().ResultSetComposite_1);
            return false;
        }
    }

    //    ??( ????, ?? select ?,??) 
    try {
        if (!GrantCheckerUtils.ifExecuteQuery(getUserDB(), reqQuery)) {
            return false;
        }
    } catch (Exception e) {
        executeErrorProgress(reqQuery, e, e.getMessage());
        return false;
    }

    // agens graph preparement  .
    if (DBDefine.AGENSGRAPH_DEFAULT != getUserDB().getDBDefine()) {
        // ? ?? ?  ? .
        if (!ifIsParameterQuery(reqQuery))
            return false;
    }

    //  ?  ? .
    controlProgress(true);

    if (compositeResult != null)
        compositeResult.initUI();

    final List<QueryExecuteResultDTO> listRSDao = new ArrayList<>();

    final int intSelectLimitCnt = GetPreferenceGeneral.getSelectLimitCount();
    final String strPlanTBName = GetPreferenceGeneral.getPlanTableName();
    final String strUserEmail = SessionManager.getEMAIL();
    final int queryTimeOut = GetPreferenceGeneral.getQueryTimeOut();
    final int intCommitCount = Integer.parseInt(GetPreferenceGeneral.getRDBCommitCount());
    final UserDBDAO tmpUserDB = getUserDB();
    final String errMsg = Messages.get().MainEditor_21;
    final RequestResultDAO reqResultDAO = new RequestResultDAO();
    // is profilling
    final boolean isProfilling = GetPreferenceGeneral.getRDBQueryProfilling();

    jobQueryManager = new Job(Messages.get().MainEditor_45) {
        @Override
        public IStatus run(IProgressMonitor monitor) {
            monitor.beginTask(reqQuery.getSql(), IProgressMonitor.UNKNOWN);

            reqResultDAO.setStartDateExecute(new Timestamp(System.currentTimeMillis()));
            reqResultDAO.setIpAddress(reqQuery.getUserIp());

            StringBuffer sbParameter = new StringBuffer("/* Execute type is ").append(reqQuery.getMode());
            // prepared statement ?  ??? .
            if (reqQuery.getSqlStatementType() == SQL_STATEMENT_TYPE.PREPARED_STATEMENT) {
                sbParameter.append(", Parameter is ");
                for (int i = 0; i < reqQuery.getStatementParameter().length; i++) {
                    Object objParam = reqQuery.getStatementParameter()[i];
                    sbParameter.append(String.format("[ %d = %s ]", i, "" + objParam));
                }
            }
            sbParameter.append(" */ \n");
            reqResultDAO.setStrSQLText(sbParameter.toString() + reqQuery.getOriginalSql());

            try {
                if (reqQuery.getExecuteType() == EditorDefine.EXECUTE_TYPE.ALL) {
                    List<String> listStrExecuteQuery = new ArrayList<String>();
                    List<String> listStrSQL = new ArrayList<String>();
                    for (String strSQL : reqQuery.getSql().split(PublicTadpoleDefine.SQL_DELIMITER)) {
                        String strExeSQL = SQLUtil.makeExecutableSQL(tmpUserDB, strSQL);

                        // execute batch update ddl?  ?      ?.
                        if (!SQLUtil.isStatement(strExeSQL)) {
                            listStrExecuteQuery.add(strExeSQL);
                        } else {
                            listStrSQL.add(strExeSQL);
                        }
                    }
                    // select ??  
                    if (!listStrExecuteQuery.isEmpty()) {
                        ExecuteBatchSQL.runSQLExecuteBatch(errMsg, listStrExecuteQuery, reqQuery, getUserDB(),
                                getDbUserRoleType(), intCommitCount, strUserEmail);
                    }

                    if (!listStrSQL.isEmpty()) {
                        for (int i = 0; i < listStrSQL.size(); i++) {
                            if (i >= BATCH_EXECUTE_SQL_LIMIT)
                                break;
                            reqQuery.setSql(listStrSQL.get(i));
                            QueryExecuteResultDTO qeResultDao = runSelect(reqQuery, queryTimeOut, strUserEmail,
                                    intSelectLimitCnt, 0);
                            listRSDao.add(qeResultDao);
                        }
                    }

                } else {
                    if (reqQuery.isStatement()) {
                        if (reqQuery.getMode() == EditorDefine.QUERY_MODE.EXPLAIN_PLAN) {
                            listRSDao.add(
                                    ExecuteQueryPlan.runSQLExplainPlan(getUserDB(), reqQuery, strPlanTBName));
                        } else {
                            QueryExecuteResultDTO rsDAO = null;

                            // 
                            // mysql profile, show status, query plan ? .
                            // 
                            // SET, CALL ? ?? ? - hangum
                            //
                            //
                            if (DBGroupDefine.MYSQL_GROUP == getUserDB().getDBGroup()) {
                                if (isProfilling) {

                                    QueryUtils.executeQuery(tmpUserDB, "SET PROFILING = 1", 0, 10);
                                    QueryUtils.executeQuery(tmpUserDB, "SET profiling_history_size = 0", 0, 10);
                                    QueryUtils.executeQuery(tmpUserDB, "SET profiling_history_size = 15", 0,
                                            10);

                                    // ?  . 
                                    QueryExecuteResultDTO startStatus = QueryUtils.executeQuery(tmpUserDB,
                                            "SHOW STATUS", 0, 500);

                                    //
                                    rsDAO = runSelect(reqQuery, queryTimeOut, strUserEmail, intSelectLimitCnt,
                                            0);
                                    listRSDao.add(rsDAO);
                                    //
                                    QueryExecuteResultDTO endStatus = QueryUtils.executeQuery(tmpUserDB,
                                            "SHOW STATUS", 0, 500);
                                    QueryExecuteResultDTO _tmppShowProfiles = QueryUtils.executeQuery(tmpUserDB,
                                            "SHOW PROFILES", 0, 100);
                                    String strQueryID = getLastQueryID(_tmppShowProfiles);

                                    if (logger.isDebugEnabled())
                                        logger.debug("profile query id is : " + strQueryID);
                                    QueryExecuteResultDTO showProfiles = QueryUtils.executeQuery(tmpUserDB,
                                            String.format(
                                                    "SELECT state, ROUND(SUM(duration),5) AS `duration(sec)` FROM information_schema.profiling WHERE query_id=%s GROUP BY state ORDER BY `duration(sec)` DESC",
                                                    strQueryID),
                                            0, 100);
                                    rsDAO.setMapExtendResult(
                                            MySQLExtensionViewDialog.MYSQL_EXTENSION_VIEW.SHOW_PROFILLING
                                                    .name(),
                                            showProfiles);

                                    // diff data
                                    QueryExecuteResultDTO diffStatusDAO = diffStatus(startStatus, endStatus);
                                    rsDAO.setMapExtendResult(
                                            MySQLExtensionViewDialog.MYSQL_EXTENSION_VIEW.STATUS_VARIABLE
                                                    .name(),
                                            diffStatusDAO);

                                    // free profiling
                                    QueryUtils.executeQuery(tmpUserDB, "SET PROFILING = 0", 0, 10);

                                    // EXECUTE_PLAN
                                    if (!(StringUtils.startsWithIgnoreCase(
                                            StringUtils.trimToEmpty(reqQuery.getSql()), "SET")
                                            || StringUtils.startsWithIgnoreCase(
                                                    StringUtils.trimToEmpty(reqQuery.getSql()), "CALL")
                                            || StringUtils.startsWithIgnoreCase(
                                                    StringUtils.trimToEmpty(reqQuery.getSql()), "SHOW"))) {
                                        try {
                                            QueryExecuteResultDTO queryPlanDAO = ExecuteQueryPlan
                                                    .runSQLExplainPlan(getUserDB(), reqQuery, strPlanTBName);
                                            rsDAO.setMapExtendResult(
                                                    MySQLExtensionViewDialog.MYSQL_EXTENSION_VIEW.EXECUTE_PLAN
                                                            .name(),
                                                    queryPlanDAO);
                                        } catch (Exception e) {
                                            logger.error("MySQL Profiling execute plan", e);
                                        }
                                    }

                                } else {
                                    rsDAO = runSelect(reqQuery, queryTimeOut, strUserEmail, intSelectLimitCnt,
                                            0);
                                    listRSDao.add(rsDAO);
                                }
                            } else {
                                rsDAO = runSelect(reqQuery, queryTimeOut, strUserEmail, intSelectLimitCnt, 0);
                                listRSDao.add(rsDAO);
                            }

                            //  .
                            if (rsDAO == null || rsDAO.getDataList() == null) {
                                reqResultDAO.setRows(0);
                            } else {
                                reqResultDAO.setRows(rsDAO.getDataList().getData().size());
                            }
                            //DBMS_OUTPUT ? ?   History?  ?? .
                            reqResultDAO.setMesssage(rsDAO.getQueryMsg());
                        }
                    } else if (TransactionManger.isTransaction(reqQuery.getSql())) {
                        if (TransactionManger.isStartTransaction(reqQuery.getSql())) {
                            startTransactionMode();
                            reqQuery.setAutoCommit(false);
                        } else {
                            TransactionManger.calledCommitOrRollback(reqQuery.getSql(), strUserEmail,
                                    getUserDB());
                        }
                    } else {
                        ExecuteOtherSQL.runPermissionSQLExecution(errMsg, reqQuery, getUserDB(),
                                getDbUserRoleType(), strUserEmail);
                    }
                }

            } catch (Exception e) {
                reqResultDAO.setResult(PublicTadpoleDefine.SUCCESS_FAIL.F.name()); //$NON-NLS-1$
                reqResultDAO.setMesssage(e.getMessage());

                return new Status(Status.WARNING, Activator.PLUGIN_ID, e.getMessage(), e);
            } finally {
                reqResultDAO.setEndDateExecute(new Timestamp(System.currentTimeMillis()));
                monitor.done();
            }

            /////////////////////////////////////////////////////////////////////////////////////////
            return Status.OK_STATUS;
        }

        /**
         * MYSQL get Last query id
         * 
         * @param query id
         * @return
         */
        private String getLastQueryID(QueryExecuteResultDTO showProfiles) {
            List<Map<Integer, Object>> listShowProfiles = showProfiles.getDataList().getData();
            Map<Integer, Object> mapLastData = listShowProfiles.get(listShowProfiles.size() - 2);

            return "" + mapLastData.get(0);
        }

        /**
         * MYSQL Diffrent show status 
         * 
         * @param startStatus
         * @param endStatus
         * @return
         */
        private QueryExecuteResultDTO diffStatus(QueryExecuteResultDTO startStatus,
                QueryExecuteResultDTO endStatus) {
            List<Map<Integer, Object>> trsStart = startStatus.getDataList().getData();
            List<Map<Integer, Object>> trsEnd = endStatus.getDataList().getData();

            QueryExecuteResultDTO renewDiffObject = new QueryExecuteResultDTO();

            // setting column type
            Map<Integer, Integer> columnType = new HashMap<>();
            columnType.put(0, java.sql.Types.VARCHAR);
            columnType.put(1, java.sql.Types.DOUBLE);
            renewDiffObject.setColumnType(columnType);
            ;

            // setting column label name
            Map<Integer, String> columnLabelName = new HashMap<>();
            columnLabelName.put(0, "variable");
            columnLabelName.put(1, "value");
            renewDiffObject.setColumnName(columnLabelName);

            TadpoleResultSet dataList = new TadpoleResultSet();
            List<Map<Integer, Object>> diffData = new ArrayList<>();
            for (int i = 0; i < trsStart.size(); i++) {
                Map<Integer, Object> mapStartObject = trsStart.get(i);
                Map<Integer, Object> mapEndObject = trsEnd.get(i);

                // ? ? ?  ..
                if (!NumberUtils.isNumber("" + mapStartObject.get(1)))
                    continue;

                // ?? ?  .
                if (!StringUtils.equals("" + mapStartObject.get(1), "" + mapEndObject.get(1))) {
                    Map<Integer, Object> mapData = new HashMap<>();
                    mapData.put(0, mapStartObject.get(0));

                    Long longDiff = NumberUtils.createLong("" + mapEndObject.get(1))
                            - NumberUtils.createLong("" + mapStartObject.get(1));
                    mapData.put(1, longDiff);

                    diffData.add(mapData);
                }
            }
            dataList.getData().addAll(diffData);
            renewDiffObject.setDataList(dataList);

            return renewDiffObject;
        }
    };

    // job? event  ?.
    jobQueryManager.addJobChangeListener(new JobChangeAdapter() {
        public void done(IJobChangeEvent event) {
            final IJobChangeEvent jobEvent = event;

            getRdbResultComposite().getSite().getShell().getDisplay().asyncExec(new Runnable() {
                public void run() {
                    //     .
                    reqQuery.setResultDao(reqResultDAO);

                    //  ??   ?? ,  ,  ??? .
                    if (jobEvent.getResult().isOK()) {
                        executeFinish(reqQuery, listRSDao);
                    } else {
                        executeErrorProgress(reqQuery, jobEvent.getResult().getException(),
                                jobEvent.getResult().getMessage());
                        getRdbResultComposite().getMainEditor()
                                .browserEvaluateToStr(EditorFunctionService.SET_SELECTED_TEXT); //$NON-NLS-1$
                    }

                    //  ? .
                    getRdbResultComposite().getCompositeQueryHistory().afterQueryInit(reqResultDAO);

                    //    ??? .
                    finallyEndExecuteCommand(listRSDao);
                }
            }); // end display.asyncExec
        } // end done

    }); // end job

    jobQueryManager.setPriority(Job.INTERACTIVE);
    jobQueryManager.setName(getUserDB().getDisplay_name() + reqQuery.getOriginalSql());
    jobQueryManager.schedule();

    return true;
}

From source file:eionet.cr.staging.exp.ExportRunner.java

/**
 *
 * @param query/*from ww  w . ja  v a 2 s.c  o m*/
 * @param offset
 * @param limit
 * @return
 * @throws DAOException
 */
private String buildPageQuery(String query, int offset, int limit) throws DAOException {

    String trimmedQuery = query.trim();
    if (!StringUtils.startsWithIgnoreCase(trimmedQuery, "SELECT")) {
        throw new DAOException("Was expecting the query to strat with a 'SELECT' statement!");
    }

    String resultQuery = new StringBuilder().append(String.format("SELECT TOP %d,%d * FROM (", offset, limit))
            .append(query.trim()).append(") as QRY").toString();
    return resultQuery;
}

From source file:adalid.util.meta.sql.MetaPlatformSql.java

private String getTemplate(File propertiesFile) {
    String slashedPath;/*w w w  .  ja v  a2  s  . c o m*/
    String shortestPath = null;
    String propertiesFilePath = propertiesFile.getPath().replace(FILE_SEPARATOR, "/");
    String[] velocityFileResourceLoaderPathArray = VelocityEngineer.getFileResourceLoaderPathArray();
    if (velocityFileResourceLoaderPathArray != null && velocityFileResourceLoaderPathArray.length > 0) {
        for (String path : velocityFileResourceLoaderPathArray) {
            slashedPath = path.replace(FILE_SEPARATOR, "/");
            if (StringUtils.startsWithIgnoreCase(propertiesFilePath, slashedPath)) {
                if (shortestPath == null || slashedPath.length() < shortestPath.length()) {
                    shortestPath = slashedPath;
                }
            }
        }
    }
    if (shortestPath == null) {
        return propertiesFile.getName();
    }
    String template = StringUtils.removeStartIgnoreCase(propertiesFilePath, shortestPath);
    return StringUtils.removeStartIgnoreCase(template, "/");
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private void processDigestChallenge(AuthCache authCache, HttpHost target, Credentials credentials,
        HttpRequest request, HttpContext context) throws AuthenticationException {
    Header authHeader = request.getFirstHeader("Authorization");
    /*/* w  ww .ja va2s  .com*/
     * Since we're going to be replacing the header, we remove it here. If the header is invalid
     * or the challenge fails, we still want to remove the header, because otherwise it will
     * interfere with reactive authentication.
     */
    request.removeHeaders("Authorization");

    if (authHeader != null) {
        String authValue = authHeader.getValue();

        // The Authorization header value will be in the form: Digest param1="value1", param2="value2"
        if (StringUtils.startsWithIgnoreCase(authValue, AuthSchemes.DIGEST)) {
            DigestScheme digestScheme = new DigestScheme();

            // Get the actual parameters by stripping off the "Digest"
            authValue = StringUtils.removeStartIgnoreCase(authValue, AuthSchemes.DIGEST).trim();
            Matcher matcher = AUTH_HEADER_PATTERN.matcher(authValue);

            while (matcher.find()) {
                // We found a param="value" group
                String group = matcher.group();
                int index = group.indexOf('=');
                String name = group.substring(0, index).trim();
                String value = group.substring(index + 1).trim();

                // Strip off any quotes in the value
                if (value.startsWith("\"")) {
                    value = value.substring(1);
                }
                if (value.endsWith("\"")) {
                    value = value.substring(0, value.length() - 1);
                }

                logger.debug("Overriding Digest Parameter: " + name + "=\"" + value + "\"");
                digestScheme.overrideParamter(name, value);
            }

            // Since this is preemptive, we need to actually process the challenge beforehand
            request.addHeader(digestScheme.authenticate(credentials, request, context));
            authCache.put(target, digestScheme);
        }
    }
}

From source file:com.hangum.tadpole.rdb.core.editors.main.MainEditor.java

/**
 * execute query/*  w w  w  . j  a va  2 s  .co  m*/
 * 
 * @param reqQuery
 */
public void executeCommand(final RequestQuery reqQuery) {
    //   . 
    if (StringUtils.isEmpty(reqQuery.getSql()))
        return;

    String strCheckSQL = SQLUtil.removeCommentAndOthers(userDB, reqQuery.getSql());
    if (StringUtils.startsWithIgnoreCase(strCheckSQL, "desc ")) {
        String strObject = StringUtils.removeStartIgnoreCase(strCheckSQL, "desc ");
        DialogUtil.popupDMLDialog(getUserDB(), strObject);
    } else {
        resultMainComposite.executeCommand(reqQuery);
    }

    // google analytic
    AnalyticCaller.track(MainEditor.ID, "executeCommand"); //$NON-NLS-1$
}