List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:org.wso2.carbon.registry.core.jdbc.dataaccess.TenantAwareSQLTransformer.java
/** * Construct the TenantAwareSQLTransformer for a given query * * @param sqlQuery the query to transform to tenant aware sql * * @throws RegistryException throws if the transformation failed. *//*w ww.j a v a 2 s . co m*/ public TenantAwareSQLTransformer(String sqlQuery) throws RegistryException { //parse SQL for possible injected SQLs try { sanityCheckSQL(sqlQuery); } catch (RegistryException e) { throw new RegistryException("SQL query provided failed validity check. Reason for failure is : " + e.getMessage() + ".SQL Query received is : " + sqlQuery); } String sqlQueryUCase = sqlQuery.toUpperCase(); parameterCount = 0; int endOfFromIndex = sqlQueryUCase.indexOf("FROM"); if (endOfFromIndex == -1) { String msg = "Error in parsing the query. You should have a 'FROM' token in your " + "custom query"; log.error(msg); throw new RegistryException(msg); } endOfFromIndex += 4; int startOfWhereIndex = sqlQueryUCase.indexOf("WHERE"); int startOfThirdClauseIndex = -1; for (String s : new String[] { "GROUP BY", "HAVING", "ORDER BY", "LIMIT" }) { int index = sqlQueryUCase.indexOf(s); if (index > 0 && (startOfThirdClauseIndex == -1 || index < startOfThirdClauseIndex)) { startOfThirdClauseIndex = index; } } boolean whereNotFound = false; if (startOfWhereIndex == -1) { // no 'WHERE' whereNotFound = true; startOfWhereIndex = sqlQueryUCase.length(); if (startOfThirdClauseIndex != -1) { startOfWhereIndex = startOfThirdClauseIndex; } } String fromPart = sqlQuery.substring(endOfFromIndex + 1, startOfWhereIndex); StringTokenizer tokenizer = new StringTokenizer(fromPart, ","); String additionalWherePart; StringBuilder sb = new StringBuilder(); while (tokenizer.hasMoreElements()) { String token = tokenizer.nextToken(); token = token.trim(); token = token.replaceAll("[\t\r\n]+", " "); int separator = token.indexOf(' '); String firstPart; String secondPart; if (separator == -1) { firstPart = token; secondPart = null; } else { firstPart = token.substring(0, separator); secondPart = token.substring(separator + 1); firstPart = firstPart.trim(); secondPart = secondPart.trim(); } // now the first part contains the table name if (secondPart == null) { if (sb.length() < 1) { sb.append(firstPart).append(".REG_TENANT_ID=?"); } else { sb.append(" AND ").append(firstPart).append(".REG_TENANT_ID=?"); } } else { if (sb.length() < 1) { sb.append(secondPart).append(".REG_TENANT_ID=?"); } else { sb.append(" AND ").append(secondPart).append(".REG_TENANT_ID=?"); } } parameterCount++; } additionalWherePart = sb.toString(); // if (whereNotFound) { // if (startOfThirdClauseIndex == -1) { // transformedQuery = sqlQuery + " WHERE " + additionalWherePart; // } else { // String[] parts = sqlQuery.substring(startOfThirdClauseIndex).split("[?]"); // if (parts != null && parts.length > 1) { // trailingParameterCount += parts.length - 1; // if (sqlQuery.substring(startOfThirdClauseIndex).endsWith("?")) { // trailingParameterCount += 1; // } // } // transformedQuery = sqlQuery.substring(0, startOfThirdClauseIndex) + " WHERE " // + additionalWherePart + " " + sqlQuery.substring(startOfThirdClauseIndex); // } // } else { // int endOfWhereIndex = startOfWhereIndex + 5; // if (startOfThirdClauseIndex == -1) { // transformedQuery = sqlQuery.substring(0, endOfWhereIndex) + " (" + // sqlQuery.substring(endOfWhereIndex) + ") " + " AND " // + additionalWherePart; // } else { // String[] parts = sqlQuery.substring(startOfThirdClauseIndex).split("[?]"); // if (parts != null && parts.length > 1) { // trailingParameterCount += parts.length - 1; // if (sqlQuery.substring(startOfThirdClauseIndex).endsWith("?")) { // trailingParameterCount += 1; // } // } // transformedQuery = sqlQuery.substring(0, endOfWhereIndex) + " (" + // sqlQuery.substring(endOfWhereIndex, startOfThirdClauseIndex) + ") " + " AND " // + additionalWherePart + " " + sqlQuery.substring(startOfThirdClauseIndex); // } // } if (whereNotFound) { if (startOfThirdClauseIndex == -1) { transformedQuery = sqlQuery + " WHERE " + additionalWherePart; } else { String[] parts = sqlQuery.substring(startOfThirdClauseIndex).split("[?]"); if (parts != null && parts.length > 1) { trailingParameterCount += parts.length - 1; if (sqlQuery.substring(startOfThirdClauseIndex).endsWith("?")) { trailingParameterCount += 1; } } transformedQuery = sqlQuery.substring(0, startOfThirdClauseIndex) + " WHERE " + additionalWherePart + " " + sqlQuery.substring(startOfThirdClauseIndex); } } else { int endOfWhereIndex = startOfWhereIndex + 5; transformedQuery = sqlQuery.substring(0, endOfWhereIndex) + " (" + additionalWherePart + ") AND " + sqlQuery.substring(endOfWhereIndex); } }
From source file:com.ktouch.kdc.launcher4.camera.CameraManager.java
public static void dumpParameter(Camera.Parameters parameters) { String flattened = parameters.flatten(); StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); Log.d(TAG, "Dump all camera parameters:"); while (tokenizer.hasMoreElements()) { Log.d(TAG, tokenizer.nextToken()); }// ww w .j a va 2s .c o m }
From source file:org.apache.sling.testing.clients.SlingHttpResponse.java
/** * Get copy paths from message//from www. j a va2 s .c o m * * @return copy paths as String Array */ public String[] getSlingCopyPaths() { String copyPaths = getSlingMessage(); StringTokenizer tokenizer = new StringTokenizer(copyPaths); List<String> copies = new ArrayList<String>(); while (tokenizer.hasMoreElements()) { copies.add(tokenizer.nextToken()); } return copies.toArray(new String[copies.size()]); }
From source file:org.jengine.mbean.FTPHL7Client.java
private void initializeQueueConnection() { try {/*from w w w. j a v a 2s . co m*/ if (session != null) session.close(); ctx = getInitialContext(); factory = (QueueConnectionFactory) ctx.lookup(CONNECTION_FACTORY); connection = factory.createQueueConnection(); session = connection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE); StringTokenizer st = new StringTokenizer(QueueNames, ":"); while (st.hasMoreElements()) { queue = (Queue) ctx.lookup("queue/" + st.nextElement()); Queues.add(queue); qSender = session.createSender(queue); QSenders.add(qSender); } } catch (JMSException je) { je.printStackTrace(); } catch (NamingException ne) { ne.printStackTrace(); } }
From source file:org.trafodion.dtm.HBaseAuditControlPoint.java
public ArrayList<String> getRecordList(String controlPt) throws IOException { if (LOG.isTraceEnabled()) LOG.trace("getRecord"); ArrayList<String> transactionList = new ArrayList<String>(); Get g = new Get(Bytes.toBytes(controlPt)); Result r = table.get(g);//from w ww. j av a 2s. co m byte[] currValue = r.getValue(CONTROL_POINT_FAMILY, ASN_HIGH_WATER_MARK); String recordString = new String(currValue); if (LOG.isDebugEnabled()) LOG.debug("recordString is " + recordString); StringTokenizer st = new StringTokenizer(recordString, ","); while (st.hasMoreElements()) { String token = st.nextElement().toString(); if (LOG.isDebugEnabled()) LOG.debug("token is " + token); transactionList.add(token); } if (LOG.isTraceEnabled()) LOG.trace("getRecord - exit with list size (" + transactionList.size() + ")"); return transactionList; }
From source file:com.squid.kraken.v4.api.core.customer.CustomerServiceBaseImpl.java
/** * Request for access to the system. The process will be the following: * <ul>/*from ww w . j a v a2 s . co m*/ * <li>Create a new Customer with given name.</li> * <li>Create a new User with Owner rights on Customer with given email.</li> * <li>Create 2 new Clients (admin_console and dashboard) with domain "api.squidsolutions.com" for this * Customer (Client.urls - new field in the Client model).</li> * <li>Send a welcome mail including a link to the API Console.</li> * </ul> * * @param request * http request * @param customerName * name of the new customer * @param email * email of the new user * @param login * login of the new user * @param password * password of the new user * @param locale * locale * @param domain * the caller domain (remote host) * @param linkURL * link to return in the email * @param emailHelper * util to send mail */ public AppContext accessRequest(AUTH_MODE authMode, String customerName, String email, String login, String password, String locale, String domain, String linkURL, String defaultClientURL, EmailHelper emailHelper) { // set defaults if (StringUtils.isEmpty(login) && StringUtils.isEmpty(email)) { login = "super"; password = "super123"; } if ((locale != null) && !locale.isEmpty()) { locale = locale.trim(); } else { locale = Locale.getDefault().toString(); } List<String> urls = new ArrayList<String>(); if (defaultClientURL != null) { if (defaultClientURL.contains(",")) { StringTokenizer st = new StringTokenizer(defaultClientURL, ","); while (st.hasMoreElements()) { urls.add(st.nextElement().toString()); } } else { urls.add(defaultClientURL); } } if (domain != null && ((defaultClientURL == null) || (!defaultClientURL.equals(domain)))) { urls.add(domain); } // clients List<Client> clients = new ArrayList<Client>(); clients.add(new Client(new ClientPK(null, CoreConstants.CONSOLE_CLIENT_ID), CoreConstants.CONSOLE_CLIENT_NAME, "" + UUID.randomUUID(), urls)); clients.add(new Client(new ClientPK(null, CoreConstants.DASHBOARD_CLIENT_ID), CoreConstants.DASHBOARD_CLIENT_NAME, "" + UUID.randomUUID(), urls)); String salt = UUID.randomUUID().toString(); AppContext ctx = createCustomer(authMode, customerName, locale, salt, login, password, email, clients); if (email != null) { // send welcome mail String linkAccessRequest = linkURL.replace('{' + CoreConstants.PARAM_NAME_CUSTOMER_ID + "}", ctx.getCustomerId()); String content = "Welcome to the SquidAnalytics API.\n\n"; content += "Your Customer ID is " + ctx.getCustomerId() + "\n\n"; content += "Please follow this link to access your API Console :\n" + linkAccessRequest; content += "\n\nThe SquidAnalytics Team."; String subject = "SquidAnalytics API access"; List<String> dests = Arrays.asList(email); try { logger.info("Sending API access request link (" + linkAccessRequest + ") to " + email + " " + ctx.getUser()); List<String> bccAddresses = new ArrayList<String>(); String bccAddress = KrakenConfig.getProperty("signup.email.bcc", true); if ((bccAddress != null) && !bccAddress.isEmpty()) { bccAddresses.add(bccAddress); } emailHelper.sendEmail(dests, bccAddresses, subject, content, null, EmailHelper.PRIORITY_NORMAL); } catch (MessagingException e) { throw new APIException(e, ctx.isNoError()); } } return ctx; }
From source file:us.mn.state.health.lims.testmanagement.action.TestManagementCancelTestsAction.java
protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String forward = FWD_SUCCESS; request.setAttribute(ALLOW_EDITS_KEY, "true"); String selectedTestsString = (String) request.getParameter("selectedTests"); BaseActionForm dynaForm = (BaseActionForm) form; String accessionNumber = (String) dynaForm.get("accessionNumber"); // initialize the form dynaForm.initialize(mapping);/*from w ww . j av a 2 s .com*/ ActionMessages errors = null; Map errorMap = new HashMap(); errorMap.put(HAS_AMENDED_TEST, new ArrayList()); errorMap.put(INVALID_STATUS_RESULTS_COMPLETE, new ArrayList()); errorMap.put(INVALID_STATUS_RESULTS_VERIFIED, new ArrayList()); Transaction tx = HibernateUtil.getSession().beginTransaction(); try { SampleDAO sampleDAO = new SampleDAOImpl(); SampleItemDAO sampleItemDAO = new SampleItemDAOImpl(); TestDAO testDAO = new TestDAOImpl(); AnalysisDAO analysisDAO = new AnalysisDAOImpl(); ResultDAO resultDAO = new ResultDAOImpl(); NoteDAO noteDAO = new NoteDAOImpl(); AnalysisQaEventDAO analysisQaEventDAO = new AnalysisQaEventDAOImpl(); AnalysisQaEventActionDAO analysisQaEventActionDAO = new AnalysisQaEventActionDAOImpl(); List listOfIds = new ArrayList(); // bugzilla 1926 insert logging - get sysUserId from login module UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA); String sysUserId = String.valueOf(usd.getSystemUserId()); if (!StringUtil.isNullorNill(selectedTestsString)) { String idSeparator = SystemConfiguration.getInstance().getDefaultIdSeparator(); StringTokenizer st = new StringTokenizer(selectedTestsString, idSeparator); while (st.hasMoreElements()) { String id = (String) st.nextElement(); listOfIds.add(id); } //now set analysis status to canceled for these analysis ids for (int i = 0; i < listOfIds.size(); i++) { String id = (String) listOfIds.get(i); //bug 2532 (the ids are now analysis ids - not test ids) Analysis analysis = new Analysis(); analysis.setId(id); analysisDAO.getData(analysis); if (analysis != null && !StringUtil.isNullorNill(analysis.getId())) { if (analysis.getStatus() .equals(SystemConfiguration.getInstance().getAnalysisStatusAssigned())) { if (!analysis.getRevision().equals("0")) { List listOfAmendedTests = (ArrayList) errorMap.get(HAS_AMENDED_TEST); listOfAmendedTests.add(analysis); errorMap.put(HAS_AMENDED_TEST, listOfAmendedTests); } } else if (analysis.getStatus() .equals(SystemConfiguration.getInstance().getAnalysisStatusResultCompleted())) { List listOfCompletedTests = (ArrayList) errorMap.get(INVALID_STATUS_RESULTS_COMPLETE); listOfCompletedTests.add(analysis); errorMap.put(INVALID_STATUS_RESULTS_COMPLETE, listOfCompletedTests); continue; } else if (analysis.getStatus() .equals(SystemConfiguration.getInstance().getAnalysisStatusReleased())) { List listOfVerifiedTests = (ArrayList) errorMap.get(INVALID_STATUS_RESULTS_VERIFIED); listOfVerifiedTests.add(analysis); errorMap.put(INVALID_STATUS_RESULTS_VERIFIED, listOfVerifiedTests); continue; } analysis.setSysUserId(sysUserId); analysis.setStatus(SystemConfiguration.getInstance().getAnalysisStatusCanceled()); analysisDAO.updateData(analysis); } } } PropertyUtils.setProperty(dynaForm, ACCESSION_NUMBER, accessionNumber); tx.commit(); // introducing a confirmation message if (errorMap != null && errorMap.size() > 0) { //1) amended message List amendedTests = (ArrayList) errorMap.get(HAS_AMENDED_TEST); List completedTests = (ArrayList) errorMap.get(INVALID_STATUS_RESULTS_COMPLETE); List verifiedTests = (ArrayList) errorMap.get(INVALID_STATUS_RESULTS_VERIFIED); if ((amendedTests != null && amendedTests.size() > 0) || (completedTests != null && completedTests.size() > 0) || (verifiedTests != null && verifiedTests.size() > 0)) { errors = new ActionMessages(); if (amendedTests != null && amendedTests.size() > 0) { ActionError error = null; if (amendedTests.size() > 1) { StringBuffer stringOfTests = new StringBuffer(); for (int i = 0; i < amendedTests.size(); i++) { Analysis analysis = (Analysis) amendedTests.get(i); stringOfTests.append("\\n " + analysis.getTest().getTestDisplayValue()); } error = new ActionError("testsmanagement.message.multiple.test.not.canceled.amended", stringOfTests.toString(), null); } else { Analysis analysis = (Analysis) amendedTests.get(0); error = new ActionError("testsmanagement.message.one.test.not.canceled.amended", "\\n " + analysis.getTest().getTestDisplayValue(), null); } errors.add(ActionMessages.GLOBAL_MESSAGE, error); } if (completedTests != null && completedTests.size() > 0) { ActionError error = null; if (completedTests.size() > 1) { StringBuffer stringOfTests = new StringBuffer(); for (int i = 0; i < completedTests.size(); i++) { Analysis analysis = (Analysis) completedTests.get(i); stringOfTests.append("\\n " + analysis.getTest().getTestDisplayValue()); } error = new ActionError("testsmanagement.message.multiple.test.not.canceled.completed", stringOfTests.toString(), null); } else { Analysis analysis = (Analysis) completedTests.get(0); error = new ActionError("testsmanagement.message.one.test.not.canceled.completed", "\\n " + analysis.getTest().getTestDisplayValue(), null); } errors.add(ActionMessages.GLOBAL_MESSAGE, error); } if (verifiedTests != null && verifiedTests.size() > 0) { ActionError error = null; if (verifiedTests.size() > 1) { StringBuffer stringOfTests = new StringBuffer(); for (int i = 0; i < verifiedTests.size(); i++) { Analysis analysis = (Analysis) verifiedTests.get(i); stringOfTests.append("\\n " + analysis.getTest().getTestDisplayValue()); } error = new ActionError("testsmanagement.message.multiple.test.not.canceled.verified", stringOfTests.toString(), null); } else { Analysis analysis = (Analysis) verifiedTests.get(0); error = new ActionError("testsmanagement.message.one.test.not.canceled.verified", "\\n " + analysis.getTest().getTestDisplayValue(), null); } errors.add(ActionMessages.GLOBAL_MESSAGE, error); } saveErrors(request, errors); request.setAttribute(Globals.ERROR_KEY, errors); } } } catch (LIMSRuntimeException lre) { //bugzilla 2154 LogEvent.logError("TestManagementCancelTests", "performAction()", lre.toString()); tx.rollback(); errors = new ActionMessages(); ActionError error = null; if (lre.getException() instanceof org.hibernate.StaleObjectStateException) { error = new ActionError("errors.OptimisticLockException", null, null); } else { error = new ActionError("errors.UpdateException", null, null); } errors.add(ActionMessages.GLOBAL_MESSAGE, error); saveErrors(request, errors); request.setAttribute(Globals.ERROR_KEY, errors); request.setAttribute(ALLOW_EDITS_KEY, "false"); return mapping.findForward(FWD_FAIL); } finally { HibernateUtil.closeSession(); } return mapping.findForward(forward); }
From source file:org.openhab.binding.smarthomatic.internal.SmarthomaticBinding.java
/** * @{inheritDoc/*from www . j a v a2 s .com*/ * */ @Override public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { // to override the default refresh interval one has to add a // parameter to openhab.cfg like // <bindingName>:refresh=<intervalInMs> String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } boolean changed = false; if (serialPortname != (String) config.get("serialPort")) { serialPortname = (String) config.get("serialPort"); changed = true; } String dummy = (String) config.get("baud"); try { if (serialBaudrate != Integer.parseInt(dummy)) { serialBaudrate = Integer.parseInt(dummy); changed = true; } } catch (NumberFormatException e) { logger.info("reading exception"); } if (changed | (baseStation == null)) { if (baseStation != null) { baseStation.closeSerialPort(); } baseStation = new BaseStation(serialPortname, serialBaudrate, this); logger.debug("Smarthomatic Binding:update creates new basestation"); } Enumeration<String> keys = config.keys(); for (int i = 0; i < config.size(); i++) { String key = keys.nextElement(); StringTokenizer tokens = new StringTokenizer(key, ":"); if (tokens.nextToken().equals("device")) { if (tokens.hasMoreElements()) { dummy = tokens.nextToken(); int deviceID = Integer.parseInt(dummy); String name = (String) config.get(key); SmarthomaticGenericBindingProvider.addDevice(name, deviceID); logger.debug("Smarthomatic device {} can be indexed by name {}", new String[] { dummy, name }); } } logger.debug("KEY: {}", key); } setProperlyConfigured(true); } }
From source file:com.sshtools.j2ssh.transport.AbstractKnownHostsKeyVerification.java
/** * <p>//from w ww . j a v a 2 s. c o m * Removes an allowed host. * </p> * * @param host the host to remove * * @since 0.2.0 */ public void removeAllowedHost(String host) { Iterator it = allowedHosts.keySet().iterator(); while (it.hasNext()) { StringTokenizer tokens = new StringTokenizer((String) it.next(), ","); while (tokens.hasMoreElements()) { String name = (String) tokens.nextElement(); if (name.equals(host)) { allowedHosts.remove(name); } } } }
From source file:com.gorillalogic.monkeytalk.ant.RunTask.java
public void sendReport() { try {/*www. ja v a 2s . c o m*/ File zippedReports = FileUtils.zipDirectory(reportdir, true, false); System.out.println(zippedReports.getAbsolutePath()); Map<String, String> additionalParams = new HashMap<String, String>(); StringTokenizer st2 = new StringTokenizer(jobrefparams, ","); while (st2.hasMoreElements()) { String param = (String) st2.nextElement(); StringTokenizer st3 = new StringTokenizer(param, ":"); additionalParams.put((String) st3.nextElement(), (String) st3.nextElement()); } sendFormPost(callbackurl, zippedReports, additionalParams); } catch (IOException ex) { ex.printStackTrace(); } }