List of usage examples for org.apache.commons.lang.text StrMatcher charSetMatcher
public static StrMatcher charSetMatcher(String chars)
From source file:com.processpuzzle.fundamental_types.domain.ParameterValueList.java
public static ParameterValueList parse(String parameters) throws ClassNotFoundException, InstantiationException, IllegalAccessException { ParameterValueList valueList = new ParameterValueList(); StrMatcher delimiters = StrMatcher.charSetMatcher(LIST_DELIMITERS.toCharArray()); StrTokenizer tokenizer = new StrTokenizer(parameters, delimiters); while (tokenizer.hasNext()) { ParameterValue parameterValue = ParameterValue.parse(tokenizer.nextToken()); valueList.add(parameterValue);//w ww . j a v a 2 s . c o m } return valueList; }
From source file:au.org.ala.delta.intkey.directives.DefineNamesDirective.java
@Override protected BasicIntkeyDirectiveInvocation doProcess(IntkeyContext context, String data) throws Exception { String keyword = null;/*from w w w . ja v a2 s. co m*/ List<String> names = new ArrayList<String>(); // Need to prompt if data starts with a wildcard - don't bother // tokenizing if (!data.toUpperCase().startsWith(IntkeyDirectiveArgument.DEFAULT_DIALOG_WILDCARD)) { // Taxon names are separated by newlines or by commas List<String> tokens = new StrTokenizer(data, StrMatcher.charSetMatcher(new char[] { '\n', '\r', ',' })) .getTokenList(); if (!tokens.isEmpty()) { String firstToken = tokens.get(0); // The keyword (which may quoted) and first taxon name may be // separated by a space List<String> splitFirstToken = new StrTokenizer(firstToken, StrMatcher.charSetMatcher(new char[] { ' ' }), StrMatcher.quoteMatcher()).getTokenList(); keyword = splitFirstToken.get(0); if (splitFirstToken.size() > 1) { names.add(StringUtils.join(splitFirstToken.subList(1, splitFirstToken.size()), " ")); } for (int i = 1; i < tokens.size(); i++) { names.add(tokens.get(i).trim()); } //If first name begins with a wildcard, we need to prompt for names. Clear out the names list if this is the case. if (!names.isEmpty()) { if (names.get(0).toUpperCase().startsWith(IntkeyDirectiveArgument.DEFAULT_DIALOG_WILDCARD)) { names.clear(); } } } } List<Item> taxa = new ArrayList<Item>(); for (String taxonName : names) { Item taxon = context.getDataset().getTaxonByName(taxonName); if (taxon == null) { throw new IntkeyDirectiveParseException( UIUtils.getResourceString("InvalidTaxonName.error", taxonName)); } else { taxa.add(taxon); } } String directiveName = StringUtils.join(getControlWords(), " ").toUpperCase(); if (StringUtils.isEmpty(keyword)) { keyword = context.getDirectivePopulator() .promptForString(UIUtils.getResourceString("EnterKeyword.caption"), null, directiveName); if (keyword == null) { // cancelled return null; } } if (taxa.isEmpty()) { List<String> selectedKeywords = new ArrayList<String>(); // Not // used, // but // required // as an // argument taxa = context.getDirectivePopulator().promptForTaxaByList(directiveName, false, false, false, false, null, selectedKeywords); if (taxa == null || taxa.isEmpty()) { // cancelled return null; } // extract taxon names for use in building string representation of // command for (Item taxon : taxa) { names.add(_taxonFormatter.formatItemDescription(taxon)); } } DefineNamesDirectiveInvocation invoc = new DefineNamesDirectiveInvocation(keyword, taxa); invoc.setStringRepresentation( String.format("%s \"%s\" %s", getControlWordsAsString(), keyword, StringUtils.join(names, ", "))); return invoc; }
From source file:org.intermine.api.query.LookupTokeniser.java
private LookupTokeniser(boolean spaceIsSeparator) { if (spaceIsSeparator) { charSetMatcher = StrMatcher.charSetMatcher(" \n\t,"); } else {/*from www. j ava2 s . c o m*/ charSetMatcher = StrMatcher.charSetMatcher("\n\t,"); } }
From source file:org.intermine.web.struts.BuildBagAction.java
/** * Action for creating a bag of InterMineObjects or Strings from identifiers in text field. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * @exception Exception if the application business logic throws * an exception/*from ww w . j a v a2 s .c om*/ */ @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); final InterMineAPI im = SessionMethods.getInterMineAPI(session); ServletContext servletContext = request.getSession().getServletContext(); Properties webProperties = (Properties) servletContext.getAttribute(Constants.WEB_PROPERTIES); BuildBagForm buildBagForm = (BuildBagForm) form; String type = buildBagForm.getType(); if (StringUtils.isEmpty(type)) { recordError(new ActionMessage("bagBuild.typeNotSet"), request); return mapping.findForward("bags"); } BagQueryRunner bagRunner = im.getBagQueryRunner(); int maxBagSize = WebUtil.getIntSessionProperty(session, "max.bag.size", 100000); Profile profile = SessionMethods.getProfile(session); if (profile == null || profile.getUsername() == null) { int defaultMaxNotLoggedSize = 3; maxBagSize = WebUtil.getIntSessionProperty(session, "max.bag.size.notloggedin", defaultMaxNotLoggedSize); } BufferedReader reader = null; FormFile formFile = buildBagForm.getFormFile(); /* * FormFile used from Struts works a bit strangely. * 1. Although the file does't exist formFile.getInputStream() doesn't * throw FileNotFoundException. * 2. When user specified empty file path or very invalid file path, * like file path not starting at '/' then formFile.getFileName() returns empty string. */ if (formFile != null && formFile.getFileName() != null && formFile.getFileName().length() > 0) { // attach file name as the name of the bag String fileName = formFile.getFileName(); // strip suffix Integer lastPos = new Integer(fileName.lastIndexOf('.')); if (lastPos.intValue() > 0) { fileName = fileName.substring(0, lastPos.intValue()); } // replace underscores fileName = fileName.replaceAll("_", " "); // attach request.setAttribute("bagName", fileName); String mimetype = formFile.getContentType(); if (!"application/octet-stream".equals(mimetype) && !mimetype.startsWith("text")) { recordError(new ActionMessage("bagBuild.notText", mimetype), request); return mapping.findForward("bags"); } if (formFile.getFileSize() == 0) { recordError(new ActionMessage("bagBuild.noBagFileOrEmpty"), request); return mapping.findForward("bags"); } reader = new BufferedReader(new InputStreamReader(formFile.getInputStream())); } else if (buildBagForm.getText() != null && buildBagForm.getText().length() != 0) { String trimmedText = buildBagForm.getText().trim(); if (trimmedText.length() == 0) { recordError(new ActionMessage("bagBuild.noBagPaste"), request); return mapping.findForward("bags"); } reader = new BufferedReader(new StringReader(trimmedText)); } else { recordError(new ActionMessage("bagBuild.noBagFile"), request); return mapping.findForward("bags"); } reader.mark(READ_AHEAD_CHARS); char[] buf = new char[READ_AHEAD_CHARS]; int read = reader.read(buf, 0, READ_AHEAD_CHARS); for (int i = 0; i < read; i++) { if (buf[i] == 0) { recordError(new ActionMessage("bagBuild.notText", "binary"), request); return mapping.findForward("bags"); } } reader.reset(); String thisLine; List<String> list = new ArrayList<String>(); int elementCount = 0; while ((thisLine = reader.readLine()) != null) { // append whitespace to valid delimiters String bagUploadDelims = (String) webProperties.get("list.upload.delimiters") + " "; StrMatcher matcher = StrMatcher.charSetMatcher(bagUploadDelims); StrTokenizer st = new StrTokenizer(thisLine, matcher, StrMatcher.doubleQuoteMatcher()); while (st.hasNext()) { String token = st.nextToken(); list.add(token); elementCount++; if (elementCount > maxBagSize) { ActionMessage actionMessage = null; if (profile == null || profile.getUsername() == null) { actionMessage = new ActionMessage("bag.bigNotLoggedIn", new Integer(maxBagSize)); } else { actionMessage = new ActionMessage("bag.tooBig", new Integer(maxBagSize)); } recordError(actionMessage, request); return mapping.findForward("bags"); } } } BagQueryResult bagQueryResult = bagRunner.search(type, list, buildBagForm.getExtraFieldValue(), false, buildBagForm.getCaseSensitive()); session.setAttribute("bagQueryResult", bagQueryResult); request.setAttribute("bagType", type); request.setAttribute("bagExtraFilter", buildBagForm.getExtraFieldValue()); //buildNewBag used by jsp to set editable the bag name field request.setAttribute("buildNewBag", "true"); return mapping.findForward("bagUploadConfirm"); }
From source file:org.intermine.webservice.server.lists.ListUploadService.java
/** * Get the String Matcher for parsing the list of identifiers. * @return The matcher to use./* w w w . j a v a 2s . co m*/ */ protected StrMatcher getMatcher() { final HttpSession session = request.getSession(); final Properties webProperties = (Properties) session.getServletContext() .getAttribute(Constants.WEB_PROPERTIES); final String bagUploadDelims = (String) webProperties.get("list.upload.delimiters") + " "; final StrMatcher matcher = StrMatcher.charSetMatcher(bagUploadDelims); return matcher; }
From source file:org.soaplab.clients.BatchTestClient.java
/************************************************************************* * Call service as define in 'locator' (which also has an input * data for the service) and report results into a new entry in * 'reports'./* w w w. j a va2s . c om*/ * * It also returns its own report. *************************************************************************/ private static Properties callService(MyLocator locator, List<Properties> reports) { Properties report = new Properties(); reports.add(report); String serviceName = locator.getServiceName(); String inputLine = locator.getInputLine(); report.setProperty(REPORT_SERVICE_NAME, serviceName); report.setProperty(REPORT_INPUT_LINE, inputLine); try { SoaplabBaseClient client = new SoaplabBaseClient(locator); // collect inputs from the input line BaseCmdLine cmd = null; if (StringUtils.isBlank(inputLine)) { cmd = new BaseCmdLine(new String[] {}, true); } else { cmd = new BaseCmdLine( new StrTokenizer(inputLine, StrMatcher.charSetMatcher(" \t\f"), StrMatcher.quoteMatcher()) .getTokenArray(), true); } SoaplabMap inputs = SoaplabMap .fromMap(InputUtils.collectInputs(cmd, SoaplabMap.toMaps(client.getInputSpec()))); // any unrecognized inputs on the command-line? if (cmd.params.length > 0) { StringBuilder buf = new StringBuilder(); buf.append("Unrecognized inputs: "); for (String arg : cmd.params) buf.append(arg + " "); report.setProperty(REPORT_ERROR_MESSAGE, buf.toString()); report.setProperty(REPORT_JOB_STATUS, "NOT STARTED"); return report; } // start service and wait for its completion String jobId = client.createAndRun(inputs); report.setProperty(REPORT_JOB_ID, jobId); client.waitFor(jobId); // save all info about just finished job String status = client.getStatus(jobId); report.setProperty(REPORT_JOB_STATUS, status); SoaplabMap times = client.getCharacteristics(jobId); Object elapsed = times.get(SoaplabConstants.TIME_ELAPSED); if (elapsed != null) { try { report.setProperty(REPORT_ELAPSED_TIME, DurationFormatUtils.formatDurationHMS(Long.decode(elapsed.toString()))); } catch (NumberFormatException e) { } } String lastEvent = client.getLastEvent(jobId); if (lastEvent != null) report.setProperty(REPORT_LAST_EVENT, lastEvent); if (!client.getLocator().getProtocol().equals(ClientConfig.PROTOCOL_AXIS1)) { // get result infos (about all available results) ByteArrayOutputStream bos = new ByteArrayOutputStream(); ResultUtils.formatResultInfo(SoaplabMap.toStringMaps(client.getResultsInfo(jobId)), new PrintStream(bos)); report.setProperty(REPORT_RESULTS_INFO, bos.toString()); } // get results (but ignore them - except the special ones) client.getResults(jobId); Map<String, Object> results = SoaplabMap.toMap(client.getSomeResults(jobId, new String[] { SoaplabConstants.RESULT_REPORT, SoaplabConstants.RESULT_DETAILED_STATUS })); for (Iterator<String> it = results.keySet().iterator(); it.hasNext();) { String resultName = it.next(); report.setProperty(resultName, results.get(resultName).toString()); } // clean the job if (!locator.isEnabledKeepResults()) { client.destroy(jobId); report.remove(REPORT_JOB_ID); } } catch (Throwable e) { reportError(report, e); } return report; }