List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:com.qframework.core.LayoutGrid.java
void animScreen(String resptype, String respdata) { if (resptype.equals("color")) { //"1000,FFFFFFFF,00000000,FFFFFFFF" StringTokenizer tok = new StringTokenizer(respdata, ","); GLColor color1 = mApp.colors().white; GLColor color2 = mApp.colors().black; GLColor color3 = null;//from w w w. ja va 2s .co m int delay = Integer.parseInt(tok.nextToken()); if (tok.hasMoreElements()) color1 = mApp.colors().getColor(tok.nextToken()); if (tok.hasMoreElements()) color2 = mApp.colors().getColor(tok.nextToken()); if (tok.hasMoreElements()) color3 = mApp.colors().getColor(tok.nextToken()); mApp.anims().createAnimColor(delay, color1, color2, color3); } }
From source file:org.candlepin.model.Product.java
@XmlTransient public List<String> getSkuEnabledContentIds() { List<String> skus = new LinkedList<String>(); ProductAttribute attrib = this.getAttribute(Attributes.CONTENT_OVERRIDE_ENABLED); if (attrib != null && attrib.getValue() != null && attrib.getValue().length() > 0) { StringTokenizer tokenizer = new StringTokenizer(attrib.getValue(), ","); while (tokenizer.hasMoreElements()) { skus.add((String) tokenizer.nextElement()); }//from www . ja v a 2s. c om } return skus; }
From source file:org.candlepin.model.Product.java
@XmlTransient public List<String> getSkuDisabledContentIds() { List<String> skus = new LinkedList<String>(); ProductAttribute attrib = this.getAttribute(Attributes.CONTENT_OVERRIDE_DISABLED); if (attrib != null && attrib.getValue() != null && attrib.getValue().length() > 0) { StringTokenizer tokenizer = new StringTokenizer(attrib.getValue(), ","); while (tokenizer.hasMoreElements()) { skus.add((String) tokenizer.nextElement()); }//from w w w . jav a 2 s . c o m } return skus; }
From source file:org.netbeans.nbbuild.MakeJnlp2.java
private void generateFiles() throws IOException, BuildException { final Set<String> declaredLocales = new HashSet<String>(); final boolean useAllLocales; if ("*".equals(includelocales)) { useAllLocales = true;/*from w w w . ja v a 2 s .c om*/ } else if ("".equals(includelocales)) { useAllLocales = false; } else { useAllLocales = false; StringTokenizer tokenizer = new StringTokenizer(includelocales, ","); while (tokenizer.hasMoreElements()) { declaredLocales.add(tokenizer.nextToken()); } } final Set<String> indirectFilePaths = new HashSet<String>(); for (FileSet fs : new FileSet[] { indirectJars, indirectFiles }) { if (fs != null) { DirectoryScanner scan = fs.getDirectoryScanner(getProject()); for (String f : scan.getIncludedFiles()) { indirectFilePaths.add(f.replace(File.pathSeparatorChar, '/')); } } } final ExecutorService executorService = Executors.newFixedThreadPool(nbThreads); final List<BuildException> exceptions = new ArrayList<BuildException>(); for (final Iterator fileIt = files.iterator(); fileIt.hasNext();) { if (!exceptions.isEmpty()) { break; } final FileResource fr = (FileResource) fileIt.next(); final File jar = fr.getFile(); if (!jar.canRead()) { throw new BuildException("Cannot read file: " + jar); } // if (optimize && checkDuplicate(jar).isPresent()) { continue; } // executorService.execute(new Runnable() { @Override public void run() { JarFile theJar = null; try { theJar = new JarFile(jar); String codenamebase = JarWithModuleAttributes .extractCodeName(theJar.getManifest().getMainAttributes()); if (codenamebase == null) { throw new BuildException("Not a NetBeans Module: " + jar); } { int slash = codenamebase.indexOf('/'); if (slash >= 0) { codenamebase = codenamebase.substring(0, slash); } } String dashcnb = codenamebase.replace('.', '-'); String title; String oneline; String shrt; String osDep = null; { String bundle = theJar.getManifest().getMainAttributes() .getValue("OpenIDE-Module-Localizing-Bundle"); Properties prop = new Properties(); if (bundle != null) { ZipEntry en = theJar.getEntry(bundle); if (en == null) { throw new BuildException("Cannot find entry: " + bundle + " in file: " + jar); } InputStream is = theJar.getInputStream(en); prop.load(is); is.close(); } title = prop.getProperty("OpenIDE-Module-Name", codenamebase); oneline = prop.getProperty("OpenIDE-Module-Short-Description", title); shrt = prop.getProperty("OpenIDE-Module-Long-Description", oneline); } { String osMan = theJar.getManifest().getMainAttributes() .getValue("OpenIDE-Module-Requires"); if (osMan != null) { if (osMan.indexOf("org.openide.modules.os.MacOSX") >= 0) { // NOI18N osDep = "Mac OS X"; // NOI18N } else if (osMan.indexOf("org.openide.modules.os.Linux") >= 0) { // NOI18N osDep = "Linux"; // NOI18N } else if (osMan.indexOf("org.openide.modules.os.Solaris") >= 0) { // NOI18N osDep = "Solaris"; // NOI18N } else if (osMan.indexOf("org.openide.modules.os.Windows") >= 0) { // NOI18N osDep = "Windows"; // NOI18N } } } Map<String, List<File>> localizedFiles = verifyExtensions(jar, theJar.getManifest(), dashcnb, codenamebase, verify, indirectFilePaths); executedLocales = localizedFiles.keySet(); new File(targetFile, dashcnb).mkdir(); File signed = new File(new File(targetFile, dashcnb), jar.getName()); // +p final JarConfigResolved jarConfig = signOrCopy(jar, signed); File jnlp = new File(targetFile, dashcnb + ".jnlp"); StringWriter writeJNLP = new StringWriter(); writeJNLP.write("<?xml version='1.0' encoding='UTF-8'?>\n"); writeJNLP.write( "<!DOCTYPE jnlp PUBLIC \"-//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0//EN\" \"http://java.sun.com/dtd/JNLP-6.0.dtd\">\n"); writeJNLP.write("<jnlp spec='1.0+' codebase='" + codebase + "'>\n"); writeJNLP.write(" <information>\n"); writeJNLP.write(" <title>" + XMLUtil.toElementContent(title) + "</title>\n"); writeJNLP.write(" <vendor>NetBeans</vendor>\n"); writeJNLP.write(" <description kind='one-line'>" + XMLUtil.toElementContent(oneline) + "</description>\n"); writeJNLP.write(" <description kind='short'>" + XMLUtil.toElementContent(shrt) + "</description>\n"); writeJNLP.write(" </information>\n"); String realPermissions = permissions; if ((jarConfig != null) && (jarConfig.getExtraManifestAttributes() != null)) { String jarPermissions = jarConfig.getExtraManifestAttributes().getValue("Permissions"); if (jarPermissions != null) { if ("all-permissions".equals(jarPermissions)) { realPermissions = "<security><all-permissions/></security>\n"; } else { realPermissions = ""; } } } writeJNLP.write(realPermissions); if (osDep == null) { writeJNLP.write(" <resources>\n"); } else { writeJNLP.write(" <resources os='" + osDep + "'>\n"); } writeJNLP.write("<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf(pack200) + "\"/>\n"); writeJNLP.write(constructJarHref(jar, dashcnb)); processExtensions(jar, theJar.getManifest(), writeJNLP, dashcnb, codebase, realPermissions); processIndirectJars(writeJNLP, dashcnb); processIndirectFiles(writeJNLP, dashcnb); writeJNLP.write(" </resources>\n"); if (useAllLocales || !declaredLocales.isEmpty()) { // write down locales for (Map.Entry<String, List<File>> e : localizedFiles.entrySet()) { final String locale = e.getKey(); if (!declaredLocales.isEmpty() && !declaredLocales.contains(locale)) { continue; } final List<File> allFiles = e.getValue(); writeJNLP.write(" <resources locale='" + locale + "'>\n"); for (File n : allFiles) { log("generating locale " + locale + " for " + n, Project.MSG_VERBOSE); String name = n.getName(); String clusterRootPrefix = jar.getParent() + File.separatorChar; String absname = n.getAbsolutePath(); if (absname.startsWith(clusterRootPrefix)) { name = absname.substring(clusterRootPrefix.length()) .replace(File.separatorChar, '-'); } File t = new File(new File(targetFile, dashcnb), name); signOrCopy(n, t); writeJNLP.write(constructJarHref(n, dashcnb, name)); } writeJNLP.write(" </resources>\n"); } } writeJNLP.write(" <component-desc/>\n"); writeJNLP.write("</jnlp>\n"); writeJNLP.close(); // +p Files.write(writeJNLP.toString(), jnlp, Charset.forName("UTF-8")); } catch (Exception e) { exceptions.add(new BuildException(e)); } finally { if (theJar != null) { try { theJar.close(); } catch (IOException e) { } } } } }); } executorService.shutdown(); try { executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (Exception e) { throw new BuildException(e); } if (!exceptions.isEmpty()) { throw exceptions.get(0); } }
From source file:nl.nn.adapterframework.http.HttpSenderBase.java
@Override public String sendMessageWithTimeoutGuarded(String correlationID, String message, ParameterResolutionContext prc) throws SenderException, TimeOutException { ParameterValueList pvl = null;/*from w ww . j a v a2 s . c o m*/ try { if (prc != null && paramList != null) { pvl = prc.getValues(paramList); } } catch (ParameterException e) { throw new SenderException( getLogPrefix() + "Sender [" + getName() + "] caught exception evaluating parameters", e); } HttpHost httpTarget; URIBuilder uri; HttpRequestBase httpRequestBase; try { if (urlParameter != null) { String url = (String) pvl.getParameterValue(getUrlParam()).getValue(); uri = getURI(url); } else { uri = staticUri; } httpTarget = new HttpHost(uri.getHost(), getPort(uri), uri.getScheme()); Map<String, String> headersParamsMap = new HashMap<String, String>(); if (headersParams != null) { StringTokenizer st = new StringTokenizer(headersParams, ","); while (st.hasMoreElements()) { headersParamsMap.put(st.nextToken(), null); } } if (isEncodeMessages()) { message = URLEncoder.encode(message, getCharSet()); } httpRequestBase = getMethod(uri, message, pvl, headersParamsMap, (prc == null) ? null : prc.getSession()); if (httpRequestBase == null) throw new MethodNotSupportedException( "could not find implementation for method [" + getMethodType() + "]"); if (StringUtils.isNotEmpty(getContentType())) { httpRequestBase.setHeader("Content-Type", getContentType()); } if (credentials != null && !StringUtils.isEmpty(credentials.getUsername())) { AuthCache authCache = httpClientContext.getAuthCache(); if (authCache == null) authCache = new BasicAuthCache(); if (authCache.get(httpTarget) == null) authCache.put(httpTarget, new BasicScheme()); httpClientContext.setAuthCache(authCache); } log.info(getLogPrefix() + "configured httpclient for host [" + uri.getHost() + "]"); } catch (Exception e) { throw new SenderException(e); } String result = null; int statusCode = -1; int count = getMaxExecuteRetries(); String msg = null; while (count-- >= 0 && statusCode == -1) { try { log.debug(getLogPrefix() + "executing method [" + httpRequestBase.getRequestLine() + "]"); HttpResponse httpResponse = getHttpClient().execute(httpTarget, httpRequestBase, httpClientContext); log.debug(getLogPrefix() + "executed method"); HttpResponseHandler responseHandler = new HttpResponseHandler(httpResponse); StatusLine statusline = httpResponse.getStatusLine(); statusCode = statusline.getStatusCode(); if (StringUtils.isNotEmpty(getResultStatusCodeSessionKey()) && prc != null) { prc.getSession().put(getResultStatusCodeSessionKey(), Integer.toString(statusCode)); } // Only give warnings for 4xx (client errors) and 5xx (server errors) if (statusCode >= 400 && statusCode < 600) { log.warn(getLogPrefix() + "status [" + statusline.toString() + "]"); } else { log.debug(getLogPrefix() + "status [" + statusCode + "]"); } result = extractResult(responseHandler, prc); log.debug(getLogPrefix() + "retrieved result [" + result + "]"); } catch (ClientProtocolException e) { StringBuilder msgBuilder = new StringBuilder(getLogPrefix() + "httpException with"); if (e.getMessage() != null) { msg = e.getMessage(); msgBuilder.append(" message [" + msg + "]"); } Throwable throwable = e.getCause(); if (throwable != null) { msgBuilder.append(" cause [" + throwable.toString() + "]"); } msgBuilder.append(" executeRetries left [" + count + "]"); log.warn(msgBuilder.toString()); } catch (IOException e) { httpRequestBase.abort(); if (e instanceof SocketTimeoutException) { throw new TimeOutException(e); } throw new SenderException(e); } finally { // By forcing the use of the HttpResponseHandler the resultStream // will automatically be closed when it has been read. // See HttpResponseHandler and ReleaseConnectionAfterReadInputStream. // We cannot close the connection as the response might be kept // in a sessionKey for later use in the pipeline. // // IMPORTANT: It is possible that poorly written implementations // wont read or close the response. // This will cause the connection to become stale.. } } if (statusCode == -1) { if (msg != null && StringUtils.contains(msg.toUpperCase(), "TIMEOUTEXCEPTION")) { //java.net.SocketTimeoutException: Read timed out throw new TimeOutException("Failed to recover from timeout exception"); } throw new SenderException("Failed to recover from exception"); } if (isXhtml() && StringUtils.isNotEmpty(result)) { result = XmlUtils.skipDocTypeDeclaration(result.trim()); if (result.startsWith("<html>") || result.startsWith("<html ")) { CleanerProperties props = new CleanerProperties(); HtmlCleaner cleaner = new HtmlCleaner(props); TagNode tagNode = cleaner.clean(result); result = new SimpleXmlSerializer(props).getAsString(tagNode); if (transformerPool != null) { log.debug(getLogPrefix() + " transforming result [" + result + "]"); ParameterResolutionContext prc_xslt = new ParameterResolutionContext(result, null, true); try { result = transformerPool.transform(prc_xslt.getInputSource(true), null); } catch (Exception e) { throw new SenderException("Exception on transforming input", e); } } } } return result; }
From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java
/** * <p>// www . j a va 2 s .com * Reads the manifest from the JAR file and collects the entries. Some * vendorKey entries are:</p> * <ul><li>Implementation Title</li> * <li>Implementation Version</li> <li>Implementation Vendor</li> * <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle * Version</li> <li>Bundle Vendor</li> <li>Bundle Description</li> <li>Main * Class</li> </ul> * However, all but a handful of specific entries are read in. * * @param dependency A reference to the dependency * @param classInformation a collection of class information * @return whether evidence was identified parsing the manifest * @throws IOException if there is an issue reading the JAR file */ protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation) throws IOException { boolean foundSomething = false; JarFile jar = null; try { jar = new JarFile(dependency.getActualFilePath()); final Manifest manifest = jar.getManifest(); if (manifest == null) { if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar") && !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar") && !dependency.getFileName().toLowerCase().endsWith("-src.jar") && !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) { LOGGER.debug("Jar file '{}' does not contain a manifest.", dependency.getFileName()); } return false; } final EvidenceCollection vendorEvidence = dependency.getVendorEvidence(); final EvidenceCollection productEvidence = dependency.getProductEvidence(); final EvidenceCollection versionEvidence = dependency.getVersionEvidence(); String source = "Manifest"; String specificationVersion = null; boolean hasImplementationVersion = false; Attributes atts = manifest.getMainAttributes(); for (Entry<Object, Object> entry : atts.entrySet()) { String key = entry.getKey().toString(); String value = atts.getValue(key); if (HTML_DETECTION_PATTERN.matcher(value).find()) { value = Jsoup.parse(value).text(); } if (IGNORE_VALUES.contains(value)) { continue; } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) { foundSomething = true; productEvidence.addEvidence(source, key, value, Confidence.HIGH); addMatchingValues(classInformation, value, productEvidence); } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) { hasImplementationVersion = true; foundSomething = true; versionEvidence.addEvidence(source, key, value, Confidence.HIGH); } else if ("specification-version".equalsIgnoreCase(key)) { specificationVersion = key; } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) { foundSomething = true; vendorEvidence.addEvidence(source, key, value, Confidence.HIGH); addMatchingValues(classInformation, value, vendorEvidence); } else if (key.equalsIgnoreCase(IMPLEMENTATION_VENDOR_ID)) { foundSomething = true; vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, vendorEvidence); } else if (key.equalsIgnoreCase(BUNDLE_DESCRIPTION)) { foundSomething = true; addDescription(dependency, value, "manifest", key); addMatchingValues(classInformation, value, productEvidence); } else if (key.equalsIgnoreCase(BUNDLE_NAME)) { foundSomething = true; productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, productEvidence); // //the following caused false positives. // } else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) { // foundSomething = true; // vendorEvidence.addEvidence(source, key, value, Confidence.HIGH); // addMatchingValues(classInformation, value, vendorEvidence); } else if (key.equalsIgnoreCase(BUNDLE_VERSION)) { foundSomething = true; versionEvidence.addEvidence(source, key, value, Confidence.HIGH); } else if (key.equalsIgnoreCase(Attributes.Name.MAIN_CLASS.toString())) { continue; //skipping main class as if this has important information to add // it will be added during class name analysis... if other fields // have the information from the class name then they will get added... } else { key = key.toLowerCase(); if (!IGNORE_KEYS.contains(key) && !key.endsWith("jdk") && !key.contains("lastmodified") && !key.endsWith("package") && !key.endsWith("classpath") && !key.endsWith("class-path") && !key.endsWith("-scm") //todo change this to a regex? && !key.startsWith("scm-") && !value.trim().startsWith("scm:") && !isImportPackage(key, value) && !isPackage(key, value)) { foundSomething = true; if (key.contains("version")) { if (!key.contains("specification")) { versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM); } } else if ("build-id".equals(key)) { int pos = value.indexOf('('); if (pos >= 0) { value = value.substring(0, pos - 1); } pos = value.indexOf('['); if (pos >= 0) { value = value.substring(0, pos - 1); } versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM); } else if (key.contains("title")) { productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, productEvidence); } else if (key.contains("vendor")) { if (key.contains("specification")) { vendorEvidence.addEvidence(source, key, value, Confidence.LOW); } else { vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, vendorEvidence); } } else if (key.contains("name")) { productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, vendorEvidence); addMatchingValues(classInformation, value, productEvidence); } else if (key.contains("license")) { addLicense(dependency, value); } else if (key.contains("description")) { addDescription(dependency, value, "manifest", key); } else { productEvidence.addEvidence(source, key, value, Confidence.LOW); vendorEvidence.addEvidence(source, key, value, Confidence.LOW); addMatchingValues(classInformation, value, vendorEvidence); addMatchingValues(classInformation, value, productEvidence); if (value.matches(".*\\d.*")) { final StringTokenizer tokenizer = new StringTokenizer(value, " "); while (tokenizer.hasMoreElements()) { final String s = tokenizer.nextToken(); if (s.matches("^[0-9.]+$")) { versionEvidence.addEvidence(source, key, s, Confidence.LOW); } } } } } } } for (Map.Entry<String, Attributes> item : manifest.getEntries().entrySet()) { final String name = item.getKey(); source = "manifest: " + name; atts = item.getValue(); for (Entry<Object, Object> entry : atts.entrySet()) { final String key = entry.getKey().toString(); final String value = atts.getValue(key); if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) { foundSomething = true; productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, productEvidence); } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) { foundSomething = true; versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM); } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) { foundSomething = true; vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, vendorEvidence); } else if (key.equalsIgnoreCase(Attributes.Name.SPECIFICATION_TITLE.toString())) { foundSomething = true; productEvidence.addEvidence(source, key, value, Confidence.MEDIUM); addMatchingValues(classInformation, value, productEvidence); } } } if (specificationVersion != null && !hasImplementationVersion) { foundSomething = true; versionEvidence.addEvidence(source, "specification-version", specificationVersion, Confidence.HIGH); } } finally { if (jar != null) { jar.close(); } } return foundSomething; }
From source file:com.sshtools.j2ssh.SftpClient.java
/** * <p>/*ww w . j a va 2s .co m*/ * Create a directory or set of directories. This method will not fail even * if the directories exist. It is advisable to test whether the directory * exists before attempting an operation by using the <code>stat</code> * method to return the directories attributes. * </p> * * @param dir the path of directories to create. */ public void mkdirs(String dir) { StringTokenizer tokens = new StringTokenizer(dir, "/"); String path = dir.startsWith("/") ? "/" : ""; while (tokens.hasMoreElements()) { path += (String) tokens.nextElement(); try { stat(path); } catch (IOException ex) { try { mkdir(path); } catch (IOException ex2) { } } path += "/"; } }
From source file:org.trafodion.dtm.TmAuditTlog.java
public boolean deleteAgedEntries(final long lvAsn) throws IOException { if (LOG.isTraceEnabled()) LOG.trace("deleteAgedEntries start: Entries older than " + lvAsn + " will be removed"); HTableInterface deleteTable;//from w w w . j av a2s. c om for (int i = 0; i < tlogNumLogs; i++) { String lv_tLogName = new String(TLOG_TABLE_NAME + "_LOG_" + Integer.toHexString(i)); // Connection deleteConnection = ConnectionFactory.createConnection(this.config); HConnection deleteConnection = HConnectionManager.createConnection(this.config); deleteTable = deleteConnection.getTable(TableName.valueOf(lv_tLogName)); try { Scan s = new Scan(); s.setCaching(100); s.setCacheBlocks(false); ArrayList<Delete> deleteList = new ArrayList<Delete>(); ResultScanner ss = deleteTable.getScanner(s); try { for (Result r : ss) { for (Cell cell : r.rawCells()) { String valueString = new String(CellUtil.cloneValue(cell)); StringTokenizer st = new StringTokenizer(valueString, ","); if (st.hasMoreElements()) { String asnToken = st.nextElement().toString(); String transidToken = st.nextElement().toString(); String stateToken = st.nextElement().toString(); if ((Long.parseLong(asnToken) < lvAsn) && (stateToken.equals("FORGOTTEN"))) { String rowKey = new String(r.getRow()); Delete del = new Delete(r.getRow()); if (LOG.isTraceEnabled()) LOG.trace("adding transid: " + transidToken + " to delete list"); deleteList.add(del); } else if ((Long.parseLong(asnToken) < lvAsn) && (stateToken.equals("COMMITTED") || stateToken.equals("ABORTED"))) { if (ageCommitted) { String rowKey = new String(r.getRow()); Delete del = new Delete(r.getRow()); if (LOG.isTraceEnabled()) LOG.trace("adding transid: " + transidToken + " to delete list"); deleteList.add(del); } else { String key = new String(r.getRow()); Get get = new Get(r.getRow()); get.setMaxVersions(versions); // will return last n versions of row Result lvResult = deleteTable.get(get); // byte[] b = lvResult.getValue(TLOG_FAMILY, ASN_STATE); // returns current version of value List<Cell> list = lvResult.getColumnCells(TLOG_FAMILY, ASN_STATE); // returns all versions of this column for (Cell element : list) { String value = new String(CellUtil.cloneValue(element)); StringTokenizer stok = new StringTokenizer(value, ","); if (stok.hasMoreElements()) { if (LOG.isTraceEnabled()) LOG.trace("Performing secondary search on (" + transidToken + ")"); asnToken = stok.nextElement().toString(); transidToken = stok.nextElement().toString(); stateToken = stok.nextElement().toString(); if ((Long.parseLong(asnToken) < lvAsn) && (stateToken.equals("FORGOTTEN"))) { Delete del = new Delete(r.getRow()); if (LOG.isTraceEnabled()) LOG.trace("Secondary search found new delete - adding (" + transidToken + ") with asn: " + asnToken + " to delete list"); deleteList.add(del); break; } else { if (LOG.isTraceEnabled()) LOG.trace("Secondary search skipping entry with asn: " + asnToken + ", state: " + stateToken + ", transid: " + transidToken); } } } } } else { if (LOG.isTraceEnabled()) LOG.trace("deleteAgedEntries skipping asn: " + asnToken + ", transid: " + transidToken + ", state: " + stateToken); } } } } } catch (Exception e) { LOG.error("deleteAgedEntries Exception getting results for table index " + i + "; " + e); throw new RuntimeException(e); } finally { ss.close(); } if (LOG.isTraceEnabled()) LOG.trace("attempting to delete list with " + deleteList.size() + " elements"); try { deleteTable.delete(deleteList); } catch (IOException e) { LOG.error("deleteAgedEntries Exception deleting from table index " + i + "; " + e); throw new RuntimeException(e); } } catch (IOException e) { LOG.error("deleteAgedEntries IOException setting up scan on table index " + i); e.printStackTrace(); } finally { try { deleteTable.close(); deleteConnection.close(); } catch (IOException e) { LOG.error("deleteAgedEntries IOException closing table or connection for table index " + i); e.printStackTrace(); } } } if (LOG.isTraceEnabled()) LOG.trace("deleteAgedEntries - exit"); return true; }
From source file:org.jabsorb.JSONRPCBridge.java
/** * Call a method using a JSON-RPC request object. * * @param context The transport context (the HttpServletRequest and * HttpServletResponse objects in the case of the HTTP transport). * * @param jsonReq The JSON-RPC request structured as a JSON object tree. * * @return a JSONRPCResult object with the result of the invocation or an * error.//from w w w .j a va 2 s . c o m */ public JSONRPCResult call(Object context[], JSONObject jsonReq) { // #1: Parse the request final String encodedMethod; final Object requestId; final JSONArray arguments; final JSONArray fixups; try { encodedMethod = jsonReq.getString("method"); arguments = jsonReq.getJSONArray("params"); requestId = jsonReq.opt("id"); fixups = jsonReq.optJSONArray("fixups"); } catch (JSONException e) { log.error("no method or parameters in request"); return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD); } if (log.isDebugEnabled()) { if (fixups != null) { log.debug("call " + encodedMethod + "(" + arguments + ")" + ", requestId=" + requestId); } else { log.debug("call " + encodedMethod + "(" + arguments + ")" + ", fixups=" + fixups + ", requestId=" + requestId); } } // apply the fixups (if any) to the parameters. This will result // in a JSONArray that might have circular references-- so // the toString method (or anything that internally tries to traverse // the JSON (without being aware of this) should not be called after this // point if (fixups != null) { try { for (int i = 0; i < fixups.length(); i++) { JSONArray assignment = fixups.getJSONArray(i); JSONArray fixup = assignment.getJSONArray(0); JSONArray original = assignment.getJSONArray(1); applyFixup(arguments, fixup, original); } } catch (JSONException e) { log.error("error applying fixups", e); return new JSONRPCResult(JSONRPCResult.CODE_ERR_FIXUP, requestId, JSONRPCResult.MSG_ERR_FIXUP + ": " + e.getMessage()); } } // #2: Get the name of the class and method from the encodedMethod final String className; final String methodName; { StringTokenizer t = new StringTokenizer(encodedMethod, "."); if (t.hasMoreElements()) { className = t.nextToken(); } else { className = null; } if (t.hasMoreElements()) { methodName = t.nextToken(); } else { methodName = null; } } // #3: Get the id of the object (if it exists) from the className // (in the format: ".obj#<objectID>") final int objectID; { final int objectStartIndex = encodedMethod.indexOf('['); final int objectEndIndex = encodedMethod.indexOf(']'); if (encodedMethod.startsWith(OBJECT_METHOD_PREFIX) && (objectStartIndex != -1) && (objectEndIndex != -1) && (objectStartIndex < objectEndIndex)) { objectID = Integer.parseInt(encodedMethod.substring(objectStartIndex + 1, objectEndIndex)); } else { objectID = 0; } } // #4: Handle list method calls if ((objectID == 0) && (encodedMethod.equals("system.listMethods"))) { return new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, getSystemMethods()); } // #5: Get the object to act upon and the possible method that could be // called on it final Map methodMap; final Object javascriptObject; final AccessibleObject ao; try { javascriptObject = getObjectContext(objectID, className); methodMap = getAccessibleObjectMap(objectID, className, methodName); // #6: Resolve the method ao = AccessibleObjectResolver.resolveMethod(methodMap, methodName, arguments, ser); if (ao == null) { throw new NoSuchMethodException(JSONRPCResult.MSG_ERR_NOMETHOD); } } catch (NoSuchMethodException e) { if (e.getMessage().equals(JSONRPCResult.MSG_ERR_NOCONSTRUCTOR)) { return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOCONSTRUCTOR, requestId, JSONRPCResult.MSG_ERR_NOCONSTRUCTOR); } return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId, JSONRPCResult.MSG_ERR_NOMETHOD); } // #7: Call the method JSONRPCResult r = AccessibleObjectResolver.invokeAccessibleObject(ao, context, arguments, javascriptObject, requestId, ser, cbc, exceptionTransformer); return r; }
From source file:org.kchine.rpf.db.DBLayer.java
public void applyDBScript(InputStream scriptInputStream) throws RemoteException, NotBoundException, AccessException { Statement stmt = null;//from w ww . j a v a2 s . c o m ResultSet rset = null; try { checkConnection(); stmt = _connection.createStatement(); BufferedReader br = new BufferedReader(new InputStreamReader(scriptInputStream)); String line = null; StringBuffer sbuffer = new StringBuffer(); try { while ((line = br.readLine()) != null) { sbuffer.append(line.trim()); sbuffer.append(" "); } } catch (Exception e) { e.printStackTrace(); } StringTokenizer st = new StringTokenizer(replaceCode(sbuffer.toString()), ";"); while (st.hasMoreElements()) { String statmentStr = ((String) st.nextElement()).trim(); if (statmentStr.equals("")) continue; System.out.println("<" + statmentStr + ">"); try { if (statmentStr.trim().equalsIgnoreCase("commit")) { _connection.commit(); } else { stmt.execute(statmentStr); } System.out.println("OK"); } catch (SQLException sqle) { if (statmentStr.toUpperCase().startsWith("DROP")) { System.out.println("NOK / " + statmentStr + " Failed "); } else { sqle.printStackTrace(); } } } } catch (SQLException sqle) { if (isNoConnectionError(sqle) && canReconnect()) { applyDBScript(scriptInputStream); } else { throw new RemoteException("", (sqle)); } } finally { if (stmt != null) try { stmt.close(); } catch (Exception e) { throw new RemoteException("", (e)); } if (rset != null) try { stmt.close(); } catch (Exception e) { throw new RemoteException("", (e)); } } }