List of usage examples for java.util StringTokenizer nextElement
public Object nextElement()
From source file:com.irets.datadownloader.SearchPropertyServlet.java
public String getServer(HttpServletRequest req) { String server = null;/*from w w w.ja v a2s . c o m*/ String uri = req.getRequestURI(); if (uri.indexOf("/") > -1) { StringTokenizer sToken = new StringTokenizer(uri, "/"); if (sToken.hasMoreElements()) { server = (String) (sToken.nextElement()); if (server.equals("imls")) return null; } } System.out.println("server from uri is " + server); return server; }
From source file:com.jaspersoft.jasperserver.war.action.repositoryExplorer.ResourceAction.java
public Event copyResource(RequestContext context) { try {//from ww w. j ava 2s.c o m String sourceUri = URLDecoder.decode((String) context.getRequestParameters().get("sourceUri"), "UTF-8"); String destUri = URLDecoder.decode((String) context.getRequestParameters().get("destUri"), "UTF-8"); StringBuffer sb = new StringBuffer(); sb.append('{'); StringTokenizer str = new StringTokenizer(sourceUri, ","); List resourceURIs = new ArrayList(); while (str.hasMoreElements()) { String currentResource = (String) str.nextElement(); // get sourceUri label String sourceLabel = repositoryService.getResource(null, currentResource).getLabel(); // check if the label already exist in the destination folder if (doesObjectLabelExist(destUri, sourceLabel)) { sb.append("\"status\":\"FAILED\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); return no(); } resourceURIs.add(currentResource); } try { repositoryService.copyResources(null, (String[]) resourceURIs.toArray(new String[resourceURIs.size()]), destUri); } catch (Exception e) { log.error("Error copying resources", e); sb.append("\"status\":\"FAILED\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); return no(); } sb.append("\"status\":\"SUCCESS\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); } catch (UnsupportedEncodingException e) { } return success(); }
From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java
/** * Get the consumer token with the given parameters and URL. The determination of whether the retrieved token * is an access token depends on whether a request token is provided. * * @param details The resource details. * @param tokenURL The token URL./*www . j av a2 s .c o m*/ * @param httpMethod The http method. * @param requestToken The request token, or null if none. * @param additionalParameters The additional request parameter. * @return The token. */ protected OAuthConsumerToken getTokenFromProvider(ProtectedResourceDetails details, URL tokenURL, String httpMethod, OAuthConsumerToken requestToken, Map<String, String> additionalParameters) { boolean isAccessToken = requestToken != null; if (!isAccessToken) { //create an empty token to make a request for a new unauthorized request token. requestToken = new OAuthConsumerToken(); } TreeMap<String, String> requestHeaders = new TreeMap<String, String>(); if ("POST".equalsIgnoreCase(httpMethod)) { requestHeaders.put("Content-Type", "application/x-www-form-urlencoded"); } InputStream inputStream = readResource(details, tokenURL, httpMethod, requestToken, additionalParameters, requestHeaders); String tokenInfo; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = inputStream.read(buffer); while (len >= 0) { out.write(buffer, 0, len); len = inputStream.read(buffer); } tokenInfo = new String(out.toByteArray(), "UTF-8"); } catch (IOException e) { throw new OAuthRequestFailedException("Unable to read the token.", e); } StringTokenizer tokenProperties = new StringTokenizer(tokenInfo, "&"); Map<String, String> tokenPropertyValues = new TreeMap<String, String>(); while (tokenProperties.hasMoreElements()) { try { String tokenProperty = (String) tokenProperties.nextElement(); int equalsIndex = tokenProperty.indexOf('='); if (equalsIndex > 0) { String propertyName = OAuthCodec.oauthDecode(tokenProperty.substring(0, equalsIndex)); String propertyValue = OAuthCodec.oauthDecode(tokenProperty.substring(equalsIndex + 1)); tokenPropertyValues.put(propertyName, propertyValue); } else { tokenProperty = OAuthCodec.oauthDecode(tokenProperty); tokenPropertyValues.put(tokenProperty, null); } } catch (DecoderException e) { throw new OAuthRequestFailedException("Unable to decode token parameters."); } } String tokenValue = tokenPropertyValues.remove(OAuthProviderParameter.oauth_token.toString()); if (tokenValue == null) { throw new OAuthRequestFailedException("OAuth provider failed to return a token."); } String tokenSecret = tokenPropertyValues.remove(OAuthProviderParameter.oauth_token_secret.toString()); if (tokenSecret == null) { throw new OAuthRequestFailedException("OAuth provider failed to return a token secret."); } OAuthConsumerToken consumerToken = new OAuthConsumerToken(); consumerToken.setValue(tokenValue); consumerToken.setSecret(tokenSecret); consumerToken.setResourceId(details.getId()); consumerToken.setAccessToken(isAccessToken); if (!tokenPropertyValues.isEmpty()) { consumerToken.setAdditionalParameters(tokenPropertyValues); } return consumerToken; }
From source file:com.jaspersoft.jasperserver.war.action.repositoryExplorer.ResourceAction.java
public Event moveResource(RequestContext context) { try {// ww w. j ava 2 s .c o m String sourceUri = URLDecoder.decode((String) context.getRequestParameters().get("sourceUri"), "UTF-8"); String destUri = URLDecoder.decode((String) context.getRequestParameters().get("destUri"), "UTF-8"); StringTokenizer str = new StringTokenizer(sourceUri, ","); StringBuffer sb = new StringBuffer(); sb.append('{'); while (str.hasMoreElements()) { String currentResource = (String) str.nextElement(); // get sourceUri label String sourceLabel = repositoryService.getResource(null, currentResource).getLabel(); // check if the label already exist in the destination folder if (doesObjectLabelExist(destUri, sourceLabel)) { sb.append("\"status\":\"FAILED\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); return no(); } } str = new StringTokenizer(sourceUri, ","); while (str.hasMoreElements()) { String currentResource = (String) str.nextElement(); try { repositoryService.moveResource(null, currentResource, destUri); } catch (Exception e) { e.printStackTrace(); sb.append("\"status\":\"FAILED\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); return no(); } } sb.append("\"status\":\"SUCCESS\""); sb.append('}'); context.getRequestScope().put(AJAX_REPORT_MODEL, sb.toString()); } catch (UnsupportedEncodingException e) { } return success(); }
From source file:gtu._work.ui.RegexDirReplacer.java
private void initGUI() { try {// w w w. j a va 2 s . c o m { } BorderLayout thisLayout = new BorderLayout(); getContentPane().setLayout(thisLayout); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { jTabbedPane1 = new JTabbedPane(); getContentPane().add(jTabbedPane1, BorderLayout.CENTER); { jPanel1 = new JPanel(); BorderLayout jPanel1Layout = new BorderLayout(); jPanel1.setLayout(jPanel1Layout); jTabbedPane1.addTab("source", null, jPanel1, null); { jScrollPane1 = new JScrollPane(); jPanel1.add(jScrollPane1, BorderLayout.CENTER); { ListModel srcListModel = new DefaultListModel(); srcList = new JList(); jScrollPane1.setViewportView(srcList); srcList.setModel(srcListModel); { panel = new JPanel(); jScrollPane1.setRowHeaderView(panel); panel.setLayout(new FormLayout( new ColumnSpec[] { ColumnSpec.decode("default:grow"), }, new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC, FormFactory.DEFAULT_ROWSPEC, })); { childrenDirChkbox = new JCheckBox("??"); childrenDirChkbox.setSelected(true); panel.add(childrenDirChkbox, "1, 1"); } { subFileNameText = new JTextField(); panel.add(subFileNameText, "1, 2, fill, default"); subFileNameText.setColumns(10); subFileNameText.setText("(txt|java)"); } { replaceOldFileChkbox = new JCheckBox(""); replaceOldFileChkbox.setSelected(true); panel.add(replaceOldFileChkbox, "1, 3"); } { charsetText = new JTextField(); panel.add(charsetText, "1, 5, fill, default"); charsetText.setColumns(10); charsetText.setText("UTF8"); } } srcList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { JListUtil.newInstance(srcList).defaultMouseClickOpenFile(evt); JPopupMenuUtil.newInstance(srcList).applyEvent(evt)// .addJMenuItem("load files from clipboard", new ActionListener() { public void actionPerformed(ActionEvent arg0) { String content = ClipboardUtil.getInstance().getContents(); DefaultListModel model = (DefaultListModel) srcList.getModel(); StringTokenizer tok = new StringTokenizer(content, "\t\n\r\f", false); for (; tok.hasMoreElements();) { String val = ((String) tok.nextElement()).trim(); model.addElement(new File(val)); } } }).show(); } }); srcList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JListUtil.newInstance(srcList).defaultJListKeyPressed(evt); } }); } } { addDirFiles = new JButton(); jPanel1.add(addDirFiles, BorderLayout.NORTH); addDirFiles.setText("add dir files"); addDirFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog() .getApproveSelectedFile(); if (file == null || !file.isDirectory()) { return; } List<File> fileLst = new ArrayList<File>(); String subName = StringUtils.trimToEmpty(subFileNameText.getText()); if (StringUtils.isBlank(subName)) { subName = ".*"; } String patternStr = ".*\\." + subName; if (childrenDirChkbox.isSelected()) { FileUtil.searchFileMatchs(file, patternStr, fileLst); } else { for (File f : file.listFiles()) { if (f.isFile() && f.getName().matches(patternStr)) { fileLst.add(f); } } } DefaultListModel model = new DefaultListModel(); for (File f : fileLst) { model.addElement(f); } srcList.setModel(model); } }); } } { jPanel2 = new JPanel(); BorderLayout jPanel2Layout = new BorderLayout(); jPanel2.setLayout(jPanel2Layout); jTabbedPane1.addTab("param", null, jPanel2, null); { exeucte = new JButton(); jPanel2.add(exeucte, BorderLayout.SOUTH); exeucte.setText("exeucte"); exeucte.setPreferredSize(new java.awt.Dimension(491, 125)); exeucte.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exeucteActionPerformed(evt); } }); } { jPanel3 = new JPanel(); GroupLayout jPanel3Layout = new GroupLayout((JComponent) jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel2.add(jPanel3, BorderLayout.CENTER); { repFromText = new JTextField(); } { repToText = new JTextField(); } jPanel3Layout.setHorizontalGroup(jPanel3Layout.createSequentialGroup() .addContainerGap(25, 25) .addGroup(jPanel3Layout.createParallelGroup() .addGroup(jPanel3Layout.createSequentialGroup().addComponent(repFromText, GroupLayout.PREFERRED_SIZE, 446, GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup().addComponent(repToText, GroupLayout.PREFERRED_SIZE, 446, GroupLayout.PREFERRED_SIZE))) .addContainerGap(20, Short.MAX_VALUE)); jPanel3Layout.setVerticalGroup(jPanel3Layout.createSequentialGroup().addContainerGap() .addComponent(repFromText, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(repToText, GroupLayout.PREFERRED_SIZE, 24, GroupLayout.PREFERRED_SIZE) .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)); } { addToTemplate = new JButton(); jPanel2.add(addToTemplate, BorderLayout.NORTH); addToTemplate.setText("add to template"); addToTemplate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { prop.put(repFromText.getText(), repToText.getText()); reloadTemplateList(); } }); } } { jPanel4 = new JPanel(); BorderLayout jPanel4Layout = new BorderLayout(); jPanel4.setLayout(jPanel4Layout); jTabbedPane1.addTab("result", null, jPanel4, null); { jScrollPane2 = new JScrollPane(); jPanel4.add(jScrollPane2, BorderLayout.CENTER); { ListModel newRepListModel = new DefaultListModel(); newRepList = new JList(); jScrollPane2.setViewportView(newRepList); newRepList.setModel(newRepListModel); newRepList.addMouseListener(new MouseAdapter() { static final String tortoiseMergeExe = "TortoiseMerge.exe"; static final String commandFormat = "cmd /c call \"%s\" /base:\"%s\" /theirs:\"%s\""; public void mouseClicked(MouseEvent evt) { if (!JListUtil.newInstance(newRepList).isCorrectMouseClick(evt)) { return; } OldNewFile oldNewFile = (OldNewFile) JListUtil .getLeadSelectionObject(newRepList); String base = oldNewFile.newFile.getAbsolutePath(); String theirs = oldNewFile.oldFile.getAbsolutePath(); String command = String.format(commandFormat, tortoiseMergeExe, base, theirs); System.out.println(command); try { Runtime.getRuntime().exec(command); } catch (IOException e) { JCommonUtil.handleException(e); } } }); newRepList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { Object[] objects = (Object[]) newRepList.getSelectedValues(); if (objects == null || objects.length == 0) { return; } DefaultListModel model = (DefaultListModel) newRepList.getModel(); int lastIndex = model.getSize() - 1; Object swap = null; StringBuilder dsb = new StringBuilder(); for (Object current : objects) { int index = model.indexOf(current); switch (evt.getKeyCode()) { case 38:// up if (index != 0) { swap = model.getElementAt(index - 1); model.setElementAt(swap, index); model.setElementAt(current, index - 1); } break; case 40:// down if (index != lastIndex) { swap = model.getElementAt(index + 1); model.setElementAt(swap, index); model.setElementAt(current, index + 1); } break; case 127:// del OldNewFile current_ = (OldNewFile) current; dsb.append(current_.newFile.getName() + "\t" + (current_.newFile.delete() ? "T" : "F") + "\n"); current_.newFile.delete(); model.removeElement(current); } } if (dsb.length() > 0) { JOptionPaneUtil.newInstance().iconInformationMessage() .showMessageDialog("del result!\n" + dsb, "DELETE"); } } }); } } { replaceOrignFile = new JButton(); jPanel4.add(replaceOrignFile, BorderLayout.SOUTH); replaceOrignFile.setText("replace orign file"); replaceOrignFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { DefaultListModel model = (DefaultListModel) newRepList.getModel(); StringBuilder sb = new StringBuilder(); for (int ii = 0; ii < model.size(); ii++) { OldNewFile file = (OldNewFile) model.getElementAt(ii); boolean delSuccess = false; boolean renameSuccess = false; if (delSuccess = file.oldFile.delete()) { renameSuccess = file.newFile.renameTo(file.oldFile); } sb.append(file.oldFile.getName() + " del:" + (delSuccess ? "T" : "F") + " rename:" + (renameSuccess ? "T" : "F") + "\n"); } JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog(sb, getTitle()); } }); } } { jPanel5 = new JPanel(); BorderLayout jPanel5Layout = new BorderLayout(); jPanel5.setLayout(jPanel5Layout); jTabbedPane1.addTab("template", null, jPanel5, null); { jScrollPane3 = new JScrollPane(); jPanel5.add(jScrollPane3, BorderLayout.CENTER); { templateList = new JList(); reloadTemplateList(); jScrollPane3.setViewportView(templateList); templateList.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent evt) { if (templateList.getLeadSelectionIndex() == -1) { return; } Entry<Object, Object> entry = (Entry<Object, Object>) JListUtil .getLeadSelectionObject(templateList); repFromText.setText((String) entry.getKey()); repToText.setText((String) entry.getValue()); } }); templateList.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent evt) { JListUtil.newInstance(templateList).defaultJListKeyPressed(evt); } }); } } { scheduleExecute = new JButton(); jPanel5.add(scheduleExecute, BorderLayout.SOUTH); scheduleExecute.setText("schedule execute"); scheduleExecute.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { scheduleExecuteActionPerformed(evt); } }); } } } this.setSize(512, 350); JCommonUtil.setFontAll(this.getRootPane()); JCommonUtil.frameCloseDo(this, new WindowAdapter() { public void windowClosing(WindowEvent paramWindowEvent) { if (StringUtils.isNotBlank(repFromText.getText())) { prop.put(repFromText.getText(), repToText.getText()); } try { prop.store(new FileOutputStream(propFile), "regexText"); } catch (Exception e) { JCommonUtil.handleException("properties store error!", e); } setVisible(false); dispose(); } }); } catch (Exception e) { e.printStackTrace(); } }
From source file:it.unimi.di.big.mg4j.document.DocumentCollectionTest.java
/** Checks that the tokenizer and the word reader return exactly the same sequence of words. * //from w w w . j a v a 2 s. c om * @param wordReader the word reader. * @param tok the tokenizer. * @throws IOException */ private void checkSameWords(WordReader wordReader, StringTokenizer tok) throws IOException { MutableString word = new MutableString(); MutableString nonWord = new MutableString(); boolean aWordInDocum, aWordInDocument; boolean firstTime = true; for (;;) { aWordInDocum = wordReader.next(word, nonWord); if (firstTime) { firstTime = false; if (word.equals("")) continue; } assertFalse(aWordInDocum && word.equals("")); aWordInDocument = tok.hasMoreElements(); assertTrue(aWordInDocum == aWordInDocument); if (!aWordInDocum) break; assertEquals(tok.nextElement(), word.toString()); } }
From source file:com.webcohesion.enunciate.modules.csharp_client.CSharpXMLClientModule.java
private File compileSources(File srcDir) { File compileDir = getCompileDir(); compileDir.mkdirs();/* www.ja v a 2 s.c o m*/ if (!isDisableCompile()) { if (!isUpToDateWithSources(compileDir)) { String compileExectuable = getCompileExecutable(); if (compileExectuable == null) { String osName = System.getProperty("os.name"); if (osName != null && osName.toUpperCase().contains("WINDOWS")) { //try the "csc" command on Windows environments. debug("Attempting to execute command \"csc /help\" for the current environment (%s).", osName); try { Process process = new ProcessBuilder("csc", "/help").redirectErrorStream(true).start(); InputStream in = process.getInputStream(); byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len > -0) { len = in.read(buffer); } int exitCode = process.waitFor(); if (exitCode != 0) { debug("Command \"csc /help\" failed with exit code " + exitCode + "."); } else { compileExectuable = "csc"; debug("C# compile executable to be used: csc"); } } catch (Throwable e) { debug("Command \"csc /help\" failed (" + e.getMessage() + ")."); } } if (compileExectuable == null) { //try the "gmcs" command (Mono) debug("Attempting to execute command \"gmcs /help\" for the current environment (%s).", osName); try { Process process = new ProcessBuilder("gmcs", "/help").redirectErrorStream(true).start(); InputStream in = process.getInputStream(); byte[] buffer = new byte[1024]; int len = in.read(buffer); while (len > -0) { len = in.read(buffer); } int exitCode = process.waitFor(); if (exitCode != 0) { debug("Command \"gmcs /help\" failed with exit code " + exitCode + "."); } else { compileExectuable = "gmcs"; debug("C# compile executable to be used: %s", compileExectuable); } } catch (Throwable e) { debug("Command \"gmcs /help\" failed (" + e.getMessage() + ")."); } } if (compileExectuable == null && isRequire()) { throw new EnunciateException( "C# client code generation is required, but there was no valid compile executable found. " + "Please supply one in the configuration file, or set it up on your system path."); } } String compileCommand = getCompileCommand(); if (compileCommand == null) { throw new IllegalStateException( "Somehow the \"compile\" step was invoked on the C# module without a valid compile command."); } compileCommand = compileCommand.replace(' ', '\0'); //replace all spaces with the null character, so the command can be tokenized later. File dll = new File(compileDir, getDLLFileName()); File docXml = new File(compileDir, getDocXmlFileName()); File sourceFile = new File(srcDir, getSourceFileName()); compileCommand = String.format(compileCommand, compileExectuable, dll.getAbsolutePath(), docXml.getAbsolutePath(), sourceFile.getAbsolutePath()); StringTokenizer tokenizer = new StringTokenizer(compileCommand, "\0"); //tokenize on the null character to preserve the spaces in the command. List<String> command = new ArrayList<String>(); while (tokenizer.hasMoreElements()) { command.add((String) tokenizer.nextElement()); } try { Process process = new ProcessBuilder(command).redirectErrorStream(true).directory(compileDir) .start(); BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = procReader.readLine(); while (line != null) { info(line); line = procReader.readLine(); } int procCode; try { procCode = process.waitFor(); } catch (InterruptedException e1) { throw new EnunciateException("Unexpected inturruption of the C# compile process."); } if (procCode != 0) { throw new EnunciateException("C# compile failed."); } } catch (IOException e) { throw new EnunciateException(e); } FileArtifact assembly = new FileArtifact(getName(), "csharp.assembly", dll); assembly.setPublic(false); enunciate.addArtifact(assembly); if (docXml.exists()) { FileArtifact docs = new FileArtifact(getName(), "csharp.docs.xml", docXml); docs.setPublic(false); enunciate.addArtifact(docs); } } else { info("Skipping C# compile because everything appears up-to-date."); } } else { debug("Skipping C# compile because a compile executable was neither found nor provided. The C# bundle will only include the sources."); } return compileDir; }
From source file:org.mifos.customers.client.struts.actionforms.ClientCustActionForm.java
public String removeSpaces(String s) { StringTokenizer st = new StringTokenizer(s, " ", false); String t = ""; while (st.hasMoreElements()) { t += st.nextElement(); }/*from w w w.j a v a 2 s . co m*/ return t; }
From source file:org.apache.jcs.access.TestCacheAccess.java
License:asdf
/** * This is the main loop called by the main method. *//* ww w.j a v a2 s . com*/ public void runLoop() { try { try { // process user input till done boolean notDone = true; String message = null; // wait to dispose BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); help(); while (notDone) { p("enter command:"); message = br.readLine(); if (message.startsWith("help")) { help(); } else if (message.startsWith("gc")) { System.gc(); } else if (message.startsWith("getAttributeNames")) { long n_start = System.currentTimeMillis(); String groupName = null; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { groupName = t.trim(); } } getAttributeNames(groupName); long n_end = System.currentTimeMillis(); p("---got attrNames for " + groupName + " in " + String.valueOf(n_end - n_start) + " millis ---"); } else if (message.startsWith("shutDown")) { CompositeCacheManager.getInstance().shutDown(); //cache_control.dispose(); notDone = false; //System.exit( -1 ); return; } else ///////////////////////////////////////////////////////////////////// // get multiple from a region if (message.startsWith("getm")) { int num = 0; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { try { num = Integer.parseInt(t.trim()); } catch (NumberFormatException nfe) { p(t + "not a number"); } } else if (tcnt == 3) { show = new Boolean(t).booleanValue(); } } if (tcnt < 2) { p("usage: get numbertoget show values[true|false]"); } else { getMultiple(num, show); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("getg")) { String key = null; String group = null; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { key = t.trim(); } else if (tcnt == 3) { group = t.trim(); } else if (tcnt == 4) { show = new Boolean(t).booleanValue(); } } if (tcnt < 2) { p("usage: get key show values[true|false]"); } else { long n_start = System.currentTimeMillis(); try { Object obj = cache_control.getFromGroup(key, group); if (show && obj != null) { p(obj.toString()); } } catch (Exception e) { log.error(e); } long n_end = System.currentTimeMillis(); p("---got " + key + " from group " + group + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("getag")) { // get auto from group int num = 0; String group = null; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { num = Integer.parseInt(t.trim()); } else if (tcnt == 3) { group = t.trim(); } else if (tcnt == 4) { show = new Boolean(t).booleanValue(); } } if (tcnt < 2) { p("usage: get key show values[true|false]"); } else { long n_start = System.currentTimeMillis(); try { for (int a = 0; a < num; a++) { Object obj = cache_control.getFromGroup("keygr" + a, group); if (show && obj != null) { p(obj.toString()); } } } catch (Exception e) { log.error(e); } long n_end = System.currentTimeMillis(); p("---got " + num + " from group " + group + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("get")) { // plain old get String key = null; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { key = t.trim(); } else if (tcnt == 3) { show = new Boolean(t).booleanValue(); } } if (tcnt < 2) { p("usage: get key show values[true|false]"); } else { long n_start = System.currentTimeMillis(); try { Object obj = cache_control.get(key); if (show && obj != null) { p(obj.toString()); } } catch (Exception e) { log.error(e); } long n_end = System.currentTimeMillis(); p("---got " + key + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else if (message.startsWith("putg")) { String group = null; String key = null; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { key = t.trim(); } else if (tcnt == 3) { group = t.trim(); } } if (tcnt < 3) { p("usage: putg key group"); } else { long n_start = System.currentTimeMillis(); cache_control.putInGroup(key, group, "data from putg ----asdfasfas-asfasfas-asfas in group " + group); long n_end = System.currentTimeMillis(); p("---put " + key + " in group " + group + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else // put automatically if (message.startsWith("putag")) { String group = null; int num = 0; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { num = Integer.parseInt(t.trim()); } else if (tcnt == 3) { group = t.trim(); } } if (tcnt < 3) { p("usage: putag num group"); } else { long n_start = System.currentTimeMillis(); for (int a = 0; a < num; a++) { cache_control.putInGroup("keygr" + a, group, "data " + a + " from putag ----asdfasfas-asfasfas-asfas in group " + group); } long n_end = System.currentTimeMillis(); p("---put " + num + " in group " + group + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("putm")) { String numS = message.substring(message.indexOf(" ") + 1, message.length()); int num = Integer.parseInt(numS.trim()); if (numS == null) { p("usage: putm numbertoput"); } else { putMultiple(num); } } else ///////////////////////////////////////////////////////////////////// if (message.startsWith("pute")) { String numS = message.substring(message.indexOf(" ") + 1, message.length()); int num = Integer.parseInt(numS.trim()); if (numS == null) { p("usage: putme numbertoput"); } else { long n_start = System.currentTimeMillis(); for (int n = 0; n < num; n++) { IElementAttributes attrp = cache_control.getDefaultElementAttributes(); ElementEventHandlerMockImpl hand = new ElementEventHandlerMockImpl(); attrp.addElementEventHandler(hand); cache_control.put("key" + n, "data" + n + " put from ta = junk", attrp); } long n_end = System.currentTimeMillis(); p("---put " + num + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else if (message.startsWith("put")) { String key = null; String val = null; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { key = t.trim(); } else if (tcnt == 3) { val = t.trim(); } } if (tcnt < 3) { p("usage: put key val"); } else { long n_start = System.currentTimeMillis(); cache_control.put(key, val); long n_end = System.currentTimeMillis(); p("---put " + key + " | " + val + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } ///////////////////////////////////////////////////////////////////// if (message.startsWith("removem")) { String numS = message.substring(message.indexOf(" ") + 1, message.length()); int num = Integer.parseInt(numS.trim()); if (numS == null) { p("usage: removem numbertoremove"); } else { removeMultiple(num); } } else if (message.startsWith("removeall")) { cache_control.clear(); p("removed all"); } else if (message.startsWith("remove")) { String key = message.substring(message.indexOf(" ") + 1, message.length()); cache_control.remove(key); p("removed " + key); } else if (message.startsWith("deattr")) { IElementAttributes ae = cache_control.getDefaultElementAttributes(); p("Default IElementAttributes " + ae); } else if (message.startsWith("cloneattr")) { String numS = message.substring(message.indexOf(" ") + 1, message.length()); int num = Integer.parseInt(numS.trim()); if (numS == null) { p("usage: put numbertoput"); } else { IElementAttributes attrp = new ElementAttributes(); long n_start = System.currentTimeMillis(); for (int n = 0; n < num; n++) { attrp.copy(); } long n_end = System.currentTimeMillis(); p("---cloned attr " + num + " in " + String.valueOf(n_end - n_start) + " millis ---"); } } else if (message.startsWith("switch")) { String name = message.substring(message.indexOf(" ") + 1, message.length()); setRegion(name); p("switched to cache = " + name); p(cache_control.toString()); } else if (message.startsWith("stats")) { p(cache_control.getStats()); } else if (message.startsWith("gc")) { System.gc(); p("Called system.gc()"); } else if (message.startsWith("random")) if (message.startsWith("random")) { String rangeS = ""; String numOpsS = ""; boolean show = true; StringTokenizer toke = new StringTokenizer(message); int tcnt = 0; while (toke.hasMoreElements()) { tcnt++; String t = (String) toke.nextElement(); if (tcnt == 2) { rangeS = t.trim(); } else if (tcnt == 3) { numOpsS = t.trim(); } else if (tcnt == 4) { show = new Boolean(t).booleanValue(); } } String numS = message.substring(message.indexOf(" ") + 1, message.length()); int range = 0; int numOps = 0; try { range = Integer.parseInt(rangeS.trim()); numOps = Integer.parseInt(numOpsS.trim()); } catch (Exception e) { p("usage: random range numOps show"); p("ex. random 100 1000 false"); } if (numS == null) { p("usage: random range numOps show"); p("ex. random 100 1000 false"); } else { random(range, numOps, show); } } } } catch (Exception e) { p(e.toString()); e.printStackTrace(System.out); } } catch (Exception e) { p(e.toString()); e.printStackTrace(System.out); } }
From source file:org.apache.cloudstack.storage.datastore.util.SolidFireUtil.java
public static String getValue(String keyToMatch, String url, boolean throwExceptionIfNotFound) { String delimiter1 = ";"; String delimiter2 = "="; StringTokenizer st = new StringTokenizer(url, delimiter1); while (st.hasMoreElements()) { String token = st.nextElement().toString(); int index = token.indexOf(delimiter2); if (index == -1) { throw new RuntimeException("Invalid URL format"); }/*from w w w . ja v a 2 s . co m*/ String key = token.substring(0, index); if (key.equalsIgnoreCase(keyToMatch)) { String valueToReturn = token.substring(index + delimiter2.length()); return valueToReturn; } } if (throwExceptionIfNotFound) { throw new RuntimeException("Key not found in URL"); } return null; }