List of usage examples for org.apache.commons.lang3 StringUtils removeEnd
public static String removeEnd(final String str, final String remove)
Removes a substring only if it is at the end of a source string, otherwise returns the source string.
A null source string will return null .
From source file:org.yamj.core.service.metadata.online.SearchEngineToolsTest.java
@Test public void roundTripIMDB() { LOG.info("roundTripIMDB"); SearchEngineTools search = new SearchEngineTools(httpClient); // movie/*from ww w. j a v a2 s .c o m*/ for (int i = 0; i < search.countSearchSites(); i++) { String engine = search.getCurrentSearchEngine(); LOG.info("Testing " + engine); String url = search.searchURL("Avatar", 2009, "www.imdb.com/title", false); url = StringUtils.removeEnd(url, "/"); assertEquals("Search engine '" + engine + "' failed", "http://www.imdb.com/title/tt0499549", url); } // TV show, must leave out the year and search for TV series for (int i = 0; i < search.countSearchSites(); i++) { String engine = search.getCurrentSearchEngine(); LOG.info("Testing " + engine); String url = search.searchURL("Two and a Half Men", -1, "www.imdb.com/title", "TV series", false); url = StringUtils.removeEnd(url, "/"); assertEquals("Search engine '" + engine + "' failed", "http://www.imdb.com/title/tt0369179", url); } }
From source file:org.zanata.util.GlossaryUtil.java
/** * Generate qualifiedName from namespace and name. * e.g project/zanata, global/default//from www .j a v a2s . c o m * * {@link QUALIFIED_NAME_SEPARATOR} at the end of namespace will be removed. */ public static String generateQualifiedName(String namespace, String name) { String processedNamespace = StringUtils.removeEnd(namespace, QUALIFIED_NAME_SEPARATOR); return processedNamespace + QUALIFIED_NAME_SEPARATOR + name; }
From source file:pcgen.system.PluginClassLoader.java
private void loadClasses(final File pluginJar) throws IOException { try (JarClassLoader loader = new JarClassLoader(pluginJar.toURI().toURL()); ZipFile file = new ZipFile(pluginJar)) { final Collection<String> classList = new LinkedList<>(); Enumeration<? extends ZipEntry> entries = file.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String name = entry.getName(); if (!name.endsWith(".class")) { continue; }/*w w w.j a v a 2 s. c o m*/ name = StringUtils.removeEnd(name, ".class").replace('/', '.'); int size = (int) entry.getSize(); byte[] buffer = new byte[size]; InputStream in = file.getInputStream(entry); int rb = 0; int chunk; while ((size - rb) > 0) { chunk = in.read(buffer, rb, size - rb); if (chunk == -1) { break; } rb += chunk; } in.close(); loader.storeClassDef(name, buffer); classList.add(name); } file.close(); /* * Loading files and loading classes can both be lengthy processes. This splits the tasks * so that class loading occurs in another thread thus allowing both processes to * operate at the same time. */ dispatcher.execute(new Runnable() { @Override public void run() { boolean pluginFound = false; for (final String string : classList) { try { pluginFound |= processClass(Class.forName(string, true, loader)); } catch (ClassNotFoundException | NoClassDefFoundError ex) { Logging.errorPrint("Error occurred while loading plugin: " + pluginJar.getName(), ex); } } if (!pluginFound) { Logging.log(Logging.WARNING, "Plugin not found in " + pluginJar.getName()); } progress++; setProgress(progress); } }); } }
From source file:se.trixon.jota.client.ui.editor.module.task.TaskSourceDestPanel.java
private void noAdditionalDirUpdate(boolean selected) { String path = sourcePanel.getPath(); while (path.endsWith("/")) { path = StringUtils.removeEnd(path, "/"); }//from w w w . j a v a 2s .com if (selected) { path = StringUtils.appendIfMissing(path, "/"); } sourcePanel.setPath(path); }
From source file:tectonicus.blockTypes.BlockRegistry.java
public void deserializeBlockstates() { List<BlockVariant> blockVariants = new ArrayList<>(); Enumeration<? extends ZipEntry> entries = zips.getBaseEntries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); if (entryName.contains("blockstates")) { ZipStackEntry zse = zips.getEntry(entryName); try { JSONObject obj = new JSONObject(FileUtils.loadJSON(zse.getInputStream())); JSONObject variants = obj.getJSONObject("variants"); Iterator<?> keys = variants.keys(); while (keys.hasNext()) { String key = (String) keys.next(); Object variant = variants.get(key); blockVariants.add(BlockVariant.deserializeVariant(key, variant)); }/*from w w w. j a v a 2 s .c o m*/ } catch (Exception e) { e.printStackTrace(); } String name = "minecraft:" + StringUtils.removeEnd(entryName.substring(entryName.lastIndexOf("/") + 1), ".json"); blockStates.put(name, blockVariants); } } }
From source file:ubic.gemma.core.analysis.expression.diff.GeneDifferentialExpressionServiceImpl.java
@Override public ExperimentalFactorValueObject configExperimentalFactorValueObject(ExperimentalFactor ef) { ExperimentalFactorValueObject efvo = new ExperimentalFactorValueObject(ef.getId()); efvo.setName(ef.getName());/*from ww w. j av a2 s .co m*/ efvo.setDescription(ef.getDescription()); Characteristic category = ef.getCategory(); if (category != null) { efvo.setCategory(category.getCategory()); efvo.setCategoryUri(category.getCategoryUri()); } Collection<FactorValue> fvs = ef.getFactorValues(); StringBuilder factorValuesAsString = new StringBuilder(StringUtils.EMPTY); for (FactorValue fv : fvs) { String fvName = fv.toString(); if (StringUtils.isNotBlank(fvName)) { factorValuesAsString.append(fvName).append(GeneDifferentialExpressionServiceImpl.FV_SEP); } } /* clean up the start and end of the string */ factorValuesAsString = new StringBuilder( StringUtils.remove(factorValuesAsString.toString(), ef.getName() + ":")); factorValuesAsString = new StringBuilder(StringUtils.removeEnd(factorValuesAsString.toString(), GeneDifferentialExpressionServiceImpl.FV_SEP)); /* * Preformat the factor name; due to Ext PropertyGrid limitations we can't do this on the client. */ efvo.setName(ef.getName() + " (" + StringUtils.abbreviate(factorValuesAsString.toString(), 50) + ")"); efvo.setFactorValues(factorValuesAsString.toString()); return efvo; }
From source file:ubic.gemma.core.analysis.report.DatabaseViewGeneratorImpl.java
private void generateDatasetView(Integer limit, Collection<ExpressionExperiment> experiments) throws IOException { DatabaseViewGeneratorImpl.log.info("Generating dataset summary view"); /*/*from w w w .j a va 2 s. c om*/ * Get handle to output file */ File file = this.getViewFile(DatabaseViewGeneratorImpl.DATASET_SUMMARY_VIEW_BASENAME); DatabaseViewGeneratorImpl.log.info("Writing to " + file); try (Writer writer = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file)))) { writer.write("GemmaDsId\tSource\tSourceAccession\tShortName\tName\tDescription\ttaxon\tManufacturer\n"); /* * Print out their names etc. */ int i = 0; for (ExpressionExperiment ee : experiments) { ee = expressionExperimentService.thawLite(ee); DatabaseViewGeneratorImpl.log.info("Processing: " + ee.getShortName()); String acc = ""; String source = ""; if (ee.getAccession() != null && ee.getAccession().getAccession() != null) { acc = ee.getAccession().getAccession(); source = ee.getAccession().getExternalDatabase().getName(); } Long gemmaId = ee.getId(); String shortName = ee.getShortName(); String name = ee.getName(); String description = ee.getDescription(); description = StringUtils.replaceChars(description, '\t', ' '); description = StringUtils.replaceChars(description, '\n', ' '); description = StringUtils.replaceChars(description, '\r', ' '); Taxon taxon = expressionExperimentService.getTaxon(ee); if (taxon == null) continue; Collection<ArrayDesign> ads = expressionExperimentService.getArrayDesignsUsed(ee); StringBuilder manufacturers = new StringBuilder(); // TODO could cache the arrayDesigns to make faster, thawing ad is time consuming for (ArrayDesign ad : ads) { ad = arrayDesignService.thawLite(ad); if (ad.getDesignProvider() == null) { DatabaseViewGeneratorImpl.log.debug("Array Design: " + ad.getShortName() + " has no design provoider assoicated with it. Skipping"); continue; } manufacturers.append(ad.getDesignProvider().getName()).append(","); } writer.write(String.format("%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", gemmaId, source, acc, shortName, name, description, taxon.getCommonName(), StringUtils.removeEnd(manufacturers.toString(), ","))); if (limit != null && (limit > 0 && ++i > limit)) break; } } }
From source file:ubic.gemma.core.analysis.report.DatabaseViewGeneratorImpl.java
private void generateDifferentialExpressionView(Integer limit, Collection<ExpressionExperiment> experiments) throws IOException { DatabaseViewGeneratorImpl.log.info("Generating dataset diffex view"); /*// w w w. j ava 2 s. c om * Get handle to output file */ File file = this.getViewFile(DatabaseViewGeneratorImpl.DATASET_DIFFEX_VIEW_BASENAME); DatabaseViewGeneratorImpl.log.info("Writing to " + file); try (Writer writer = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(file)))) { /* * For each gene that is differentially expressed, print out a line per contrast */ writer.write( "GemmaDsId\tEEShortName\tGeneNCBIId\tGemmaGeneId\tFactor\tFactorURI\tBaseline\tContrasting\tDirection\n"); int i = 0; for (ExpressionExperiment ee : experiments) { ee = expressionExperimentService.thawLite(ee); Collection<DifferentialExpressionAnalysis> results = differentialExpressionAnalysisService .getAnalyses(ee); if (results == null || results.isEmpty()) { DatabaseViewGeneratorImpl.log.warn("No differential expression results found for " + ee); continue; } //noinspection StatementWithEmptyBody // FIXME. Should probably skip for this purpose. if (results.size() > 1) { } DatabaseViewGeneratorImpl.log.info("Processing: " + ee.getShortName()); for (DifferentialExpressionAnalysis analysis : results) { analysis = this.differentialExpressionAnalysisService.thawFully(analysis); for (ExpressionAnalysisResultSet ears : analysis.getResultSets()) { // ears = differentialExpressionResultService.thawRawAndProcessed( ears ); FactorValue baselineGroup = ears.getBaselineGroup(); if (baselineGroup == null) { // log.warn( "No baseline defined for " + ee ); // interaction continue; } if (ExperimentalDesignUtils.isBatch(baselineGroup.getExperimentalFactor())) { continue; } String baselineDescription = ExperimentalDesignUtils.prettyString(baselineGroup); // Get the factor category name StringBuilder factorName = new StringBuilder(); StringBuilder factorURI = new StringBuilder(); for (ExperimentalFactor ef : ears.getExperimentalFactors()) { factorName.append(ef.getName()).append(","); if (StringUtils.isNotBlank(ef.getCategory().getCategoryUri())) { factorURI.append(ef.getCategory().getCategoryUri()).append(","); } } factorName = new StringBuilder(StringUtils.removeEnd(factorName.toString(), ",")); factorURI = new StringBuilder(StringUtils.removeEnd(factorURI.toString(), ",")); if (ears.getResults() == null || ears.getResults().isEmpty()) { DatabaseViewGeneratorImpl.log .warn("No differential expression analysis results found for " + ee); continue; } // Generate probe details for (DifferentialExpressionAnalysisResult dear : ears.getResults()) { if (dear == null) { DatabaseViewGeneratorImpl.log .warn("Missing results for " + ee + " skipping to next. "); continue; } if (dear.getCorrectedPvalue() == null || dear.getCorrectedPvalue() > DatabaseViewGeneratorImpl.THRESH_HOLD) continue; String formatted = this.formatDiffExResult(ee, dear, factorName.toString(), factorURI.toString(), baselineDescription); if (StringUtils.isNotBlank(formatted)) writer.write(formatted); } // dear loop } // ears loop } // analysis loop if (limit != null && (limit > 0 && ++i > limit)) break; } // EE loop } }
From source file:ubic.gemma.core.analysis.service.ExpressionDataFileServiceImpl.java
@Override public List<DifferentialExpressionAnalysisResult> analysisResultSetToString(ExpressionAnalysisResultSet ears, Map<Long, String[]> geneAnnotations, StringBuilder buf, Map<Long, StringBuilder> probe2String, List<DifferentialExpressionAnalysisResult> sortedFirstColumnOfResults) { if (sortedFirstColumnOfResults == null) { // Sort P values in ears (because 1st column) sortedFirstColumnOfResults = new ArrayList<>(ears.getResults()); Collections.sort(sortedFirstColumnOfResults, DifferentialExpressionAnalysisResultComparator.Factory.newInstance()); }// www . jav a2s .co m // Generate a description of the factors involved "factor1_factor2", trying to be R-friendly StringBuilder factorColumnName = new StringBuilder(); for (ExperimentalFactor ef : ears.getExperimentalFactors()) { factorColumnName.append(ef.getName().replaceAll("\\s+", "_")).append("_"); } factorColumnName = new StringBuilder( StringUtil.makeValidForR(StringUtils.removeEnd(factorColumnName.toString(), "_"))); // Generate headers buf.append("\tQValue_").append(factorColumnName); buf.append("\tPValue_").append(factorColumnName); // Generate probe details for (DifferentialExpressionAnalysisResult dear : ears.getResults()) { StringBuilder probeBuffer = new StringBuilder(); CompositeSequence cs = dear.getProbe(); // Make a hashMap so we can organize the data by probe with factors as columns // Need to cache the information until we have it organized in the correct format to write Long csid = cs.getId(); if (probe2String.containsKey(csid)) { probeBuffer = probe2String.get(csid); } else {// no entry for probe yet probeBuffer.append(cs.getName()); if (geneAnnotations.containsKey(csid)) { String[] annotationStrings = geneAnnotations.get(csid); /* * Fields: * * 1: gene symbols * 2: gene name * 4: ncbi ID */ probeBuffer.append("\t").append(annotationStrings[1]).append("\t").append(annotationStrings[2]) .append("\t").append(annotationStrings[4]); } else { probeBuffer.append("\t\t\t"); } probe2String.put(csid, probeBuffer); } Double correctedPvalue = dear.getCorrectedPvalue(); Double pvalue = dear.getPvalue(); String formattedCP = correctedPvalue == null ? "" : String.format(ExpressionDataFileServiceImpl.DECIMAL_FORMAT, correctedPvalue); String formattedP = pvalue == null ? "" : String.format(ExpressionDataFileServiceImpl.DECIMAL_FORMAT, pvalue); probeBuffer.append("\t").append(formattedCP).append("\t").append(formattedP); } return sortedFirstColumnOfResults; }
From source file:ubic.gemma.core.analysis.service.ExpressionDataFileServiceImpl.java
private String getFactorValueString(FactorValue fv) { String result;/*from w ww . j ava 2s. co m*/ if (fv == null) return "null"; if (fv.getCharacteristics() != null && fv.getCharacteristics().size() > 0) { StringBuilder fvString = new StringBuilder(); for (Characteristic c : fv.getCharacteristics()) { fvString.append(c.getValue()).append("_"); } result = StringUtils.removeEnd(fvString.toString(), "_"); } else if (fv.getMeasurement() != null) { result = fv.getMeasurement().getValue(); } else if (fv.getValue() != null && !fv.getValue().isEmpty()) { result = fv.getValue(); } else return "no_data"; // R-friendly, but no need to add "X" to the beginning since this is a suffix. return result.replaceAll("[\\W]+", "."); }