List of usage examples for org.apache.commons.lang StringUtils substring
public static String substring(String str, int start, int end)
Gets a substring from the specified String avoiding exceptions.
From source file:org.sakaiproject.assignment.tool.AssignmentAction.java
/** * Takes the inline submission, prepares it as an attachment to the submission and queues the attachment with the content review service *///ww w . ja va 2 s . co m private void prepareInlineForContentReview(String text, AssignmentSubmissionEdit edit, SessionState state, User student) { //We will be replacing the inline submission's attachment //firstly, disconnect any existing attachments with AssignmentSubmission.PROP_INLINE_SUBMISSION set List attachments = edit.getSubmittedAttachments(); List toRemove = new ArrayList(); Iterator itAttachments = attachments.iterator(); while (itAttachments.hasNext()) { Reference attachment = (Reference) itAttachments.next(); ResourceProperties attachProps = attachment.getProperties(); if ("true".equals(attachProps.getProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION))) { toRemove.add(attachment); } } Iterator itToRemove = toRemove.iterator(); while (itToRemove.hasNext()) { Reference attachment = (Reference) itToRemove.next(); edit.removeSubmittedAttachment(attachment); } //now prepare the new resource //provide lots of info for forensics - filename=InlineSub_assignmentId_userDisplayId_(for_studentDisplayId)_date.html User currentUser = UserDirectoryService.getCurrentUser(); String currentDisplayName = currentUser.getDisplayId(); String siteId = (String) state.getAttribute(STATE_CONTEXT_STRING); SimpleDateFormat dform = ((SimpleDateFormat) DateFormat.getDateInstance()); //avoid semicolons in filenames, right? dform.applyPattern("yyyy-MM-dd_HH-mm-ss"); StringBuilder sb_resourceId = new StringBuilder("InlineSub_"); String u = "_"; sb_resourceId.append(edit.getAssignmentId()).append(u).append(currentDisplayName).append(u); boolean isOnBehalfOfStudent = student != null && !student.equals(currentUser); if (isOnBehalfOfStudent) { // We're submitting on behalf of somebody sb_resourceId.append("for_").append(student.getDisplayId()).append(u); } sb_resourceId.append(dform.format(new Date())); String fileExtension = ".html"; /* * TODO: add and use a method in ContentHostingService to get the length of the ID of an attachment collection * Attachment collections currently look like this: * /attachment/dc126c4a-a48f-42a6-bda0-cf7b9c4c5c16/Assignments/eac7212a-9597-4b7d-b958-89e1c47cdfa7/ * See BaseContentService.addAttachmentResource for more information */ String toolName = "Assignments"; // TODO: add and use a method in IdManager to get the maxUuidLength int maxUuidLength = 36; int esl = Entity.SEPARATOR.length(); int attachmentCollectionLength = ContentHostingService.ATTACHMENTS_COLLECTION.length() + siteId.length() + esl + toolName.length() + esl + maxUuidLength + esl; int maxChars = ContentHostingService.MAXIMUM_RESOURCE_ID_LENGTH - attachmentCollectionLength - fileExtension.length() - 1; String resourceId = StringUtils.substring(sb_resourceId.toString(), 0, maxChars) + fileExtension; ResourcePropertiesEdit inlineProps = m_contentHostingService.newResourceProperties(); inlineProps.addProperty(ResourceProperties.PROP_DISPLAY_NAME, rb.getString("submission.inline")); inlineProps.addProperty(ResourceProperties.PROP_DESCRIPTION, resourceId); inlineProps.addProperty(AssignmentSubmission.PROP_INLINE_SUBMISSION, "true"); //create a byte array input stream //text is almost in html format, but it's missing the start and ending tags //(Is this always the case? Does the content review service care?) String toHtml = "<html><head></head><body>" + text + "</body></html>"; InputStream contentStream = new ByteArrayInputStream(toHtml.getBytes()); String contentType = "text/html"; //duplicating code from doAttachUpload. TODO: Consider refactoring into a method SecurityAdvisor sa = new SecurityAdvisor() { public SecurityAdvice isAllowed(String userId, String function, String reference) { if (function.equals(m_contentHostingService.AUTH_RESOURCE_ADD)) { return SecurityAdvice.ALLOWED; } else if (function.equals(m_contentHostingService.AUTH_RESOURCE_WRITE_ANY)) { return SecurityAdvice.ALLOWED; } else { return SecurityAdvice.PASS; } } }; try { m_securityService.pushAdvisor(sa); ContentResource attachment = m_contentHostingService.addAttachmentResource(resourceId, siteId, toolName, contentType, contentStream, inlineProps); // TODO: need to put this file in some kind of list to improve performance with web service impls of content-review service String contentUserId = isOnBehalfOfStudent ? student.getId() : currentUser.getId(); contentReviewService.queueContent(contentUserId, siteId, edit.getAssignment().getReference(), Arrays.asList(attachment)); try { Reference ref = EntityManager .newReference(m_contentHostingService.getReference(attachment.getId())); edit.addSubmittedAttachment(ref); } catch (Exception e) { M_log.warn(this + "prepareInlineForContentReview() cannot find reference for " + attachment.getId() + e.getMessage()); } } catch (PermissionException e) { addAlert(state, rb.getString("notpermis4")); } catch (RuntimeException e) { if (m_contentHostingService.ID_LENGTH_EXCEPTION.equals(e.getMessage())) { addAlert(state, rb.getFormattedMessage("alert.toolong", new String[] { resourceId })); } } catch (ServerOverloadException e) { M_log.debug(this + ".prepareInlineForContentReview() ***** DISK IO Exception ***** " + e.getMessage()); addAlert(state, rb.getString("failed.diskio")); } catch (Exception ignore) { M_log.debug( this + ".prepareInlineForContentReview() ***** Unknown Exception ***** " + ignore.getMessage()); addAlert(state, rb.getString("failed")); } finally { m_securityService.popAdvisor(sa); } }
From source file:org.sakaiproject.lap.service.DateService.java
/** * Parses a dated directory name to get the date object * e.g. yyyyMMdd_HHmmss_A => date object * //from w w w. j a v a 2s . c o m * @param directory the directory name * @return the date object */ public Date parseDirectoryToDateTime(String directory) { if (StringUtils.isBlank(directory)) { throw new NullArgumentException(directory); } if (directory.length() > 15) { directory = StringUtils.substring(directory, 0, 15); } Date date = null; try { date = DateUtils.SDF_FILE_NAME.parse(directory); } catch (Exception e) { log.error("Error parsing directory string to date. Error: " + e, e); } return date; }
From source file:org.sakaiproject.lap.util.ExtractorUtils.java
/** * Gets the full name of the extraction type for a given directory * e.g. "manual" or "scheduled"// w w w. j av a 2s .c o m * * @param directory the directory * @return the full name of the extraction type */ public static String calculateExtractionType(String directory) { // get the last 2 characters of directory name String fileNameExtractionType = StringUtils.substring(directory, directory.length() - 2, directory.length()); String extractionType = Constants.EXTRACTION_TYPE_MAP.get(fileNameExtractionType); if (extractionType == null) { extractionType = ""; } return extractionType; }
From source file:org.sakaiproject.profile2.util.ProfileUtils.java
/** * Trims text to the given maximum number of displayed characters. * Supports HTML and preserves formatting. * /*from w w w. j a v a 2 s . co m*/ * @param s the string * @param maxNumOfChars num chars to keep. If HTML, it's the number of content chars, ignoring tags. * @param isHtml is the string HTML? * @return */ public static String truncate(String s, int maxNumOfChars, boolean isHtml) { if (StringUtils.isBlank(s)) { return ""; } //html if (isHtml) { StringBuilder trimmedHtml = new StringBuilder(); FormattedText.trimFormattedText(s, maxNumOfChars, trimmedHtml); return trimmedHtml.toString(); } //plain text return StringUtils.substring(s, 0, maxNumOfChars); }
From source file:org.sakuli.services.forwarder.AbstractOutputBuilder.java
protected static String cutTo(String string, int summaryMaxLength) { if (string != null && string.length() > summaryMaxLength) { return StringUtils.substring(string, 0, summaryMaxLength) + " ..."; }/*from ww w .j av a2s . c o m*/ return string; }
From source file:org.sipfoundry.sipxconfig.admin.alarm.AlarmEvent.java
private Date extractDate(String line) { try {/*from www . ja va2s . c o m*/ String token = StringUtils.substring(line, 1, 20); // alarm times are the UTC times from the alarms log LOG_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); return LOG_DATE_FORMAT.parse(token); } catch (ParseException ex) { return new Date(0); } }
From source file:org.sipfoundry.sipxconfig.alarm.AlarmEvent.java
private static Date extractDate(String line) { try {/*w w w .j a v a 2 s . c o m*/ String token = StringUtils.substring(line, 1, 20); // alarm times are the UTC times from the alarms log LOG_DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); return LOG_DATE_FORMAT.parse(token); } catch (ParseException ex) { return new Date(0); } }
From source file:org.sonar.php.checks.ConstantNameCheck.java
private String getFirstParameter(AstNode astNode) { String firstParam = astNode.getFirstChild(PHPGrammar.PARAMETER_LIST_FOR_CALL).getFirstChild() .getTokenOriginalValue();/*from w ww.j av a 2 s . c o m*/ return StringUtils.substring(firstParam, 1, firstParam.length() - 1); }
From source file:org.sonar.php.checks.StringLiteralDuplicatedCheck.java
@Override public void visitLiteral(LiteralTree tree) { if (tree.is(Kind.REGULAR_STRING_LITERAL)) { String literal = tree.value(); String value = StringUtils.substring(literal, 1, literal.length() - 1); if (value.length() >= MINIMAL_LITERAL_LENGTH) { if (!sameLiteralOccurrencesCounter.containsKey(value)) { sameLiteralOccurrencesCounter.put(value, 1); firstOccurrenceLines.put(value, ((PHPTree) tree).getLine()); } else { int occurrences = sameLiteralOccurrencesCounter.get(value); sameLiteralOccurrencesCounter.put(value, occurrences + 1); }/*from ww w. ja va 2s . co m*/ } } }
From source file:org.sonar.plugins.scmstats.AbstractScmAdapter.java
Resource createResource(String resourceName) { String mavenizedResourceName = StringUtils.remove(resourceName, configuration.getSourceDir()); mavenizedResourceName = StringUtils.remove(mavenizedResourceName, configuration.getTestSourceDir()); int index = StringUtils.lastIndexOf(mavenizedResourceName, "/"); String directory = StringUtils.substring(mavenizedResourceName, 0, index); String filename = StringUtils.substring(mavenizedResourceName, index + 1); return new File(directory, filename); }