List of usage examples for org.apache.commons.lang3 StringUtils abbreviate
public static String abbreviate(final String str, final int maxWidth)
Abbreviates a String using ellipses.
From source file:tiwolij.service.wikidata.WikidataRepository.java
public String extractImageAttribution(Integer wikidataId) { String imageAttribution = null; String wikimediaImageinfo = env.getProperty("wikimedia.imageinfo"); String artist = "Unknown Artist"; String license = "Unspecified License"; try {//from ww w . j a v a 2 s . com WikibaseDataFetcher data = WikibaseDataFetcher.getWikidataDataFetcher(); ItemDocument item = (ItemDocument) data.getEntityDocument("Q" + wikidataId); if (item.hasStatement("P18")) { Value value = item.findStatementGroup("P18").getStatements().get(0).getValue(); String file = value.toString().replaceAll("^\"|\"$", "").replace(" ", "_"); URL url = new URL("https://" + wikimediaImageinfo + file); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(url.openStream()); Node artistNode = document.getElementsByTagName("Artist").item(0); Node licenseNode = document.getElementsByTagName("LicenseShortName").item(0); if (artistNode != null) { artist = artistNode.getAttributes().getNamedItem("value").getNodeValue(); artist = StringUtils.abbreviate(artist.replaceAll("\\<[^>]*>", ""), 100); } if (licenseNode != null) { license = licenseNode.getAttributes().getNamedItem("value").getNodeValue(); license = StringUtils.abbreviate(license.replaceAll("\\<[^>]*>", ""), 100); } imageAttribution = StringEscapeUtils.unescapeHtml4(artist) + " (" + StringEscapeUtils.unescapeHtml4(license) + ")"; } } catch (Exception e) { } return imageAttribution; }
From source file:tw.edu.chit.struts.action.course.ReportPrintAction.java
/** * ?/*from w w w .j a v a 2 s.com*/ * * @param mapping org.apache.struts.action.ActionMapping object * @param form org.apache.struts.action.ActionForm object * @param request request javax.servlet.http.HttpServletRequest object * @param response response javax.servlet.http.HttpServletResponse object * @param sterm */ @SuppressWarnings("unchecked") private void printCourseDataPrint(ActionMapping mapping, DynaActionForm form, HttpServletRequest request, HttpServletResponse response, String sterm) throws Exception { HttpSession session = request.getSession(false); AdminManager am = (AdminManager) getBean(IConstants.ADMIN_MANAGER_BEAN_NAME); MemberManager mm = (MemberManager) getBean(IConstants.MEMBER_MANAGER_BEAN_NAME); CourseManager cm = (CourseManager) getBean(IConstants.COURSE_MANAGER_BEAN_NAME); ScoreManager sm = (ScoreManager) getBean(IConstants.SCORE_MANAGER_BEAN_NAME); ServletContext context = request.getSession().getServletContext(); Integer year = cm.getSchoolYear(); List<Clazz> clazzes = sm.findClassBy(new Clazz(processClassInfo(form)), getUserCredential(session).getClassInChargeAry(), true); if (!clazzes.isEmpty()) { File templateXLS = new File(context.getRealPath("/WEB-INF/reports/CourseDataPrint.xls")); HSSFWorkbook workbook = Toolket.getHSSFWorkbook(templateXLS); HSSFFont fontSize12 = workbook.createFont(); fontSize12.setFontHeightInPoints((short) 12); fontSize12.setFontName("Arial Unicode MS"); HSSFSheet sheet = workbook.getSheetAt(0); Toolket.setCellValue(sheet, 0, 0, "?" + year + "?"); Toolket.setCellValue(sheet, 0, 30, "" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())); int index = 2, boys = 0, girls = 0; boolean flag = false; String departClass = null, optValue = null; Dtime dtime = null; Empl empl = null; Csno csno = null; List<Object> objs = null; List<DtimeTeacher> dtimeTeachers = null; List<String> csGroups = null; List<Student> stmds = null; Object[] data = null; String[] no = { "50000", "T0001", "T0002" }; String[] no1 = { "", "", "", "", "()", "()", "()", "()", "()", "()" }; String[] no2 = { "", "" }; String[] english = { "S0351", "S0352", "S0353", "S0391", "T0090", "T0350", "T0351", "T0352", "T0360", "T0B20", "TD890", "TG321", "TH821", "THQ20", "TP3W0", "TQ090" }; String[] japan = { "T0161" }; StringBuffer buffer = new StringBuffer(); String hql = "SELECT d, cs FROM Dtime d, Csno cs " + "WHERE d.cscode = cs.cscode " + "AND d.sterm = ? AND d.departClass = ?"; String hql1 = "SELECT DISTINCT cg.cname FROM CsGroup cg, CsGroupSet cs " + "WHERE cg.oid = cs.groupOid AND cs.cscode = ? ORDER BY cg.oid"; for (Clazz clazz : clazzes) { departClass = clazz.getClassNo(); if (Toolket.isDelayClass(departClass)) continue; objs = am.find(hql, new Object[] { sterm, departClass }, -1); for (Object o : objs) { data = (Object[]) o; dtime = (Dtime) data[0]; csno = (Csno) data[1]; stmds = cm.findSeldStudentByDtimeOid(dtime.getOid()); if (!ArrayUtils.contains(no, dtime.getCscode()) && !stmds.isEmpty()) { csGroups = am.find(hql1, new Object[] { dtime.getCscode() }, -1); if (csGroups.isEmpty()) Toolket.setCellValue(sheet, index, 0, ""); else { buffer = new StringBuffer(); for (String cg : csGroups) buffer.append(cg).append(","); Toolket.setCellValue(sheet, index, 0, StringUtils.substring(buffer.toString(), 0, buffer.toString().length() - 1)); // ?? } Toolket.setCellValue(sheet, index, 1, ""); // Toolket.setCellValue(sheet, index, 2, "D".equalsIgnoreCase(clazz.getSchoolType()) ? "0" : ("N".equalsIgnoreCase(clazz.getSchoolType()) ? "1" : "2")); // Toolket.setCellValue(sheet, index, 3, Toolket.getSchoolNoBy(clazz)); // / Toolket.setCellValue(sheet, index, 4, StringUtils.abbreviate(csno.getChiName(), 64)); // ?? Toolket.setCellValue(sheet, index, 5, StringUtils.abbreviate(Toolket.getDepartName(departClass), 25)); // Toolket.setCellValue(sheet, index, 6, ""); // Toolket.setCellValue(sheet, index, 7, "1"); // flag = false; for (String noValue : no1) { if (csno.getChiName().endsWith(noValue)) { flag = true; break; } } if (!flag) { for (String noValue : no2) { if (StringUtils.contains(csno.getChiName(), noValue)) { flag = true; break; } } } Toolket.setCellValue(sheet, index, 8, flag ? "1" : "0"); // ? optValue = "1".equals(dtime.getOpt()) ? "0" : ("2".equals(dtime.getOpt()) ? "1" : "3"); Toolket.setCellValue(sheet, index, 9, optValue); // ? Toolket.setCellValue(sheet, index, 10, dtime.getCredit().toString()); // Toolket.setCellValue(sheet, index, 11, dtime.getThour().toString()); // ? Toolket.setCellValue(sheet, index, 12, ""); // ? Toolket.setCellValue(sheet, index, 13, clazz.getGrade()); // Toolket.setCellValue(sheet, index, 14, clazz.getClassName()); // ? Toolket.setCellValue(sheet, index, 15, "http://www.cust.edu.tw/www/info/intro_en.php?coursenum=" + dtime.getOid()); // ? Toolket.setCellValue(sheet, index, 16, "http://www.cust.edu.tw/www/info/intro_obj.php?coursenum=" + dtime.getOid()); // Toolket.setCellValue(sheet, index, 17, ""); // ? buffer = new StringBuffer(); empl = mm.findEmplByIdno(dtime.getTechid()); if (empl != null) buffer.append(empl.getCname()).append(","); dtimeTeachers = cm.getDtimeTeacherBy(dtime.getOid().toString()); for (DtimeTeacher dt : dtimeTeachers) buffer.append(dt.getChiName2()).append(","); Toolket.setCellValue(sheet, index, 18, StringUtils.substring(buffer.toString(), 0, buffer.toString().length() - 1)); // ? Toolket.setCellValue(sheet, index, 19, ""); // Toolket.setCellValue(sheet, index, 20, ""); // if (ArrayUtils.contains(english, csno.getCscode())) { Toolket.setCellValue(sheet, index, 21, ""); // 1 Toolket.setCellValue(sheet, index, 22, ""); // 2 } else if (ArrayUtils.contains(japan, csno.getCscode())) { Toolket.setCellValue(sheet, index, 21, ""); // 1 Toolket.setCellValue(sheet, index, 22, ""); // 2 } else { Toolket.setCellValue(sheet, index, 21, ""); // 1 Toolket.setCellValue(sheet, index, 22, ""); // 2 } Toolket.setCellValue(sheet, index, 23, ""); // Toolket.setCellValue(sheet, index, 24, ""); // 1 Toolket.setCellValue(sheet, index, 25, ""); // 2 Toolket.setCellValue(sheet, index, 26, StringUtils.abbreviate(csno.getEngName(), 255)); // ?? Toolket.setCellValue(sheet, index, 27, "0"); // Toolket.setCellValue(sheet, index, 28, StringUtils.contains(csno.getChiName(), "") ? "2" : Toolket.getCourseStyleBy(dtime.getElearning())); // Toolket.setCellValue(sheet, index, 29, empl == null ? "" : Toolket.getTeacherSourceBy(empl.getUnit())); // ? boys = 0; girls = 0; for (Student student : stmds) { if ("1".equals(student.getSex())) boys++; else if ("2".equals(student.getSex())) girls++; } Toolket.setCellValue(sheet, index, 30, String.valueOf(boys)); // Toolket.setCellValue(sheet, index++, 31, String.valueOf(girls)); // } } } File tempDir = new File( context.getRealPath("/WEB-INF/reports/temp/" + getUserCredential(session).getMember().getIdno() + (new SimpleDateFormat("yyyyMMdd").format(new Date())))); if (!tempDir.exists()) tempDir.mkdirs(); File output = new File(tempDir, "CourseDataPrint.xls"); FileOutputStream fos = new FileOutputStream(output); workbook.write(fos); fos.close(); JasperReportUtils.printXlsToFrontEnd(response, output); output.delete(); tempDir.delete(); } else { Map<String, String> param = new HashMap<String, String>(); File image = new File(context.getRealPath("/pages/images/2002chitS.jpg")); param.put("IMAGE", image.getAbsolutePath()); byte[] bytes = JasperRunManager.runReportToPdf(JasperReportUtils.getNoResultReport(context), param, new JREmptyDataSource()); JasperReportUtils.printPdfToFrontEnd(response, bytes); } }
From source file:ubic.basecode.graphics.MatrixDisplay.java
/** * Pads a string to the maxColumnLength. If it is over the maxColumnLength, it abbreviates it to the maxColumnLength * //from w ww.jav a 2s .c om * @param str * @return */ private String padColumnString(String str) { String paddedstr = StringUtils.abbreviate(str, m_maxColumnLength); paddedstr = StringUtils.rightPad(str, m_maxColumnLength, " "); return paddedstr; }
From source file:ubic.basecode.io.reader.DoubleMatrixReader.java
/** * @param row//from w ww . j a v a2 s . c o m * @param rowNames * @param MTemp * @param wantedRowNames * @param skipColumns the number of columns after the first to ignore (for example, Gemma output that includes gene * information as well as numeric data) * @return * @throws IOException */ private String parseRow(String row, Collection<String> rowNames, List<DoubleArrayList> MTemp, Collection<String> wantedRowNames, int skipColumns) throws IOException { if (row.startsWith("#") || row.startsWith("!")) { return null; } String[] tokens = StringUtils.splitPreserveAllTokens(row, "\t"); DoubleArrayList rowTemp = new DoubleArrayList(); int columnNumber = 0; String previousToken = ""; String currentRowName = null; for (int i = 0; i < tokens.length; i++) { String tok = tokens[i]; boolean missing = false; if (tok.compareTo("\t") == 0) { /* two tabs in a row */ if (previousToken.compareTo("\t") == 0) { missing = true; } else if (i == tokens.length - 1) { // at end of line. missing = true; } else { previousToken = tok; continue; } } else if (StringUtils.isBlank(tok) || tok.compareTo("NaN") == 0 || tok.compareTo("NA") == 0) { missing = true; } if (columnNumber > 0) { if (skipColumns > 0 && columnNumber <= skipColumns) { // skip. } else if (missing) { rowTemp.add(Double.NaN); } else { try { /* * NumberFormat.parse thinks things like 9101001_at are okay. Try to catch such cases. Note that * we can't use Double.parseDouble because that doesn't seem to handle locale-specific number * formats like european decimals (0,001 etc.) */ // if ( tok.matches( ".*[a-zA-Z_=].*" ) ) { // throw new NumberFormatException( "Unexpected non-numeric value found in column " // + columnNumber + ": " + tok ); // } rowTemp.add(nf.parse(tok.toUpperCase()).doubleValue()); } catch (ParseException e) { throw new RuntimeException(e); } } } else { // First field is the row label. if (missing) { throw new IOException( "Missing values not allowed for row labels (" + StringUtils.abbreviate(row, 20) + ")"); } currentRowName = tok; // Skip rows. Return the row name anyway. if (wantedRowNames != null && !wantedRowNames.contains(currentRowName)) { return currentRowName; } rowNames.add(currentRowName); } columnNumber++; previousToken = tok; } // end while (st.hasMoreTokens()) // done parsing one row -- no more tokens if (rowTemp.size() > numHeadings) { throw new IOException("Too many values (" + rowTemp.size() + ") in row (based on headings count of " + numHeadings + ")"); } MTemp.add(rowTemp); return currentRowName; }
From source file:ubic.basecode.util.r.type.AnovaEffect.java
@Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(StringUtils.rightPad(StringUtils.abbreviate(getEffectName(), 10), 10) + "\t"); buf.append(String.format("%.2f", getDegreesOfFreedom()) + "\t"); buf.append(String.format("%.4f", getSsQ()) + "\t"); buf.append(String.format("%.4f", getMeanSq()) + "\t"); if (fStatistic != null) { buf.append(StringUtils.rightPad(String.format("%.3f", getFStatistic()), 6) + "\t"); buf.append(String.format("%.3g", getPValue())); }// w w w . j a va 2 s . com return buf.toString(); }
From source file:ubic.gemma.core.analysis.expression.coexpression.CoexpressionSearchCommand.java
@Override public String toString() { return "Genes=" + StringUtils.abbreviate(StringUtils.join(this.getGeneIds(), ","), 100) + " EESet=" + this.getEeSetId() + " QueryGenesOnly=" + this.getQueryGenesOnly() + " tax=" + this.getTaxonId() + (stringency > 1 ? " Stringency=" + stringency : "") + " ees=" + StringUtils.abbreviate(StringUtils.join(this.getEeIds(), ","), 100); }
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 w w w . j a v a 2 s.c o 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.preprocess.VectorMergingServiceImpl.java
/** * Create a new one or use an existing one. (an existing one might be found if this process was started once before * and aborted partway through)./*from ww w.jav a 2 s . co m*/ * * @param oldDims in the sort order to be used. * @return BA dim */ private BioAssayDimension combineBioAssayDimensions(List<BioAssayDimension> oldDims) { List<BioAssay> bioAssays = new ArrayList<>(); for (BioAssayDimension bioAd : oldDims) { for (BioAssay bioAssay : bioAd.getBioAssays()) { if (bioAssays.contains(bioAssay)) { throw new IllegalStateException("Duplicate bioassay for biodimension: " + bioAssay + "; inspecting " + oldDims.size() + " BioAssayDimensions"); } bioAssays.add(bioAssay); } } // first see if we already have an equivalent one. boolean found = true; for (BioAssayDimension newDim : oldDims) { // size should be the same. List<BioAssay> assaysInExisting = newDim.getBioAssays(); if (assaysInExisting.size() != bioAssays.size()) { continue; } for (int i = 0; i < bioAssays.size(); i++) { if (!assaysInExisting.get(i).equals(bioAssays.get(i))) { found = false; break; } } if (!found) continue; VectorMergingServiceImpl.log .info("Already have a dimension created that fits the bill - removing it from the 'old' list."); oldDims.remove(newDim); return newDim; } BioAssayDimension newBioAd = BioAssayDimension.Factory.newInstance(); newBioAd.setName(""); newBioAd.setDescription( VectorMergingServiceImpl.MERGED_DIM_DESC_PREFIX + " " + oldDims.size() + " dimensions: "); for (BioAssayDimension bioAd : oldDims) { newBioAd.setName(newBioAd.getName() + bioAd.getName() + " "); newBioAd.setDescription(newBioAd.getDescription() + bioAd.getName() + " "); } newBioAd.setName(StringUtils.abbreviate(newBioAd.getName(), 255)); newBioAd.setBioAssays(bioAssays); newBioAd = bioAssayDimensionService.create(newBioAd); VectorMergingServiceImpl.log .info("Created new bioAssayDimension with " + newBioAd.getBioAssays().size() + " bioassays."); return newBioAd; }
From source file:ubic.gemma.core.analysis.report.TwitterOutboundImpl.java
/** * Generate content for the tweet; exposed for testing. *//*ww w.j a v a 2s . c om*/ @Override public String generateDailyFeed() { Calendar c = Calendar.getInstance(); Date date = c.getTime(); date = DateUtils.addDays(date, -1); WhatsNew whatsNew = whatsNewService.getReport(date); Collection<ExpressionExperiment> experiments = new ArrayList<>(); int updatedExperimentsCount = 0; int newExperimentsCount = 0; Random rand = new Random(); // Query for all updated / new expression experiments to store into a experiments collection if (whatsNew != null) { Collection<ExpressionExperiment> updatedExperiments = whatsNew.getUpdatedExpressionExperiments(); Collection<ExpressionExperiment> newExperiments = whatsNew.getNewExpressionExperiments(); experiments.addAll(updatedExperiments); experiments.addAll(newExperiments); updatedExperimentsCount = updatedExperiments.size(); newExperimentsCount = newExperiments.size(); } ExpressionExperiment experiment; // Query latest experiments if there are no updated / new experiments if (updatedExperimentsCount == 0 && newExperimentsCount == 0) { Collection<ExpressionExperiment> latestExperiments = expressionExperimentService.findByUpdatedLimit(10); Collection<ExpressionExperiment> publicExperiments = securityService.choosePublic(latestExperiments); if (publicExperiments.isEmpty()) { TwitterOutboundImpl.log.warn("There are no valid experiments to tweet about"); return null; } experiment = (ExpressionExperiment) publicExperiments.toArray()[rand.nextInt(publicExperiments.size())]; } else { if (experiments.isEmpty()) { TwitterOutboundImpl.log.warn("There are no valid experiments to tweet about"); return null; } experiment = (ExpressionExperiment) experiments.toArray()[rand.nextInt(experiments.size())]; } assert experiment != null; String status = this.statusWithExperiment( StringUtils.abbreviate(experiment.getShortName() + ": " + experiment.getName(), 60), this.formExperimentUrl(experiment), updatedExperimentsCount, newExperimentsCount); return StringUtils.abbreviate(status, 140); // this will look a bit weird, and might chop off the url...but // have to ensure. }
From source file:ubic.gemma.core.datastructure.matrix.ExpressionDataDoubleMatrix.java
/** * Create a matrix given a 'raw' matrix that uses the same samples as the experiment. Only simple situations are * supported (one platform, not subsetting the dataset). * * @param ee to be associated with this//ww w . ja va 2 s . c o m * @param qt to be associated with this * @param matrix with valid row and column elements, and the data */ public ExpressionDataDoubleMatrix(ExpressionExperiment ee, QuantitationType qt, DoubleMatrix<CompositeSequence, BioMaterial> matrix) { if (ee == null) { throw new IllegalArgumentException("Experiment cannot be null"); } if (matrix.rows() == 0 || matrix.columns() == 0 || matrix.getRowNames().isEmpty() || matrix.getColNames().isEmpty()) { throw new IllegalArgumentException("Matrix is invalid"); } this.init(); this.expressionExperiment = ee; this.matrix = matrix; this.quantitationTypes.add(qt); BioAssayDimension dim = BioAssayDimension.Factory.newInstance(); List<BioAssay> bioassays = new ArrayList<>(); for (BioMaterial bm : matrix.getColNames()) { Collection<BioAssay> bioAssaysUsedIn = bm.getBioAssaysUsedIn(); if (bioAssaysUsedIn.size() > 1) { throw new UnsupportedOperationException( "Can't make new data from matrix that has multiple bioassays per biomaterial"); } BioAssay bioAssay = bioAssaysUsedIn.iterator().next(); if (!ee.getBioAssays().contains(bioAssay)) { throw new IllegalArgumentException("Bioassays in the matrix must match those in the experiment"); } bioassays.add(bioAssay); } if (bioassays.size() != ee.getBioAssays().size()) { throw new IllegalArgumentException("All bioassays in the experiment must be used in the matrix"); } dim.setBioAssays(bioassays); dim.setDescription("Built from matrix supplied to Constructor for " + ee + " from matrix"); dim.setName(StringUtils.abbreviate("For " + ee.getShortName() + " from matrix", 255)); assert !matrix.getRowNames().isEmpty(); int i = 0; for (CompositeSequence cs : matrix.getRowNames()) { bioAssayDimensions.put(cs, dim); this.addToRowMaps(i, cs); i++; } assert !bioAssayDimensions.isEmpty(); this.setUpColumnElements(); }