List of usage examples for org.apache.commons.lang StringUtils chomp
public static String chomp(String str)
Removes one newline from end of a String if it's there, otherwise leave it alone.
From source file:org.owasp.jbrofuzz.fuzz.io.Save.java
/** * <p>Method for obtaining the data for the transforms and their corresponding fuzzers * in CSV type format.</p>// ww w . j a v a2 s . com * <p>Examples include:<p> * <code> * 1,URL Cp1252,QUFB,QkJC * 1,Base64,zqbOps6m,zqbOps6m * 2,SHA-512 Hash,zpHOo86U, * </code> * * @param The main frame where JBroFuzz will get the URL, Request and * other parameters. * * @return e.g. the example above * * @author subere@uncon.org * @version 2.5 * @since 2.5 * */ public static String getTableOfTransformsInCSVFormat(final JBroFuzzWindow mWindow) { FuzzersTableModel inputTableModel = mWindow.getPanelFuzzing().getFuzzersPanel().getFuzzersTableModel(); final StringBuffer output = new StringBuffer(); final int totalFuzzerRows = inputTableModel.getRowCount(); if (totalFuzzerRows < 1) { return ""; } for (int fuzzerRow = 0; fuzzerRow < totalFuzzerRows; fuzzerRow++) { TransformsTableModel encoderRows = mWindow.getPanelFuzzing().getTransformsPanel() .getTransforms(fuzzerRow); final int totalEncoderRows = encoderRows.getRowCount(); for (int transformRow = 0; transformRow < totalEncoderRows; transformRow++) { output.append((fuzzerRow + 1)); output.append(','); output.append(encoderRows.getRow(transformRow).getEncoder()); output.append(','); String prefix; try { prefix = Base64.encodeBase64String( encoderRows.getRow(transformRow).getPrefixOrMatch().getBytes("UTF-8")); prefix = StringUtils.chomp(prefix); } catch (UnsupportedEncodingException e) { prefix = ""; } output.append(prefix); output.append(','); String suffix; try { suffix = Base64.encodeBase64String( encoderRows.getRow(transformRow).getSuffixOrReplace().getBytes("UTF-8")); suffix = StringUtils.chomp(suffix); } catch (UnsupportedEncodingException e) { suffix = ""; } output.append(suffix); // Append a new line, but not for the last line of the last transform if ((fuzzerRow != totalFuzzerRows - 1) || (transformRow != totalEncoderRows - 1)) { output.append('\n'); } } } return output.toString(); }
From source file:org.sakaiproject.tool.assessment.ui.listener.author.ItemAddListener.java
public void saveItem(ItemAuthorBean itemauthor) throws FinFormatException { boolean update = false; ItemBean bean = itemauthor.getCurrentItem(); ItemFacade item;// ww w. j a v a 2 s . c o m AuthorBean author = (AuthorBean) ContextUtil.lookupBean("author"); isEditPendingAssessmentFlow = author.getIsEditPendingAssessmentFlow(); log.debug("**** isEditPendingAssessmentFlow : " + isEditPendingAssessmentFlow); String target = itemauthor.getTarget(); boolean isFromQuestionPool = false; if (target != null && (target.equals(ItemAuthorBean.FROM_QUESTIONPOOL) && !author.getIsEditPoolFlow())) { isFromQuestionPool = true; } log.debug("**** isFromQuestionPool : " + isFromQuestionPool); isPendingOrPool = isEditPendingAssessmentFlow || (isFromQuestionPool && !author.getIsEditPoolFlow()); ItemService delegate; if (isPendingOrPool) { EventTrackingService.post(EventTrackingService.newEvent("sam.assessment.revise", "siteId=" + AgentFacade.getCurrentSiteId() + ", itemId=" + itemauthor.getItemId(), true)); delegate = new ItemService(); } else { EventTrackingService.post(EventTrackingService.newEvent("sam.pubassessment.revise", "siteId=" + AgentFacade.getCurrentSiteId() + ", itemId=" + itemauthor.getItemId(), true)); delegate = new PublishedItemService(); } // update not working yet, delete, then add if ((bean.getItemId() != null) && (!bean.getItemId().equals("0"))) { update = true; // if modify ,itemid shouldn't be null , or 0. Long oldId = Long.valueOf(bean.getItemId()); if (isPendingOrPool) { delegate.deleteItemContent(oldId, AgentFacade.getAgentString()); } item = delegate.getItem(oldId, AgentFacade.getAgentString()); } else { if (isPendingOrPool) { item = new ItemFacade(); } else { item = new PublishedItemFacade(); } } item.setScore(Double.valueOf(bean.getItemScore())); item.setDiscount(Double.valueOf(bean.getItemDiscount())); item.setHint(""); item.setStatus(ItemDataIfc.ACTIVE_STATUS); item.setTypeId(Long.valueOf(bean.getItemType())); if (item.getTypeId().equals(TypeFacade.EXTENDED_MATCHING_ITEMS)) { item.setAnswerOptionsSimpleOrRich(Integer.valueOf(bean.getAnswerOptionsSimpleOrRich())); item.setAnswerOptionsRichCount(Integer.valueOf(bean.getAnswerOptionsRichCount())); } item.setCreatedBy(AgentFacade.getAgentString()); item.setCreatedDate(new Date()); item.setLastModifiedBy(AgentFacade.getAgentString()); item.setLastModifiedDate(new Date()); if (bean.getInstruction() != null) { // for matching and matrix Survey item.setInstruction(bean.getInstruction()); } // update hasRationale if (bean.getRationale() != null) { item.setHasRationale(Boolean.valueOf(bean.getRationale())); } else { item.setHasRationale(Boolean.FALSE); } item.setPartialCreditFlag(Boolean.valueOf(bean.getPartialCreditFlag())); // update maxNumAttempts for audio if (bean.getNumAttempts() != null) { item.setTriesAllowed(Integer.valueOf(bean.getNumAttempts())); } // save timeallowed for audio recording if (bean.getTimeAllowed() != null) { item.setDuration(Integer.valueOf(bean.getTimeAllowed())); } if (update && !isPendingOrPool) { //prepare itemText, including answers item.setItemTextSet(preparePublishedText(item, bean, delegate)); // prepare MetaData item.setItemMetaDataSet(preparePublishedMetaData(item, bean)); // prepare feedback, because this is UPDATE // if it's an empty string, we need to update feedback to an empty string // not like below (below we don't ADD if the feedback is null or empty string) if ((bean.getCorrFeedback() != null)) { updateItemFeedback(item, ItemFeedbackIfc.CORRECT_FEEDBACK, stripPtags(bean.getCorrFeedback())); } if ((bean.getIncorrFeedback() != null)) { updateItemFeedback(item, ItemFeedbackIfc.INCORRECT_FEEDBACK, stripPtags(bean.getIncorrFeedback())); } if ((bean.getGeneralFeedback() != null)) { updateItemFeedback(item, ItemFeedbackIfc.GENERAL_FEEDBACK, stripPtags(bean.getGeneralFeedback())); } } else { //prepare itemText, including answers if (item.getTypeId().equals(TypeFacade.EXTENDED_MATCHING_ITEMS)) { item.setItemTextSet(prepareTextForEMI(item, bean, itemauthor)); } else if (item.getTypeId().equals(TypeFacade.MATCHING)) { item.setItemTextSet(prepareTextForMatching(item, bean, itemauthor)); } else if (item.getTypeId().equals(TypeFacade.CALCULATED_QUESTION)) { item.setItemTextSet(prepareTextForCalculatedQuestion(item, bean, itemauthor)); } else if (item.getTypeId().equals(TypeFacade.MATRIX_CHOICES_SURVEY)) { item.setItemTextSet(prepareTextForMatrixChoice(item, bean, itemauthor)); } else if (item.getTypeId().equals(TypeFacade.IMAGEMAP_QUESTION)) { item.setItemTextSet(prepareTextForImageMapQuestion(item, bean, itemauthor)); } else { //Other Types item.setItemTextSet(prepareText(item, bean, itemauthor)); } // prepare MetaData item.setItemMetaDataSet(prepareMetaData(item, bean)); // prepare feedback, only store if feedbacks are not empty if ((bean.getCorrFeedback() != null) && (!bean.getCorrFeedback().equals(""))) { item.setCorrectItemFeedback(stripPtags(bean.getCorrFeedback())); } if ((bean.getIncorrFeedback() != null) && (!bean.getIncorrFeedback().equals(""))) { item.setInCorrectItemFeedback(stripPtags(bean.getIncorrFeedback())); } if ((bean.getGeneralFeedback() != null) && (!bean.getGeneralFeedback().equals(""))) { item.setGeneralItemFeedback(stripPtags(bean.getGeneralFeedback())); } } if (isFromQuestionPool) { // Came from Pool manager delegate.saveItem(item); // added by daisyf, 10/10/06 updateAttachment(item.getItemAttachmentList(), itemauthor.getAttachmentList(), (ItemDataIfc) item.getData(), true); if (item.getTypeId().equals(TypeFacade.EXTENDED_MATCHING_ITEMS)) { Iterator emiItemIter = itemauthor.getCurrentItem().getEmiQuestionAnswerCombinationsClean() .iterator(); while (emiItemIter.hasNext()) { AnswerBean answerBean = (AnswerBean) emiItemIter.next(); ItemTextIfc itemText = item.getItemTextBySequence(answerBean.getSequence()); updateItemTextAttachment(answerBean.getAttachmentList(), itemText, true); } } item = delegate.getItem(item.getItemId().toString()); QuestionPoolService qpdelegate = new QuestionPoolService(); if (!qpdelegate.hasItem(item.getItemIdString(), Long.valueOf(itemauthor.getQpoolId()))) { qpdelegate.addItemToPool(item.getItemId(), Long.valueOf(itemauthor.getQpoolId())); } QuestionPoolBean qpoolbean = (QuestionPoolBean) ContextUtil.lookupBean("questionpool"); QuestionPoolDataBean contextCurrentPool = qpoolbean.getCurrentPool(); qpoolbean.buildTree(); /* // Reset question pool bean QuestionPoolFacade thepool= qpdelegate.getPool(new Long(itemauthor.getQpoolId()), AgentFacade.getAgentString()); qpoolbean.getCurrentPool().setNumberOfQuestions(thepool.getQuestionSize().toString()); */ qpoolbean.startEditPoolAgain(itemauthor.getQpoolId()); QuestionPoolDataBean currentPool = qpoolbean.getCurrentPool(); currentPool.setDisplayName(contextCurrentPool.getDisplayName()); currentPool.setOrganizationName(contextCurrentPool.getOrganizationName()); currentPool.setDescription(contextCurrentPool.getDescription()); currentPool.setObjectives(contextCurrentPool.getObjectives()); currentPool.setKeywords(contextCurrentPool.getKeywords()); ArrayList addedQuestions = qpoolbean.getAddedQuestions(); if (addedQuestions == null) { addedQuestions = new ArrayList(); } addedQuestions.add(item.getItemId()); qpoolbean.setAddedPools(addedQuestions); // return to edit pool itemauthor.setOutcome("editPool"); } // Came from Questionbank Authoring else if (itemauthor.getTarget() != null && (itemauthor.getTarget().equals("sambank"))) { delegate.saveItem(item); itemauthor.setItemNo(item.getItemId().toString()); } else { // Came from Assessment Authoring AssessmentService assessdelegate; if (isEditPendingAssessmentFlow) { assessdelegate = new AssessmentService(); } else { assessdelegate = new PublishedAssessmentService(); } // add the item to the specified part, otherwise add to default if (bean.getSelectedSection() != null) { // need to do add a temp part first if assigned to a temp part SAK-2109 SectionFacade section; if ("-1".equals(bean.getSelectedSection())) { AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean"); // add a new section section = assessdelegate.addSection(assessmentBean.getAssessmentId()); } else { section = assessdelegate.getSection(bean.getSelectedSection()); } item.setSection(section); if (update) { // if Modify, need to reorder if assgned to different section ' if ((bean.getOrigSection() != null) && (!bean.getOrigSection().equals(bean.getSelectedSection()))) { // if reassigned to different section Integer oldSeq = item.getSequence(); item.setSequence(Integer.valueOf(section.getItemSet().size() + 1)); // reorder the sequences of items in the OrigSection SectionFacade origsect = assessdelegate.getSection(bean.getOrigSection()); shiftItemsInOrigSection(delegate, origsect, oldSeq); } else { // no action needed } } if (!update) { if ((itemauthor.getInsertPosition() == null) || ("".equals(itemauthor.getInsertPosition())) || !section.getSequence().toString().equals(itemauthor.getInsertToSection())) { // if adding to the end if (section.getItemSet() != null) { item.setSequence(Integer.valueOf(section.getItemSet().size() + 1)); } else { // this is a new part, not saved yet item.setSequence(Integer.valueOf(1)); } } else { // if inserting or a question String insertPos = itemauthor.getInsertPosition(); shiftSequences(delegate, section, Integer.valueOf(insertPos)); int insertPosInt = (Integer.valueOf(insertPos)).intValue() + 1; item.setSequence(Integer.valueOf(insertPosInt)); // reset InsertPosition itemauthor.setInsertPosition(""); } } if (itemauthor.getInsertToSection() != null) { // reset insertToSection to null; itemauthor.setInsertToSection(null); } if (author != null && author.getIsEditPoolFlow()) { section.getData().setLastModifiedDate(item.getLastModifiedDate()); DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZ"); section.addSectionMetaData(SectionDataIfc.QUESTIONS_RANDOM_DRAW_DATE, df.format(item.getLastModifiedDate())); assessdelegate.saveOrUpdateSection(section); } delegate.saveItem(item); // added by daisyf, 10/10/06 updateAttachment(item.getItemAttachmentList(), itemauthor.getAttachmentList(), (ItemDataIfc) item.getData(), isEditPendingAssessmentFlow); if (item.getTypeId().equals(TypeFacade.EXTENDED_MATCHING_ITEMS)) { for (AnswerBean answerBean : itemauthor.getCurrentItem() .getEmiQuestionAnswerCombinationsClean()) { ItemTextIfc itemText = item.getItemTextBySequence(answerBean.getSequence()); updateItemTextAttachment(answerBean.getAttachmentList(), itemText, isEditPendingAssessmentFlow); } } item = delegate.getItem(item.getItemId().toString()); } // prepare saving column choice to favorites (SAM_FAVORITECOLCHOICES_T and SAM_FAVORITECOLCHOICESITEM_T) // and save if (bean.getAddToFavorite()) { FavoriteColChoices favorite = new FavoriteColChoices(); favorite.setFavoriteName(bean.getFavoriteName().trim()); //find the agentId favorite.setOwnerStringId(AgentFacade.getAgentString()); String[] temp = bean.getColumnChoices().split(System.getProperty("line.separator")); //remove the empty string List<String> stringList = new ArrayList<String>(); for (String string : temp) { if (string != null && string.trim().length() > 0) { stringList.add(string); } } temp = stringList.toArray(new String[stringList.size()]); for (int i = 0; i < temp.length; i++) { FavoriteColChoicesItem favoriteChoiceItem = new FavoriteColChoicesItem( StringUtils.chomp(temp[i]), Integer.valueOf(i)); favoriteChoiceItem.setFavoriteChoice(favorite); favorite.getFavoriteItems().add(favoriteChoiceItem); } delegate.saveFavoriteColumnChoices(favorite); } QuestionPoolService qpdelegate = new QuestionPoolService(); // removed the old pool-item mappings if ((bean.getOrigPool() != null) && (!bean.getOrigPool().equals(""))) { qpdelegate.removeQuestionFromPool(item.getItemId(), Long.valueOf(bean.getOrigPool())); } // if assign to pool, add the item to the pool if ((bean.getSelectedPool() != null) && !bean.getSelectedPool().equals("")) { // if the item is already in the pool then do not add. // This is a scenario where the item might already be in the pool: // create an item in an assessemnt and assign it to p1 // copy item from p1 to p2. // now the item is already in p2. and if you want to edit the original item in the assessment, and reassign it to p2, you will get a duplicate error. if (!qpdelegate.hasItem(item.getItemIdString(), Long.valueOf(bean.getSelectedPool()))) { qpdelegate.addItemToPool(item.getItemId(), Long.valueOf(bean.getSelectedPool())); } } // #1a - goto editAssessment.jsp, so reset assessmentBean AssessmentBean assessmentBean = (AssessmentBean) ContextUtil.lookupBean("assessmentBean"); AssessmentIfc assessment = assessdelegate.getAssessment(Long.valueOf(assessmentBean.getAssessmentId())); assessmentBean.setAssessment(assessment); itemauthor.setOutcome("editAssessment"); } // sorry, i need this for item attachment, used by SaveItemAttachmentListener. itemauthor.setItemId(item.getItemId().toString()); }
From source file:org.sakaiproject.tool.assessment.ui.listener.author.ItemAddListener.java
private String[] returnMatrixChoices(ItemBean bean, String str) { String[] result = null, temp = null; if ("row".equals(str)) temp = bean.getRowChoices().split(System.getProperty("line.separator")); else/* w ww . ja va 2 s . c om*/ temp = bean.getColumnChoices().split(System.getProperty("line.separator")); //remove the empty string List<String> stringList = new ArrayList<String>(); for (String string : temp) { if (string != null && string.trim().length() > 0) { stringList.add(string); } } temp = stringList.toArray(new String[stringList.size()]); result = new String[temp.length]; for (int i = 0; i < temp.length; i++) { //remove new line result[i] = StringUtils.chomp(temp[i]); } return result; }
From source file:org.sipfoundry.sipxconfig.backup.BackupCommandRunner.java
public String getBackupLink() { return StringUtils.chomp(runCommand("--link", m_plan.getAbsolutePath())); }
From source file:org.sipfoundry.sipxconfig.backup.BackupCommandRunner.java
public List<String> list() { if (!m_plan.exists()) { return Collections.emptyList(); }//from w w w . j av a2s . com String lines = StringUtils.chomp(runCommand("--list", m_plan.getAbsolutePath())); return Arrays.asList(StringUtils.splitByWholeSeparator(lines, "\n")); }
From source file:ubic.gemma.loader.entrez.pubmed.PubMedSearch.java
/** * Search based on terms//from ww w . ja v a2s. c o m * * @param searchTerms * @return BibliographicReference representing the publication * @throws IOException */ public Collection<BibliographicReference> searchAndRetrieveByHTTP(Collection<String> searchTerms) throws IOException, SAXException, ParserConfigurationException { StringBuilder builder = new StringBuilder(); builder.append(uri); builder.append("&term="); for (String string : searchTerms) { builder.append(string); builder.append("+"); } URL toBeGotten = new URL(StringUtils.chomp(builder.toString())); log.info("Fetching " + toBeGotten); ESearchXMLParser parser = new ESearchXMLParser(); Collection<String> ids = parser.parse(toBeGotten.openStream()); Collection<BibliographicReference> results = fetchById(ids); log.info("Fetched " + results.size() + " references"); return results; }
From source file:ubic.gemma.loader.entrez.pubmed.PubMedXMLFetcher.java
/** * For collection of integer pubmed ids. * /* ww w .j a v a2s .co m*/ * @param pubMedIds * @return Collection<BibliographicReference> * @throws IOException */ public Collection<BibliographicReference> retrieveByHTTP(Collection<Integer> pubMedIds) throws IOException { StringBuilder buf = new StringBuilder(); for (Integer integer : pubMedIds) { buf.append(integer + ","); } URL toBeGotten = new URL(uri + StringUtils.chomp(buf.toString())); log.debug("Fetching " + toBeGotten); PubMedXMLParser pmxp = new PubMedXMLParser(); return pmxp.parse(toBeGotten.openStream()); }
From source file:uk.ac.sanger.cgp.wwdocker.actions.Local.java
public static Map<String, String> execCapture(String command, Map envs, boolean shellCmd) { Map<String, String> result = new HashMap(); ProcessBuilder pb;//from w w w . j a v a 2s . c o m if (shellCmd) { pb = new ProcessBuilder("/bin/sh", "-c", command); } else { pb = new ProcessBuilder(command.split(" ")); } Map<String, String> pEnv = pb.environment(); if (envs != null) { pEnv.putAll(envs); } logger.info("Executing: " + command); int exitCode = -1; Process p = null; File tempOut = null; File tempErr = null; try { tempOut = File.createTempFile("wwdExec", ".out"); tempErr = File.createTempFile("wwdExec", ".err"); pb.redirectOutput(tempOut); pb.redirectError(tempErr); p = pb.start(); exitCode = p.waitFor(); } catch (InterruptedException | IOException e) { logger.error(e.getMessage(), e); } finally { if (tempOut != null && tempErr != null) { try { result.put("stdout", StringUtils.chomp(IOUtils.toString(new FileInputStream(tempOut)))); result.put("stderr", StringUtils.chomp(IOUtils.toString(new FileInputStream(tempErr)))); tempOut.delete(); tempErr.delete(); logger.info(result.get("stdout")); logger.error(result.get("stderr")); } catch (IOException e) { logger.error("Failed to get output from log files"); } } if (p != null) { p.destroy(); exitCode = p.exitValue(); } } result.put("exitCode", Integer.toString(exitCode)); return result; }