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

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

Introduction

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

Prototype

public static String remove(String str, char remove) 

Source Link

Document

Removes all occurrences of a character from within the source string.

Usage

From source file:edu.cornell.med.icb.goby.R.FisherExact.java

/**
 * Pass the fisher expression to R for computation.
 *
 * @param rengine          The R engine to use to calcuate the results.
 * @param fisherExpression The string representing the expression to evaluate.
 * @param is2x2matrix      Whether or not the data being evaluated represents a 2x2 matrix
 * @return The results of the evaluation (may be null if an exception interrupts the calculation)
 *///from   w w w  .  j  a v  a2  s. c  o m
private static Result evaluateFisherExpression(final Rengine rengine, final String fisherExpression,
        final boolean is2x2matrix) {
    // evaluate the R expression
    if (LOG.isDebugEnabled()) {
        LOG.debug("About to evaluate: " + fisherExpression);
    }
    final REXP fisherResultExpression = rengine.eval(fisherExpression);
    if (LOG.isDebugEnabled()) {
        LOG.debug(fisherResultExpression);
    }
    if (fisherResultExpression == null) {
        return null;
    }
    // the result from R is a vector/map of values
    final RVector fisherResultVector = fisherResultExpression.asVector();
    if (LOG.isDebugEnabled()) {
        LOG.debug(fisherResultVector);
    }

    // extract the p-value
    final REXP pValueExpression = fisherResultVector.at("p.value");
    final double pValue;
    if (pValueExpression != null) {
        pValue = pValueExpression.asDouble();
    } else {
        pValue = Double.NaN;
    }

    // extract the alternative hypothesis
    final REXP alternativeExpression = fisherResultVector.at("alternative");
    final String alternative = alternativeExpression.asString();
    if (LOG.isDebugEnabled()) {
        LOG.debug("alternative: " + alternative);
    }
    final AlternativeHypothesis alternativeHypothesis = AlternativeHypothesis
            .valueOf(StringUtils.remove(alternative, '.'));

    // some values are only returned when the input was a 2x2 matrix
    final double estimate;
    final double[] confidenceInterval;
    final double oddsRatio;

    if (is2x2matrix) {
        final REXP estimateExpression = fisherResultVector.at("estimate");
        if (estimateExpression != null) {
            estimate = estimateExpression.asDouble();
        } else {
            estimate = Double.NaN;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug(estimateExpression);
            LOG.debug("estimate: " + estimate);
        }

        final REXP confidenceIntervalExpression = fisherResultVector.at("conf.int");
        if (confidenceIntervalExpression != null) {
            confidenceInterval = confidenceIntervalExpression.asDoubleArray();
        } else {
            confidenceInterval = ArrayUtils.EMPTY_DOUBLE_ARRAY;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug(confidenceIntervalExpression);
            LOG.debug("confidenceInterval: " + ArrayUtils.toString(confidenceInterval));
        }

        final REXP oddsRatioExpression = fisherResultVector.at("null.value");
        if (oddsRatioExpression != null) {
            oddsRatio = oddsRatioExpression.asDouble();
        } else {
            oddsRatio = Double.NaN;
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug(oddsRatioExpression);
            LOG.debug("oddsRatio: " + ArrayUtils.toString(oddsRatio));
        }
    } else {
        // these values are not present in the 2xN case
        estimate = Double.NaN;
        confidenceInterval = ArrayUtils.EMPTY_DOUBLE_ARRAY;
        oddsRatio = Double.NaN;
    }

    return new Result(pValue, confidenceInterval, estimate, oddsRatio, alternativeHypothesis);
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.GeoCleanupFuzzySearch.java

/**
 * @param name//from   ww  w  .  ja v a2s.  c om
 * @return
 */
protected static String stripExtrasFromName(final String name) {
    String sName = name;
    for (int i = 0; i < replaceNames.length; i += 2) {
        sName = StringUtils.replace(sName.trim(), replaceNames[i], replaceNames[i + 1]);
    }
    for (String extraStr : removeStrs) {
        sName = StringUtils.remove(sName.trim(), extraStr);
    }
    for (String replStr : replaceStrs) {
        sName = StringUtils.replace(sName.trim(), replStr, " ");
    }
    sName = kSpecialCharsPattern.matcher(sName).replaceAll(" ").trim();

    while (sName.contains("  ")) {
        sName = StringUtils.replace(sName.trim(), "  ", " ");
    }
    return sName;
}

From source file:com.doculibre.constellio.wicket.panels.results.DefaultSearchResultPanel.java

public DefaultSearchResultPanel(String id, SolrDocument doc, final SearchResultsDataProvider dataProvider) {
    super(id);/*from   w  w w.  j  a  va 2s.com*/

    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
    SearchInterfaceConfigServices searchInterfaceConfigServices = ConstellioSpringUtils
            .getSearchInterfaceConfigServices();

    String collectionName = dataProvider.getSimpleSearch().getCollectionName();

    RecordCollection collection = collectionServices.get(collectionName);
    Record record = recordServices.get(doc);
    if (record != null) {
        SearchInterfaceConfig searchInterfaceConfig = searchInterfaceConfigServices.get();

        IndexField uniqueKeyField = collection.getUniqueKeyIndexField();
        IndexField defaultSearchField = collection.getDefaultSearchIndexField();
        IndexField urlField = collection.getUrlIndexField();
        IndexField titleField = collection.getTitleIndexField();

        if (urlField == null) {
            urlField = uniqueKeyField;
        }
        if (titleField == null) {
            titleField = urlField;
        }

        final String recordURL = record.getUrl();
        final String displayURL;

        if (record.getDisplayUrl().startsWith("/get?file=")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            displayURL = ContextUrlUtils.getContextUrl(req) + record.getDisplayUrl();

        } else {
            displayURL = record.getDisplayUrl();
        }

        String title = record.getDisplayTitle();

        final String protocol = StringUtils.substringBefore(displayURL, ":");
        boolean linkEnabled = isLinkEnabled(protocol);

        // rcupration des champs highlight  partir de la cl unique
        // du document, dans le cas de Nutch c'est l'URL
        QueryResponse response = dataProvider.getQueryResponse();
        Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
        Map<String, List<String>> fieldsHighlighting = highlighting.get(recordURL);

        String titleHighlight = getTitleFromHighlight(titleField.getName(), fieldsHighlighting);
        if (titleHighlight != null) {
            title = titleHighlight;
        }

        String excerpt = null;
        String description = getDescription(record);
        String summary = getSummary(record);

        if (StringUtils.isNotBlank(description) && searchInterfaceConfig.isDescriptionAsExcerpt()) {
            excerpt = description;
        } else {
            excerpt = getExcerptFromHighlight(defaultSearchField.getName(), fieldsHighlighting);
            if (excerpt == null) {
                excerpt = description;
            }
        }

        toggleSummaryLink = new WebMarkupContainer("toggleSummaryLink");
        add(toggleSummaryLink);
        toggleSummaryLink.setVisible(StringUtils.isNotBlank(summary));
        toggleSummaryLink.add(new AttributeModifier("onclick", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                return "toggleSearchResultSummary('" + summaryLabel.getMarkupId() + "')";
            }
        }));

        summaryLabel = new Label("summary", summary);
        add(summaryLabel);
        summaryLabel.setOutputMarkupId(true);
        summaryLabel.setVisible(StringUtils.isNotBlank(summary));

        ExternalLink titleLink;
        if (displayURL.startsWith("file://")) {
            HttpServletRequest req = ((WebRequest) getRequest()).getHttpServletRequest();
            String newDisplayURL = ContextUrlUtils.getContextUrl(req) + "app/getSmbFile?"
                    + SmbServletPage.RECORD_ID + "=" + record.getId() + "&" + SmbServletPage.COLLECTION + "="
                    + collectionName;
            titleLink = new ExternalLink("titleLink", newDisplayURL);
        } else {
            titleLink = new ExternalLink("titleLink", displayURL);
        }

        final RecordModel recordModel = new RecordModel(record);
        AttributeModifier computeClickAttributeModifier = new AttributeModifier("onmousedown", true,
                new LoadableDetachableModel() {
                    @Override
                    protected Object load() {
                        Record record = recordModel.getObject();
                        SimpleSearch simpleSearch = dataProvider.getSimpleSearch();
                        WebRequest webRequest = (WebRequest) RequestCycle.get().getRequest();
                        HttpServletRequest httpRequest = webRequest.getHttpServletRequest();
                        return ComputeSearchResultClickServlet.getCallbackJavascript(httpRequest, simpleSearch,
                                record);
                    }
                });
        titleLink.add(computeClickAttributeModifier);
        titleLink.setEnabled(linkEnabled);

        boolean resultsInNewWindow;
        PageParameters params = RequestCycle.get().getPageParameters();
        if (params != null && params.getString(POPUP_LINK) != null) {
            resultsInNewWindow = params.getBoolean(POPUP_LINK);
        } else {
            resultsInNewWindow = searchInterfaceConfig.isResultsInNewWindow();
        }
        titleLink.add(new SimpleAttributeModifier("target", resultsInNewWindow ? "_blank" : "_self"));

        // Add title
        title = StringUtils.remove(title, "\n");
        title = StringUtils.remove(title, "\r");
        if (StringUtils.isEmpty(title)) {
            title = StringUtils.defaultString(displayURL);
            title = StringUtils.substringAfterLast(title, "/");
            title = StringUtils.substringBefore(title, "?");
            try {
                title = URLDecoder.decode(title, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (title.length() > 120) {
                title = title.substring(0, 120) + " ...";
            }
        }

        Label titleLabel = new Label("title", title);
        titleLink.add(titleLabel.setEscapeModelStrings(false));
        add(titleLink);

        Label excerptLabel = new Label("excerpt", excerpt);
        add(excerptLabel.setEscapeModelStrings(false));
        // add(new ExternalLink("url", url,
        // url).add(computeClickAttributeModifier).setEnabled(linkEnabled));
        if (displayURL.startsWith("file://")) {
            // Creates a Windows path for file URLs
            String urlLabel = StringUtils.substringAfter(displayURL, "file:");
            urlLabel = StringUtils.stripStart(urlLabel, "/");
            urlLabel = "\\\\" + StringUtils.replace(urlLabel, "/", "\\");
            try {
                urlLabel = URLDecoder.decode(urlLabel, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            add(new Label("url", urlLabel));
        } else {
            add(new Label("url", displayURL));
        }

        final ReloadableEntityModel<RecordCollection> collectionModel = new ReloadableEntityModel<RecordCollection>(
                collection);
        add(new ListView("searchResultFields", new LoadableDetachableModel() {
            @Override
            protected Object load() {
                RecordCollection collection = collectionModel.getObject();
                return collection.getSearchResultFields();
            }

            /**
             * Detaches from the current request. Implement this method with
             * custom behavior, such as setting the model object to null.
             */
            protected void onDetach() {
                recordModel.detach();
                collectionModel.detach();
            }
        }) {
            @Override
            protected void populateItem(ListItem item) {
                SearchResultField searchResultField = (SearchResultField) item.getModelObject();
                IndexFieldServices indexFieldServices = ConstellioSpringUtils.getIndexFieldServices();
                Record record = recordModel.getObject();
                IndexField indexField = searchResultField.getIndexField();
                Locale locale = getLocale();
                String indexFieldTitle = indexField.getTitle(locale);
                if (StringUtils.isBlank(indexFieldTitle)) {
                    indexFieldTitle = indexField.getName();
                }
                StringBuffer fieldValueSb = new StringBuffer();
                List<Object> fieldValues = indexFieldServices.extractFieldValues(record, indexField);
                Map<String, String> defaultLabelledValues = indexFieldServices
                        .getDefaultLabelledValues(indexField, locale);
                for (Object fieldValue : fieldValues) {
                    if (fieldValueSb.length() > 0) {
                        fieldValueSb.append("\n");
                    }
                    String fieldValueLabel = indexField.getLabelledValue("" + fieldValue, locale);
                    if (fieldValueLabel == null) {
                        fieldValueLabel = defaultLabelledValues.get("" + fieldValue);
                    }
                    if (fieldValueLabel == null) {
                        fieldValueLabel = "" + fieldValue;
                    }
                    fieldValueSb.append(fieldValueLabel);
                }

                item.add(new Label("indexField", indexFieldTitle));
                item.add(new MultiLineLabel("indexFieldValue", fieldValueSb.toString()));
                item.setVisible(fieldValueSb.length() > 0);
            }

            @SuppressWarnings("unchecked")
            @Override
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    List<SearchResultField> searchResultFields = (List<SearchResultField>) getModelObject();
                    visible = !searchResultFields.isEmpty();
                }
                return visible;
            }
        });

        // md5
        ConstellioSession session = ConstellioSession.get();
        ConstellioUser user = session.getUser();
        // TODO Provide access to unauthenticated users ?
        String md5 = "";
        if (user != null) {
            IntelliGIDServiceInfo intelligidServiceInfo = ConstellioSpringUtils.getIntelliGIDServiceInfo();
            if (intelligidServiceInfo != null) {
                Collection<Object> md5Coll = doc.getFieldValues(IndexField.MD5);
                if (md5Coll != null) {
                    for (Object md5Obj : md5Coll) {
                        try {
                            String md5Str = new String(Hex.encodeHex(Base64.decodeBase64(md5Obj.toString())));
                            InputStream is = HttpClientHelper
                                    .get(intelligidServiceInfo.getIntelligidUrl() + "/connector/checksum",
                                            "md5=" + URLEncoder.encode(md5Str, "ISO-8859-1"),
                                            "username=" + URLEncoder.encode(user.getUsername(), "ISO-8859-1"),
                                            "password=" + URLEncoder.encode(Base64.encodeBase64String(
                                                    ConstellioSession.get().getPassword().getBytes())),
                                            "ISO-8859-1");
                            try {
                                Document xmlDocument = new SAXReader().read(is);
                                Element root = xmlDocument.getRootElement();
                                for (Iterator<Element> it = root.elementIterator("fichier"); it.hasNext();) {
                                    Element fichier = it.next();
                                    String url = fichier.attributeValue("url");
                                    md5 += "<a href=\"" + url + "\">" + url + "</a> ";
                                }
                            } finally {
                                IOUtils.closeQuietly(is);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        Label md5Label = new Label("md5", md5) {
            public boolean isVisible() {
                boolean visible = super.isVisible();
                if (visible) {
                    visible = StringUtils.isNotBlank(this.getModelObjectAsString());
                }
                return visible;
            }
        };
        md5Label.setEscapeModelStrings(false);
        add(md5Label);

        add(new ElevatePanel("elevatePanel", record, dataProvider.getSimpleSearch()));
    } else {
        setVisible(false);
    }
}

From source file:hydrograph.ui.expression.editor.jar.util.BuildExpressionEditorDataSturcture.java

private void loadClassesFromSettingsFolder() {
    Properties properties = new Properties();
    IFolder folder = getCurrentProject().getFolder(PathConstant.PROJECT_RESOURCES_FOLDER);
    IFile file = folder.getFile(PathConstant.EXPRESSION_EDITOR_EXTERNAL_JARS_PROPERTIES_FILES);
    try {/*from   w ww . j  ava2s. com*/
        LOGGER.debug("Loading property file");
        if (file.getLocation().toFile().exists()) {
            FileInputStream inStream = new FileInputStream(file.getLocation().toString());
            properties.load(inStream);

            for (Object key : properties.keySet()) {
                String packageName = StringUtils.remove((String) key, Constants.DOT + Constants.ASTERISK);
                if (StringUtils.isNotBlank(properties.getProperty((String) key))
                        && StringUtils.isNotBlank(packageName)) {
                    loadUserDefinedClassesInClassRepo(properties.getProperty((String) key), packageName);
                }
            }
        }
    } catch (IOException | RuntimeException exception) {
        LOGGER.error("Exception occurred while loading jar files from projects setting folder", exception);
    }
}

From source file:io.ecarf.core.utils.LogParser.java

private double extractAndGetTimer(String line, String after, boolean ignoreMillis) {
    String timer = StringUtils.substringAfter(line, after);
    timer = StringUtils.remove(timer, ':');
    timer = StringUtils.trim(timer);//  ww  w.j a  va 2 s .  co  m

    return this.parseStopwatchTime(timer, ignoreMillis);
}

From source file:edu.ku.brc.specify.plugins.HostTaxonPlugin.java

/**
 * @return/*from  w  ww.  ja  va2 s  .c  o m*/
 */
protected ViewBasedSearchQueryBuilderIFace createSearchQueryBuilder() {
    return new ViewBasedSearchQueryBuilderIFace() {
        /* (non-Javadoc)
         * @see edu.ku.brc.af.ui.db.ViewBasedSearchQueryBuilderIFace#buildSQL(java.lang.String, boolean)
         */
        @Override
        public String buildSQL(String searchText, boolean isForCount) {
            String cols = isForCount ? "COUNT(*)" : "tx.fullName, tx.id";
            String sql = String.format(
                    "SELECT %s FROM Taxon tx INNER JOIN tx.definition ttd WHERE ttd.id = %d AND LOWER(tx.fullName) LIKE '%c%s%c' ORDER BY tx.fullName",
                    cols, taxonTreeDef.getId(), '%', searchText, '%');

            //System.out.println("adjustSQLTemplate: "+sql.toString());
            return sql;
        }

        /* (non-Javadoc)
         * @see edu.ku.brc.af.ui.db.ViewBasedSearchQueryBuilderIFace#buildSQL(java.util.Map, java.util.List)
         */
        @Override
        public String buildSQL(Map<String, Object> dataMap, List<String> fieldNames) {
            String orderBy = "";
            String fullName = (String) dataMap.get("taxon.FullName");
            if (StringUtils.isNotEmpty(fullName)) {
                fullName = StringUtils.remove(fullName, '#');
                fullName = StringUtils.remove(fullName, '*');
                if (StringUtils.isNotEmpty(fullName)) {
                    orderBy = "FullName";
                    fullName = String.format("LOWER(FullName) LIKE '%c%s%c'", '%', fullName.toLowerCase(), '%');
                }
            }

            String common = (String) dataMap.get("taxon.CommonName");
            if (StringUtils.isNotEmpty(common)) {
                common = StringUtils.remove(common, '#');
                common = StringUtils.remove(common, '*');
                if (StringUtils.isNotEmpty(common)) {
                    common = (StringUtils.isNotEmpty(fullName) ? " OR " : "")
                            + String.format("LOWER(CommonName) LIKE '%c%s%c'", '%', common.toLowerCase(), '%');
                    if (StringUtils.isEmpty(orderBy)) {
                        orderBy = "CommonName";
                    }
                }
            }

            if ("".equals(orderBy)) {
                orderBy = "FullName";
            }
            String where = (fullName == null ? "" : fullName) + " " + (common == null ? "" : common);
            if (!"".equals(where.trim())) {
                where = " AND (" + where + ")";
            } else {
                where = "";
            }
            String sql = String.format(
                    "SELECT TaxonID, FullName, CommonName FROM taxon tx INNER JOIN taxontreedef ttd ON tx.TaxonTreeDefID = ttd.TaxonTreeDefID WHERE ttd.TaxonTreeDefID = %d %s ORDER BY %s",
                    taxonTreeDef.getId(), where, orderBy);
            //System.out.println(sql);
            return sql;
        }

        /* (non-Javadoc)
         * @see edu.ku.brc.af.ui.db.ViewBasedSearchQueryBuilderIFace#createQueryForIdResults()
         */
        @Override
        public QueryForIdResultsIFace createQueryForIdResults() {
            ExpressResultsTableInfo esTblInfo = ExpressSearchConfigCache.getTableInfoByName("TaxonSearch");
            return new TableSearchResults(
                    DBTableIdMgr.getInstance().getInfoById(CollectionObject.getClassTableId()),
                    esTblInfo.getCaptionInfo()); //true => is HQL
        }

    };
}

From source file:com.linkedin.pinot.index.writer.FixedByteWidthRowColDataFileWriterTest.java

@Test
public void testSpecialPaddingCharsForStringReaderWriter() throws Exception {
    for (int iter = 0; iter < 2; iter++) {
        char paddingChar = (iter == 0) ? '%' : '\0';
        final byte[] bytes1 = new byte[] { -17, -65, -67, -17, -65, -67, 32, 69, 120, 101, 99, 117, 116, 105,
                118, 101 };//from   w  ww  .  ja  v a2  s. c  o m
        final byte[] bytes2 = new byte[] { -17, -65, -68, 32, 99, 97, 108, 103, 97, 114, 121, 32, 106, 117, 110,
                107, 32, 114, 101, 109, 111, 118, 97, 108 };
        File file = new File("test_single_col_writer.dat");
        file.delete();
        int rows = 100;
        int cols = 1;
        String testString1 = new String(bytes1);
        String testString2 = new String(bytes2);
        System.out.println(Arrays.toString(bytes2));
        int stringColumnMaxLength = Math.max(testString1.getBytes().length, testString2.getBytes().length);
        int[] columnSizes = new int[] { stringColumnMaxLength };
        FixedByteSingleValueMultiColWriter writer = new FixedByteSingleValueMultiColWriter(file, rows, cols,
                columnSizes);
        String[] data = new String[rows];
        for (int i = 0; i < rows; i++) {
            String toPut = (i % 2 == 0) ? testString1 : testString2;
            final int padding = stringColumnMaxLength - toPut.getBytes().length;

            final StringBuilder bld = new StringBuilder();
            bld.append(toPut);
            for (int j = 0; j < padding; j++) {
                bld.append(paddingChar);
            }
            data[i] = bld.toString();
            writer.setString(i, 0, data[i]);
        }
        writer.close();
        PinotDataBuffer mmapBuffer = PinotDataBuffer.fromFile(file, ReadMode.mmap,
                FileChannel.MapMode.READ_ONLY, "testing");
        FixedByteSingleValueMultiColReader dataFileReader = new FixedByteSingleValueMultiColReader(mmapBuffer,
                rows, 1, new int[] { stringColumnMaxLength });
        for (int i = 0; i < rows; i++) {
            String stringInFile = dataFileReader.getString(i, 0);
            Assert.assertEquals(stringInFile, data[i]);
            Assert.assertEquals(StringUtils.remove(stringInFile, String.valueOf(paddingChar)),
                    StringUtils.remove(data[i], String.valueOf(paddingChar)));
        }
        file.delete();
    }
}

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

/**
 * db ?? ? ./*from w  w  w.  ja va  2 s  .c  om*/
 * 
 * @param userDB
 * @param isTest
 * @return
 */
private boolean checkDatabase(final UserDBDAO userDB, boolean isTest) {
    try {
        if (userDB.getDBDefine() == DBDefine.MONGODB_DEFAULT) {
            MongoConnectionManager.getInstance(userDB);

        } else if (userDB.getDBDefine() == DBDefine.TAJO_DEFAULT) {
            new TajoConnectionManager().connectionCheck(userDB);

        } else if (userDB.getDBDefine() == DBDefine.SQLite_DEFAULT) {
            String strFileLoc = StringUtils.difference(
                    StringUtils.remove(userDB.getDBDefine().getDB_URL_INFO(), "%s"), userDB.getUrl());
            File fileDB = new File(strFileLoc);
            if (fileDB.exists()) {
                List<String> strArr = FileUtils.readLines(fileDB);

                if (!StringUtils.contains(strArr.get(0), "SQLite format")) {
                    throw new SQLException("Doesn't SQLite files.");
                }
            }

        } else {
            SqlMapClient sqlClient = TadpoleSQLManager.getInstance(userDB);
            sqlClient.queryForList("connectionCheck", userDB.getDb()); //$NON-NLS-1$
        }

        return true;
    } catch (Exception e) {
        String errMsg = e.getMessage();

        // driver  ?  .
        try {
            Throwable cause = e.getCause().getCause();
            if (cause instanceof ClassNotFoundException) {
                errMsg = String.format(Messages.get().TadpoleTableComposite_driverMsg, userDB.getDbms_type(),
                        e.getMessage());
            }
        } catch (Exception ee) {
            // igonre exception
        }

        logger.error("DB Connecting... [url]" + userDB.getUrl(), e); //$NON-NLS-1$
        // If UserDBDao is not invalid, remove UserDBDao at internal cache
        TadpoleSQLManager.removeInstance(userDB);

        // mssql ??? ?  ?? ?.  .
        // https://github.com/hangum/TadpoleForDBTools/issues/512 
        if (!isTest) {// && loginInfo.getDBDefine() != DBDefine.MSSQL_DEFAULT) {
            TDBYesNoErroDialog dialog = new TDBYesNoErroDialog(getShell(), userDB.getDb() + " Test",
                    String.format(Messages.get().AbstractLoginComposite_3, errMsg));
            if (dialog.open() == IDialogConstants.OK_ID)
                return true;

        } else {
            TDBInfoDialog dialog = new TDBInfoDialog(getShell(), userDB.getDb() + " Test", errMsg);
            dialog.open();
        }

        return false;
    }
}

From source file:edu.scripps.fl.pubchem.promiscuity.PCPromiscuityOutput.java

public void compoundPromiscuityToXML(Map<Long, CompoundPromiscuityInfo> map, PCPromiscuityParameters params,
        File file) throws Exception {

    jsp = new JSProcessor();
    jsp.init();/*from  w w w  .  j  a va2 s  . c om*/
    try {

        InputStream is = getClass().getResourceAsStream("/compress.txt");
        jsp.setCodeSource(new InputStreamReader(is));

        String[] descriptorColumns = descriptorNames;
        List<Long> ids = params.getIds();

        URL url = getClass().getClassLoader().getResource("Result.xml");
        Document doc = new XMLDocument().readDocFromURL(url);

        Element root = doc.getRootElement();
        String db = params.getDatabase();
        String idString = "SID";
        if (db.equalsIgnoreCase("pccompound"))
            idString = "CID";
        for (Long id : ids) {
            Element result = root.addElement("Result");
            result.addElement(idString).addText(id.toString());

            CompoundPromiscuityInfo cpInfo = map.get(id);
            if (cpInfo == null)
                result.addElement("NoResults").addText("Error Processing this compound.");
            else {
                if (cpInfo.getOnHold())
                    result.addElement("OnHold").addText("True");
                else {
                    if (db.equalsIgnoreCase("pcsubstance")) {
                        Element CIDe = result.addElement("CID");
                        if (cpInfo.getCID() != null)
                            CIDe.addText(cpInfo.getCID().toString());
                    }

                    Map<String, Object> descriptors = cpInfo.getDescriptors();
                    Map<String, CategorizedFunctionalGroups> categorizedFGMap = cpInfo
                            .getCategorizedFunctionalGroupsMap();

                    Element descriptorsE = result.addElement("Descriptors");
                    for (String category : functionalGroupCategories) {
                        Element fgCategoryE = descriptorsE.addElement(category);
                        CategorizedFunctionalGroups cFGs = categorizedFGMap.get(category);
                        if (cFGs != null) {
                            List<FunctionalGroup> fgs = cFGs.getFunctionalGroups();
                            List<String> groups = new ArrayList<String>();
                            for (FunctionalGroup group : fgs) {
                                groups.add(group.getName());
                            }
                            fgCategoryE.addText(StringUtils.join(groups, ", "));
                        }
                    }
                    Element possibleFalse = descriptorsE.addElement("PossibleFalseAromaticityDetection");
                    if (cpInfo.isPossibleFalseAromaticityDetection())
                        possibleFalse.addText("true");

                    for (String cc : descriptorColumns) {
                        Element descriptorCC = descriptorsE.addElement(StringUtils.remove(cc, " "));
                        if (descriptors.get(cc) != null)
                            descriptorCC.addText(descriptors.get(cc).toString());
                    }

                    Element proteinsE = result.addElement("Proteins");
                    if (params.getPerProteinMode()) {
                        Map<Protein, Map<String, PromiscuityCount<?>>> proteinCounts = cpInfo
                                .getPerProteinCounts();
                        Set<Protein> proteins = proteinCounts.keySet();
                        for (Protein protein : proteins) {
                            Element proteinE = proteinsE.addElement("Protein");
                            proteinE.addElement("Name").addText(protein.getName());
                            Element promiscuityCountsE = proteinE.addElement("PromiscuityCounts");
                            addCounts(promiscuityCountsE, proteinCounts.get(protein), id, db);
                        }
                        Map<String, PromiscuityCount<?>> noProteinCounts = cpInfo.getNoProteinCounts();
                        Element noProtein = proteinsE.addElement("Protein");
                        noProtein.addElement("Name").addText("");
                        Element noProteinCountsE = noProtein.addElement("PromiscuityCounts");
                        addCounts(noProteinCountsE, noProteinCounts, id, db);
                        root.addAttribute("format", "protein");
                    } else {
                        Map<String, PromiscuityCount<?>> counts = cpInfo.getCounts();
                        Element allProteins = proteinsE.addElement("Protein");
                        allProteins.addElement("Name").addText("All Proteins");
                        Element allProteinCountsE = allProteins.addElement("PromiscuityCounts");
                        addCounts(allProteinCountsE, counts, id, db);
                        root.addAttribute("format", "compound");
                    }
                }
            }

        }
        new XMLDocument().write(doc, file);
        log.info("Finished writing xml to: " + file.getAbsolutePath());
    } finally {
        jsp.exit();
    }
}

From source file:io.ecarf.core.utils.LogParser.java

/**
 *  - Processing file: /tmp/wordnet_links.nt.gz.kryo.gz, dictionary items: 49382611, memory usage: 14.336268931627274GB, timer: 290.0 ms
 * /tmp/wikipedia_links_en.nt.gz.kryo.gz, dictionary items: 44, memory usage: 0.013648882508277893GB, timer: 2.636 s
 *                      START: Downloading file: interlanguage_links_chapters_en.nt.gz.kryo.gz, memory usage: 0.0GB
 * @param line/* w ww .ja  v  a2  s. com*/
 * @param after
 * @return
 */
private double[] extractAndGetMemoryDictionaryItems(String line) {
    double memory = 0;
    double items = 0;
    String memoryStr = null;

    if (line.contains(TIMER_PREFIX)) {
        memoryStr = StringUtils.substringBetween(line, MEM_USE, TIMER_PREFIX);

        if (line.contains(DIC_ITEMS)) {
            String itemsStr = StringUtils.trim(StringUtils.substringBetween(line, DIC_ITEMS, MEM_USE));

            items = Double.parseDouble(itemsStr);
        }

    } else {
        memoryStr = StringUtils.substringAfter(line, MEM_USE);
    }

    if (memoryStr != null) {
        memoryStr = StringUtils.remove(memoryStr, "GB");
        memoryStr = StringUtils.strip(memoryStr);
    }

    memory = Double.parseDouble(memoryStr);

    double[] values = new double[] { memory, items };
    return values;
}