List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:org.pentaho.platform.plugin.action.eclipsebirt.BirtSystemListener.java
private IReportEngine createBIRTEngine() { try {/*from ww w .ja v a2 s.co m*/ // Get the global settings for the BIRT engine from our system settings String birtHome = PentahoSystem.getApplicationContext().getSolutionPath("system/BIRT"); //$NON-NLS-1$ birtHome = birtHome.replaceAll("\\\\.\\\\", "\\\\"); //$NON-NLS-1$ //$NON-NLS-2$ String birtResourcePath = PentahoSystem.getApplicationContext() .getSolutionPath("system/BIRT/resources"); //$NON-NLS-1$ birtResourcePath = birtResourcePath.replaceAll("\\\\.\\\\", "\\\\"); //$NON-NLS-1$//$NON-NLS-2$ if (PentahoSystem.debug) { Logger.debug(BirtSystemListener.class.getName(), Messages.getString("BIRT.DEBUG_BIRT_HOME", birtHome)); //$NON-NLS-1$ } // Create an appropriate Config object EngineConfig config = new EngineConfig(); config.setEngineHome(birtHome); // Configuring where BIRT engine is installed config.setResourcePath(birtResourcePath); // Set the directory where the BIRT log files will go String logDest = PentahoSystem.getApplicationContext().getFileOutputPath("system/logs/BIRT"); //$NON-NLS-1$ // Set the logging level int loggingLevel = Logger.getLogLevel(); if (loggingLevel == ILogger.TRACE) { config.setLogConfig(logDest, Level.ALL); } else if (loggingLevel == ILogger.DEBUG) { config.setLogConfig(logDest, Level.FINE); } else if (loggingLevel == ILogger.INFO) { config.setLogConfig(logDest, Level.INFO); } else if (loggingLevel == ILogger.WARN) { config.setLogConfig(logDest, Level.WARNING); } else if (loggingLevel == ILogger.ERROR) { config.setLogConfig(logDest, Level.SEVERE); } else if (loggingLevel == ILogger.FATAL) { config.setLogConfig(logDest, Level.SEVERE); } // Register new image handler // Bart Maertens, 14/11/2007: Replace HTMLEmitterConfig with HTMLRenderOption. // HTMLEmitterConfig emitterConfig = new HTMLEmitterConfig(); // emitterConfig.setActionHandler(new HTMLActionHandler()); // emitterConfig.setImageHandler(new HTMLServerImageHandler()); // config.getEmitterConfigs().put(RenderOptionBase.OUTPUT_FORMAT_HTML, emitterConfig); IRenderOption option = new RenderOption(); option.setOutputFormat("html"); //$NON-NLS-1$ HTMLRenderOption renderOption = new HTMLRenderOption(option); renderOption.setImageDirectory(imageDirectory); config.getEmitterConfigs().put(IRenderOption.OUTPUT_FORMAT_HTML, renderOption); // Workaround for Eclipse bug 156877 String protocolHandler = System.getProperty("java.protocol.handler.pkgs"); //$NON-NLS-1$ if ((protocolHandler != null) && (protocolHandler.indexOf("org.jboss.net.protocol") != -1)) { //$NON-NLS-1$ StringTokenizer tok = new StringTokenizer(protocolHandler, "|"); //$NON-NLS-1$ StringBuffer newProtocolHandler = new StringBuffer(); String name; while (tok.hasMoreElements()) { name = tok.nextToken(); if (!name.equals("org.jboss.net.protocol")) { //$NON-NLS-1$ newProtocolHandler.append(name).append('|'); } } newProtocolHandler.setLength(Math.max(0, newProtocolHandler.length() - 1)); // chop the last '|' BirtSystemListener.workaroundProtocolHandler = System.setProperty("java.protocol.handler.pkgs", //$NON-NLS-1$ newProtocolHandler.toString()); } // End Workaround Platform.startup(config); IReportEngineFactory factory = (IReportEngineFactory) Platform .createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY); IReportEngine engine = factory.createReportEngine(config); return engine; } catch (BirtException be) { BirtSystemListener.logger.error(null, be); Logger.error(BirtSystemListener.class.getName(), Messages.getErrorString("BIRT.ERROR_0008_INVALID_CONFIGURATION")); //$NON-NLS-1$ } return null; }
From source file:eu.stratosphere.pact.test.util.TestBase.java
/** * Compares the expectedResultString and the file(s) in the HDFS linewise. * Both results (expected and computed) are held in memory. Hence, this * method should not be used to compare large results. * //from ww w. j a va2 s .co m * The line comparator is used to compare lines from the expected and result set. * * @param expectedResult * @param hdfsPath * @param comp Line comparator */ protected void compareResultsByLinesInMemory(String expectedResultStr, String resultPath, Comparator<String> comp) throws Exception { ArrayList<String> resultFiles = new ArrayList<String>(); // Determine all result files if (getFilesystemProvider().isDir(resultPath)) { for (String file : getFilesystemProvider().listFiles(resultPath)) { if (!getFilesystemProvider().isDir(file)) { resultFiles.add(resultPath + "/" + file); } } } else { resultFiles.add(resultPath); } // collect lines of all result files PriorityQueue<String> computedResult = new PriorityQueue<String>(); for (String resultFile : resultFiles) { // read each result file InputStream is = getFilesystemProvider().getInputStream(resultFile); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = reader.readLine(); // collect lines while (line != null) { computedResult.add(line); line = reader.readLine(); } reader.close(); } PriorityQueue<String> expectedResult = new PriorityQueue<String>(); StringTokenizer st = new StringTokenizer(expectedResultStr, "\n"); while (st.hasMoreElements()) { expectedResult.add(st.nextToken()); } // log expected and computed results if (LOG.isDebugEnabled()) { LOG.debug("Expected: " + expectedResult); LOG.debug("Computed: " + computedResult); } Assert.assertEquals("Computed and expected results have different size", expectedResult.size(), computedResult.size()); while (!expectedResult.isEmpty()) { String expectedLine = expectedResult.poll(); String computedLine = computedResult.poll(); if (LOG.isDebugEnabled()) LOG.debug("expLine: <" + expectedLine + ">\t\t: compLine: <" + computedLine + ">"); Assert.assertEquals("Computed and expected lines differ", expectedLine, computedLine); } }
From source file:org.apache.james.protocols.smtp.core.MailCmdHandler.java
/** * @param session// w w w . j av a 2s .com * SMTP session object * @param argument * the argument passed in with the command by the SMTP client */ private Response doMAILFilter(SMTPSession session, String argument) { String sender = null; if ((argument != null) && (argument.indexOf(":") > 0)) { int colonIndex = argument.indexOf(":"); sender = argument.substring(colonIndex + 1); argument = argument.substring(0, colonIndex); } if (session.getAttachment(SMTPSession.SENDER, State.Transaction) != null) { return SENDER_ALREADY_SPECIFIED; } else if (session.getAttachment(SMTPSession.CURRENT_HELO_MODE, State.Connection) == null && session.getConfiguration().useHeloEhloEnforcement()) { return EHLO_HELO_NEEDED; } else if (argument == null || !argument.toUpperCase(Locale.US).equals("FROM") || sender == null) { return SYNTAX_ERROR_ARG; } else { sender = sender.trim(); // the next gt after the first lt ... AUTH may add more <> int lastChar = sender.indexOf('>', sender.indexOf('<')); // Check to see if any options are present and, if so, whether they // are correctly formatted // (separated from the closing angle bracket by a ' '). if ((lastChar > 0) && (sender.length() > lastChar + 2) && (sender.charAt(lastChar + 1) == ' ')) { String mailOptionString = sender.substring(lastChar + 2); // Remove the options from the sender sender = sender.substring(0, lastChar + 1); StringTokenizer optionTokenizer = new StringTokenizer(mailOptionString, " "); while (optionTokenizer.hasMoreElements()) { String mailOption = optionTokenizer.nextToken(); int equalIndex = mailOption.indexOf('='); String mailOptionName = mailOption; String mailOptionValue = ""; if (equalIndex > 0) { mailOptionName = mailOption.substring(0, equalIndex).toUpperCase(Locale.US); mailOptionValue = mailOption.substring(equalIndex + 1); } // Handle the SIZE extension keyword if (paramHooks.containsKey(mailOptionName)) { MailParametersHook hook = paramHooks.get(mailOptionName); SMTPResponse res = calcDefaultSMTPResponse( hook.doMailParameter(session, mailOptionName, mailOptionValue)); if (res != null) { return res; } } else { // Unexpected option attached to the Mail command if (session.getLogger().isDebugEnabled()) { StringBuilder debugBuffer = new StringBuilder(128) .append("MAIL command had unrecognized/unexpected option ") .append(mailOptionName).append(" with value ").append(mailOptionValue); session.getLogger().debug(debugBuffer.toString()); } } } } if (session.getConfiguration().useAddressBracketsEnforcement() && (!sender.startsWith("<") || !sender.endsWith(">"))) { if (session.getLogger().isInfoEnabled()) { StringBuilder errorBuffer = new StringBuilder(128).append("Error parsing sender address: ") .append(sender).append(": did not start and end with < >"); session.getLogger().info(errorBuffer.toString()); } return SYNTAX_ERROR; } MailAddress senderAddress = null; if (session.getConfiguration().useAddressBracketsEnforcement() || (sender.startsWith("<") && sender.endsWith(">"))) { // Remove < and > sender = sender.substring(1, sender.length() - 1); } if (sender.length() == 0) { // This is the <> case. Let senderAddress == null } else { if (!sender.contains("@")) { sender = sender + "@" + getDefaultDomain(); } try { senderAddress = new MailAddress(sender); } catch (Exception pe) { if (session.getLogger().isInfoEnabled()) { StringBuilder errorBuffer = new StringBuilder(256).append("Error parsing sender address: ") .append(sender).append(": ").append(pe.getMessage()); session.getLogger().info(errorBuffer.toString()); } return SYNTAX_ERROR_ADDRESS; } } if ((senderAddress == null) || ((senderAddress.getLocalPart().length() == 0) && (senderAddress.getDomain().length() == 0))) { senderAddress = MailAddress.nullSender(); } // Store the senderAddress in session map session.setAttachment(SMTPSession.SENDER, senderAddress, State.Transaction); } return null; }
From source file:org.wso2.appcloud.core.docker.DockerClient.java
/** * Create a docker file according to given details. This will get docker template file and replace the parameters * with the given customized values in the dockerFilePropertyMap * @param dockerFilePath//from w ww .ja v a 2 s. c o m * @param runtimeId - application runtime id * @param dockerTemplateFilePath * @param dockerFileCategory - app creation method eg : svn, url, default * @param dockerFilePropertyMap * @param customDockerFileProperties * @throws IOException * @throws AppCloudException */ public void createDockerFile(String dockerFilePath, String runtimeId, String dockerTemplateFilePath, String dockerFileCategory, Map<String, String> dockerFilePropertyMap, Map<String, String> customDockerFileProperties) throws AppCloudException { customDockerFileProperties.keySet().removeAll(dockerFilePropertyMap.keySet()); dockerFilePropertyMap.putAll(customDockerFileProperties); // Get docker template file // A sample docker file can be found at // https://github.com/wso2/app-cloud/blob/master/modules/resources/dockerfiles/wso2as/default/Dockerfile.wso2as.6.0.0-m1 String dockerFileTemplatePath = DockerUtil.getDockerFileTemplatePath(runtimeId, dockerTemplateFilePath, dockerFileCategory); List<String> dockerFileConfigs = new ArrayList<>(); try { for (String line : FileUtils.readLines(new File(dockerFileTemplatePath))) { StringTokenizer stringTokenizer = new StringTokenizer(line); //Search if line contains keyword to replace with the value while (stringTokenizer.hasMoreElements()) { String element = stringTokenizer.nextElement().toString().trim(); if (dockerFilePropertyMap.containsKey(element)) { if (log.isDebugEnabled()) { log.debug("Dockerfile placeholder : " + element); } String value = dockerFilePropertyMap.get(element); line = line.replace(element, value); } } dockerFileConfigs.add(line); } } catch (IOException e) { String msg = "Error occurred while reading docker template file " + dockerFileTemplatePath; throw new AppCloudException(msg, e); } try { FileUtils.writeLines(new File(dockerFilePath), dockerFileConfigs); } catch (IOException e) { String msg = "Error occurred while writing to docker file " + dockerFilePath; throw new AppCloudException(msg, e); } }
From source file:com.actionbazaar.controller.SellController.java
/** * Performs the category search//from w w w .j a v a2 s . c o m */ public void performCategorySearch() { List<String> split = new LinkedList<>(); StringTokenizer tokenizer = new StringTokenizer(keywords, " "); while (tokenizer.hasMoreElements()) { split.add((String) tokenizer.nextElement()); } String splitArray[] = new String[split.size()]; splitArray = split.toArray(splitArray); searchCategories.setSource(pickListBean.findCategories(splitArray)); }
From source file:org.openmrs.module.muzima.web.resource.openmrs.ConceptResource.java
/** * Concept searches support the following additional query parameters: * <ul>/*from w w w. j a v a2 s . co m*/ * <li>answerTo=(uuid): restricts results to concepts that are answers to the given concept uuid * </li> * <li>memberOf=(uuid): restricts to concepts that are set members of the given concept set's * uuid</li> * </ul> * * @see org.openmrs.module.webservices.rest.web.resource.impl.DelegatingCrudResource#doSearch(RequestContext) */ @Override protected PageableResult doSearch(RequestContext context) { ConceptService service = Context.getConceptService(); Integer startIndex = null; Integer limit = null; boolean canPage = true; // Collect information for answerTo and memberOf query parameters String acceptedLanguages = context.getRequest().getHeader("Accept-Language"); String answerToUuid = context.getRequest().getParameter("answerTo"); String memberOfUuid = context.getRequest().getParameter("memberOf"); Concept answerTo = null; List<Concept> memberOfList = null; if (StringUtils.isNotBlank(answerToUuid)) { try { answerTo = (Concept) ConversionUtil.convert(answerToUuid, Concept.class); } catch (ConversionException ex) { log.error("Unexpected exception while retrieving answerTo Concept with UUID " + answerToUuid, ex); } } if (StringUtils.isNotBlank(memberOfUuid)) { Concept memberOf = service.getConceptByUuid(memberOfUuid); memberOfList = service.getConceptsByConceptSet(memberOf); canPage = false; // ConceptService does not support memberOf searches, so paging must be deferred. } // Only set startIndex and limit if we can return paged results if (canPage) { startIndex = context.getStartIndex(); limit = context.getLimit(); } List<ConceptSearchResult> searchResults; List<Locale> locales = null; if (StringUtils.isNotBlank(acceptedLanguages)) { StringTokenizer localeTokens = new StringTokenizer(acceptedLanguages, ","); if (localeTokens.hasMoreElements()) { String strLocale = localeTokens.nextToken(); //TODO: Agree if this is the Best approach. [If several locales pick the first one with priority 1] /* A locale of format en-US has two parts <pre>en is the language (English in this case) and US is the country</pre> Since OpenMRS saves concepts names only using the language we will only take the first token Here we would expect a - but also lets support _ just in case e.g en-US vs en_US */ StringTokenizer countrySplitter = new StringTokenizer(strLocale, "_-"); if (countrySplitter.hasMoreElements()) { // We have a language, create a Locale for this language Locale parsedLocale = new Locale(countrySplitter.nextToken()); locales = new ArrayList<Locale>(); locales.add(parsedLocale); // //TODO: ConceptService searches only on Context.getLocale(); Context.setLocale(parsedLocale); } } } else { // get the user's locales...and then convert that from a set to a list locales = new ArrayList<Locale>(LocaleUtility.getLocalesInOrder()); } searchResults = service.getConcepts(context.getParameter("q"), locales, context.getIncludeAll(), null, null, null, null, answerTo, startIndex, limit); // convert search results into list of concepts List<FakeConcept> results = new ArrayList<FakeConcept>(searchResults.size()); for (ConceptSearchResult csr : searchResults) { // apply memberOf filter if (memberOfList == null || memberOfList.contains(csr.getConcept())) results.add(FakeConcept.copyConcept(csr.getConcept())); } PageableResult result; if (canPage) { Integer count = service.getCountOfConcepts(context.getParameter("q"), locales, false, Collections.<ConceptClass>emptyList(), Collections.<ConceptClass>emptyList(), Collections.<ConceptDatatype>emptyList(), Collections.<ConceptDatatype>emptyList(), answerTo); boolean hasMore = count > startIndex + limit; result = new AlreadyPaged<FakeConcept>(context, results, hasMore); } else { result = new NeedsPaging<FakeConcept>(results, context); } return result; }
From source file:com.ericsson.deviceaccess.adaptor.ruleengine.device.Rule.java
public final void setWeekDays(String weekDays) { weekDaysBool = new boolean[7]; StringTokenizer st = new StringTokenizer(weekDays, ","); while (st.hasMoreElements()) { String weekDay = st.nextToken().trim(); Integer weekDayIdx = WEEKDAYS.get(weekDay); if (weekDayIdx == null) { throw new IllegalArgumentException("Invalid weekday: " + weekDay); }//from w w w. j av a 2s . co m weekDaysBool[weekDayIdx] = true; } this.weekDays = weekDays; }
From source file:it.unibas.spicy.persistence.xml.operators.UpdateDataSourceWithConstraints.java
private List<String> normalizePath(String path) { String currentPath = path;//w w w . j a v a 2s .com ArrayList<String> list = new ArrayList<String>(); if (currentPath.startsWith(".")) { currentPath = path.substring(1); } currentPath = currentPath.replaceAll("\\@", ""); currentPath = currentPath.replaceAll("\\*", ""); StringTokenizer tokenizer = new StringTokenizer(currentPath, "/"); if (tokenizer.countTokens() > 0) { if (logger.isDebugEnabled()) logger.debug(" --- Tokenizer for " + path + " with " + tokenizer.countTokens() + " elements"); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); if (!(token.trim().equals(""))) { if (logger.isDebugEnabled()) logger.debug("\t +" + token + " added"); list.add(token); } } } else { if (!(currentPath.trim().equals(""))) { if (logger.isDebugEnabled()) logger.debug("\t +" + currentPath + " added"); list.add(currentPath); } } if (logger.isDebugEnabled()) logger.debug(" --- Size of list for " + path + " is = " + list.size()); return list; }
From source file:org.pdfgal.pdfgalweb.validators.utils.impl.ValidatorUtilsImpl.java
/** * This method represents the loop for the validateConcretePages method. * //from w w w . j av a2s . co m * @param totalPages * @param pages * @param delim1 * @param delim2 * @param moreThanOne * @return */ private boolean validateConcretePagesLoop(final Integer totalPages, final String pages, final String delim1, final String delim2, final boolean testMoreThanOne) { boolean result = false; if (totalPages != null && StringUtils.isNotEmpty(pages) && StringUtils.isNotEmpty(delim1)) { result = true; final StringTokenizer st = new StringTokenizer(pages, delim1); Integer previous = null; String token = null; if ("-".equals(delim1) && st.countTokens() != 2) { result = false; } else { while (st.hasMoreElements()) { try { token = st.nextToken(); final Integer current = Integer.valueOf(token); boolean isMoreThan = true; if (testMoreThanOne) { isMoreThan = (current.compareTo(new Integer(2)) < 0); } else { isMoreThan = (current.compareTo(new Integer(1)) < 0); } if ((current.compareTo(totalPages) > 0) || isMoreThan || (previous != null && current.compareTo(previous) <= 0)) { result = false; break; } previous = current; } catch (final Exception e) { if (StringUtils.isNotEmpty(delim2)) { result = this.validateConcretePagesLoop(totalPages, token, delim2, null, testMoreThanOne); } else { result = false; } if (!result) { break; } } } } } return result; }
From source file:ro.cs.cm.common.TextTable.java
public void addRow(String theRow, byte aRowAlign) { // dk am speficat ca nu avem nici o linie (doar headerul) // nu face nimic // adaug inca o linie la matricea tabel // log.debug("addRow() -> CurrentRowNo begin = " + currentRowNo); if (currentRowNo > MAX_NO_OF_ROWS_ALLOWED) { logger.info("No of allowed cols ".concat(String.valueOf(MAX_NO_OF_ROWS_ALLOWED))); }/*from w w w. j ava 2 s. c o m*/ ArrayList<String> row = new ArrayList<String>(); StringTokenizer st = new StringTokenizer(theRow, ELEMENT_SEPARATOR); rowAlign.add(new Byte(aRowAlign)); int j = 0; boolean amAvutCaracterEndLine = false; StringBuffer sb = new StringBuffer(); while (st.hasMoreElements()) { // punem un spatiu in stanga si in dreapta continutului sb.delete(0, sb.length()); // resetez StringBufferul sb.append(" "); String s = (String) st.nextElement(); if (s.indexOf('\n') != -1) { s = s.replace('\n', '?'); amAvutCaracterEndLine = true; } sb.append(s); sb.append(" "); row.add(sb.toString()); } // in cazul in care o linie nu este completa (ca numar de coloane), // completez if (j < header.length) { for (int i = j; i < header.length; row.add(" "), i++) { ; } } if (amAvutCaracterEndLine) { row.add(" (? = \\n)"); } table.add(row); // incrementez variabila statica currentRow pentru // a stii nr. de ordine al urmatoarei linii adaugate currentRowNo++; // log.debug("addRow() -> CurrentRowNo end = " + currentRowNo); }