List of usage examples for java.util TreeSet iterator
public Iterator<E> iterator()
From source file:org.jcamp.parser.CommonSpectrumJCAMPReader.java
License:asdf
/** * gets ##XYPOINTS= content//from w w w . j a va2s .c o m * * @return double[] * @param block JCAMPBlock * @param nPoints int number of data points (from ##NPOINTS=) * @exception JCAMPException The exception description. */ protected double[][] getXYPoints(JCAMPBlock block, int nPoints, double xFactor, double yFactor) throws JCAMPException { class XYPair implements Comparable<XYPair> { public double x; public double y; public XYPair(double x, double y) { this.x = x; this.y = y; } @Override public int compareTo(XYPair o) { XYPair p = o; if (this.x < p.x) { return -1; } if (this.x > p.x) { return 1; } return 0; } } ; JCAMPDataRecord ldrXYPoints = block.getDataRecord("XYPOINTS"); if (ldrXYPoints == null) { throw new JCAMPException("missing required label ##XYPOINTS="); } int i = 0; AFFNTokenizer tokenizer = new AFFNTokenizer(ldrXYPoints); TreeSet<XYPair> data = new TreeSet<XYPair>(); while (tokenizer.hasMoreGroups()) { AFFNGroup group = tokenizer.nextGroup(); data.add(new XYPair(xFactor * group.getValue(0), yFactor * group.getValue(1))); } if (data.size() != nPoints) { if (log.isErrorEnabled()) { log.error("bad ##NPOINTS= or duplicate X values"); } } double[][] xy = new double[2][data.size()]; for (Iterator<XYPair> it = data.iterator(); it.hasNext();) { XYPair p = it.next(); xy[0][i] = p.x; xy[1][i] = p.y; } return xy; }
From source file:geogebra.kernel.EquationSolver.java
/** * Calculates all roots of a polynomial given by eqn using Laguerres method. * Polishes roots found. The roots are stored in eqn again. * @param eqn: coefficients of polynomial *//*from ww w .java2 s . c om*/ private int laguerreAllComplex(double[] real, double[] complex) { Complex[] complexRoots = null; try { if (laguerreSolver == null) { laguerreSolver = new LaguerreSolver(); } complexRoots = laguerreSolver.solveAll(real, LAGUERRE_START); } catch (Exception e) { Application.debug("Problem solving with LaguerreSolver" + e.getLocalizedMessage()); return 0; } // sort by real part & remove duplicates TreeSet<Complex> sortedSet = new TreeSet<Complex>(getComparatorReal()); for (int i = 0; i < complexRoots.length; i++) { sortedSet.add(complexRoots[i]); } int roots = 0; Complex temp; Iterator<Complex> iterator = sortedSet.iterator(); while (iterator.hasNext()) { temp = iterator.next(); real[roots] = temp.getReal(); complex[roots] = temp.getImaginary(); roots++; } return roots; }
From source file:org.zaproxy.zap.extension.ascanrulesBeta.UsernameEnumeration.java
/** * looks for username enumeration in the login page, by changing the username field to be a * valid / invalid user, and looking for differences in the response *//*from w w w. j a v a 2 s .co m*/ @Override public void scan() { // the technique to determine if usernames can be enumerated is as follows, using a variant // of the Freiling+Schinzel method, // adapted to the case where we do not know which is the username field // // 1) Request the original URL n times. (The original URL is assumed to have a valid // username, if not a valid password). Store the results in A[]. // 2) Compute the longest common subsequence (LCS) of A[] into LCS_A // 3) for each parameter in the original URL (ie, for URL params, form params, and cookie // params) // 4) Change the current parameter (which we assume is the username parameter) to an invalid // username (randomly), and request the URL n times. Store the results in B[]. // 5) Compute the longest common subsequence (LCS) of B[] into LCS_B // 6) If LCS_A <> LCS_B, then there is a Username Enumeration issue on the current parameter try { boolean loginUrl = false; // Are we dealing with a login url in any of the contexts of which this uri is part URI requestUri = getBaseMsg().getRequestHeader().getURI(); // using the session, get the list of contexts for the url List<Context> contextList = extAuth.getModel().getSession().getContextsForUrl(requestUri.getURI()); // now loop, and see if the url is a login url in each of the contexts in turn... for (Context context : contextList) { URI loginUri = extAuth.getLoginRequestURIForContext(context); if (loginUri != null) { if (requestUri.getScheme().equals(loginUri.getScheme()) && requestUri.getHost().equals(loginUri.getHost()) && requestUri.getPort() == loginUri.getPort() && requestUri.getPath().equals(loginUri.getPath())) { // we got this far.. only the method (GET/POST), user details, query params, // fragment, and POST params // are possibly different from the login page. loginUrl = true; log.info(requestUri.toString() + " falls within a context, and is the defined Login URL. Scanning for possible Username Enumeration vulnerability."); break; // Stop checking } } } // the Username Enumeration scanner will only run for logon pages if (loginUrl == false) { if (this.debugEnabled) { log.debug(requestUri.toString() + " is not a defined Login URL."); } return; // No need to continue for this URL } // find all params set in the request (GET/POST/Cookie) TreeSet<HtmlParameter> htmlParams = new TreeSet<>(); htmlParams.addAll(getBaseMsg().getRequestHeader().getCookieParams()); // request cookies only. no response cookies htmlParams.addAll(getBaseMsg().getFormParams()); // add in the POST params htmlParams.addAll(getBaseMsg().getUrlParams()); // add in the GET params int numberOfRequests = 0; if (this.getAttackStrength() == AttackStrength.INSANE) { numberOfRequests = 50; } else if (this.getAttackStrength() == AttackStrength.HIGH) { numberOfRequests = 15; } else if (this.getAttackStrength() == AttackStrength.MEDIUM) { numberOfRequests = 5; } else if (this.getAttackStrength() == AttackStrength.LOW) { numberOfRequests = 3; } // 1) Request the original URL n times. (The original URL is assumed to have a valid // username, if not a valid password). Store the results in A[]. // make sure to manually handle all redirects, and cookies that may be set in response. // allocate enough space for the responses StringBuilder responseA = null; StringBuilder responseB = null; String longestCommonSubstringA = null; String longestCommonSubstringB = null; for (int i = 0; i < numberOfRequests; i++) { // initialise the storage for this iteration // baseResponses[i]= new StringBuilder(250); responseA = new StringBuilder(250); HttpMessage msgCpy = getNewMsg(); // clone the request, but not the response sendAndReceive(msgCpy, false, false); // request the URL, but do not automatically follow redirects. // get all cookies set in the response TreeSet<HtmlParameter> cookies = msgCpy.getResponseHeader().getCookieParams(); int redirectCount = 0; while (HttpStatusCode.isRedirection(msgCpy.getResponseHeader().getStatusCode())) { redirectCount++; if (this.debugEnabled) log.debug("Following redirect " + redirectCount + " for message " + i + " of " + numberOfRequests + " iterations of the original query"); // append the response to the responses so far for this particular instance // this will give us a complete picture of the full set of actual traffic // associated with following redirects for the request responseA.append(msgCpy.getResponseHeader().getHeadersAsString()); responseA.append(msgCpy.getResponseBody().toString()); // and manually follow the redirect // create a new message from scratch HttpMessage msgRedirect = new HttpMessage(); // create a new URI from the absolute location returned, and interpret it as // escaped // note that the standard says that the Location returned should be absolute, // but it ain't always so... URI newLocation = new URI(msgCpy.getResponseHeader().getHeader(HttpHeader.LOCATION), true); try { msgRedirect.getRequestHeader().setURI(newLocation); } catch (Exception e) { // the Location field contents may not be standards compliant. Lets generate // a uri to use as a workaround where a relative path was // given instead of an absolute one URI newLocationWorkaround = new URI(msgCpy.getRequestHeader().getURI(), msgCpy.getResponseHeader().getHeader(HttpHeader.LOCATION), true); // try again, except this time, if it fails, don't try to handle it if (this.debugEnabled) log.debug("The Location [" + newLocation + "] specified in a redirect was not valid (not absolute?). Trying absolute workaround url [" + newLocationWorkaround + "]"); msgRedirect.getRequestHeader().setURI(newLocationWorkaround); } msgRedirect.getRequestHeader().setMethod(HttpRequestHeader.GET); // it's always a GET for a redirect msgRedirect.getRequestHeader().setContentLength(0); // since we send a GET, the body will be 0 long if (cookies.size() > 0) { // if a previous request sent back a cookie that has not since been // invalidated, we need to set that cookie when following redirects, as a // browser would msgRedirect.getRequestHeader().setCookieParams(cookies); } if (this.debugEnabled) log.debug("DEBUG: Following redirect to [" + newLocation + "]"); sendAndReceive(msgRedirect, false, false); // do NOT redirect.. handle it here // handle scenario where a cookie is unset in a subsequent iteration, or where // the same cookie name is later re-assigned a different value // ie, in these cases, do not simply (and dumbly) accumulate cookie detritus. // first get all cookies set in the response TreeSet<HtmlParameter> cookiesTemp = msgRedirect.getResponseHeader().getCookieParams(); for (Iterator<HtmlParameter> redirectSetsCookieIterator = cookiesTemp .iterator(); redirectSetsCookieIterator.hasNext();) { HtmlParameter cookieJustSet = redirectSetsCookieIterator.next(); // loop through each of the cookies we know about in cookies, to see if it // matches by name. // if so, delete that cookie, and add the one that was just set to cookies. // if not, add the one that was just set to cookies. for (Iterator<HtmlParameter> knownCookiesIterator = cookies.iterator(); knownCookiesIterator .hasNext();) { HtmlParameter knownCookie = knownCookiesIterator.next(); if (cookieJustSet.getName().equals(knownCookie.getName())) { knownCookiesIterator.remove(); break; // out of the loop for known cookies, back to the next cookie // set in the response } } // end of loop for cookies we already know about // we can now safely add the cookie that was just set into cookies, knowing // it does not clash with anything else in there. cookies.add(cookieJustSet); } // end of for loop for cookies just set in the redirect msgCpy = msgRedirect; // store the last redirect message into the MsgCpy, as we // will be using it's output in a moment.. } // end of loop to follow redirects // now that the redirections have all been handled.. was the request finally a // success or not? Successful or Failed Logins would normally both return an OK // HTTP status if (!HttpStatusCode.isSuccess(msgCpy.getResponseHeader().getStatusCode())) { log.warn("The original URL [" + getBaseMsg().getRequestHeader().getURI() + "] returned a non-OK HTTP status " + msgCpy.getResponseHeader().getStatusCode() + " (after " + i + " of " + numberOfRequests + " steps). Could be indicative of SQL Injection, or some other error. The URL is not stable enough to look at Username Enumeration"); return; // we have not even got as far as looking at the parameters, so just // abort straight out of the method } if (this.debugEnabled) log.debug("Done following redirects!"); // append the response to the responses so far for this particular instance // this will give us a complete picture of the full set of actual traffic associated // with following redirects for the request responseA.append(msgCpy.getResponseHeader().getHeadersAsString()); responseA.append(msgCpy.getResponseBody().toString()); // 2) Compute the longest common subsequence (LCS) of A[] into LCS_A // Note: in the Freiling and Schinzel method, this is calculated recursively. We // calculate it iteratively, but using an equivalent method // first time in, the LCS is simple: it's the first HTML result.. no diffing // required if (i == 0) longestCommonSubstringA = responseA.toString(); // else get the LCS of the existing string, and the current result else longestCommonSubstringA = this.longestCommonSubsequence(longestCommonSubstringA, responseA.toString()); // optimisation step: if the LCS of A is 0 characters long already, then the URL // output is not stable, and we can abort now, and save some time if (longestCommonSubstringA.length() == 0) { // this might occur if the output returned for the URL changed mid-way. Perhaps // a CAPTCHA has fired, or a WAF has kicked in. Let's abort now so. log.warn("The original URL [" + getBaseMsg().getRequestHeader().getURI() + "] does not produce stable output (at " + i + 1 + " of " + numberOfRequests + " steps). There is no static element in the output that can be used as a basis of comparison for the result of requesting URLs with the parameter values modified. Perhaps a CAPTCHA or WAF has kicked in!!"); return; // we have not even got as far as looking at the parameters, so just // abort straight out of the method } } // get rid of any remnants of cookie setting and Date headers in the responses, as these // cause false positives, and can be safely ignored // replace the content length with a non-variable placeholder // replace url parameters with a non-variable placeholder to eliminate tokens in URLs in // the output longestCommonSubstringA = longestCommonSubstringA.replaceAll("Set-Cookie:[^\\r\\n]+[\\r\\n]{1,2}", ""); longestCommonSubstringA = longestCommonSubstringA.replaceAll("Date:[^\\r\\n]+[\\r\\n]{1,2}", ""); longestCommonSubstringA = longestCommonSubstringA.replaceAll("Content-Length:[^\\r\\n]+[\\r\\n]{1,2}", "Content-Length: XXXX\n"); longestCommonSubstringA = longestCommonSubstringA .replaceAll("(?<=(&|\\?)[^\\?\"=&;]+=)[^\\?\"=&;]+(?=(&|\"))", "YYYY"); if (this.debugEnabled) log.debug("The LCS of A is [" + longestCommonSubstringA + "]"); // 3) for each parameter in the original URL (ie, for URL params, form params, and // cookie params) for (Iterator<HtmlParameter> iter = htmlParams.iterator(); iter.hasNext();) { HttpMessage msgModifiedParam = getNewMsg(); HtmlParameter currentHtmlParameter = iter.next(); if (this.debugEnabled) log.debug("Handling [" + currentHtmlParameter.getType() + "] parameter [" + currentHtmlParameter.getName() + "], with value [" + currentHtmlParameter.getValue() + "]"); // 4) Change the current parameter value (which we assume is the username parameter) // to an invalid username (randomly), and request the URL n times. Store the results // in B[]. // get a random user name the same length as the original! String invalidUsername = RandomStringUtils.random(currentHtmlParameter.getValue().length(), RANDOM_USERNAME_CHARS); if (this.debugEnabled) log.debug("The invalid username chosen was [" + invalidUsername + "]"); TreeSet<HtmlParameter> requestParams = null; if (currentHtmlParameter.getType().equals(HtmlParameter.Type.cookie)) { requestParams = msgModifiedParam.getRequestHeader().getCookieParams(); requestParams.remove(currentHtmlParameter); requestParams.add(new HtmlParameter(currentHtmlParameter.getType(), currentHtmlParameter.getName(), invalidUsername.toString())); // add in the invalid username msgModifiedParam.setCookieParams(requestParams); } else if (currentHtmlParameter.getType().equals(HtmlParameter.Type.url)) { requestParams = msgModifiedParam.getUrlParams(); requestParams.remove(currentHtmlParameter); requestParams.add(new HtmlParameter(currentHtmlParameter.getType(), currentHtmlParameter.getName(), invalidUsername.toString())); // add in the invalid username msgModifiedParam.setGetParams(requestParams); } else if (currentHtmlParameter.getType().equals(HtmlParameter.Type.form)) { requestParams = msgModifiedParam.getFormParams(); requestParams.remove(currentHtmlParameter); requestParams.add(new HtmlParameter(currentHtmlParameter.getType(), currentHtmlParameter.getName(), invalidUsername.toString())); // add in the invalid username msgModifiedParam.setFormParams(requestParams); } if (this.debugEnabled) log.debug("About to loop for " + numberOfRequests + " iterations with an incorrect user of the same length"); boolean continueForParameter = true; for (int i = 0; i < numberOfRequests && continueForParameter; i++) { // initialise the storage for this iteration responseB = new StringBuilder(250); HttpMessage msgCpy = msgModifiedParam; // use the message we already set up, with the // modified parameter value sendAndReceive(msgCpy, false, false); // request the URL, but do not automatically follow redirects. // get all cookies set in the response TreeSet<HtmlParameter> cookies = msgCpy.getResponseHeader().getCookieParams(); int redirectCount = 0; while (HttpStatusCode.isRedirection(msgCpy.getResponseHeader().getStatusCode())) { redirectCount++; if (this.debugEnabled) log.debug("Following redirect " + redirectCount + " for message " + i + " of " + numberOfRequests + " iterations of the modified query"); // append the response to the responses so far for this particular instance // this will give us a complete picture of the full set of actual traffic // associated with following redirects for the request responseB.append(msgCpy.getResponseHeader().getHeadersAsString()); responseB.append(msgCpy.getResponseBody().toString()); // and manually follow the redirect // create a new message from scratch HttpMessage msgRedirect = new HttpMessage(); // create a new URI from the absolute location returned, and interpret it as // escaped // note that the standard says that the Location returned should be // absolute, but it ain't always so... URI newLocation = new URI(msgCpy.getResponseHeader().getHeader(HttpHeader.LOCATION), true); try { msgRedirect.getRequestHeader().setURI(newLocation); } catch (Exception e) { // the Location field contents may not be standards compliant. Lets // generate a uri to use as a workaround where a relative path was // given instead of an absolute one URI newLocationWorkaround = new URI(msgCpy.getRequestHeader().getURI(), msgCpy.getResponseHeader().getHeader(HttpHeader.LOCATION), true); // try again, except this time, if it fails, don't try to handle it if (this.debugEnabled) log.debug("The Location [" + newLocation + "] specified in a redirect was not valid (not absolute?). Trying absolute workaround url [" + newLocationWorkaround + "]"); msgRedirect.getRequestHeader().setURI(newLocationWorkaround); } msgRedirect.getRequestHeader().setMethod(HttpRequestHeader.GET); // it's always a GET for a redirect msgRedirect.getRequestHeader().setContentLength(0); // since we send a GET, the body will be 0 long if (cookies.size() > 0) { // if a previous request sent back a cookie that has not since been // invalidated, we need to set that cookie when following redirects, as // a browser would msgRedirect.getRequestHeader().setCookieParams(cookies); } sendAndReceive(msgRedirect, false, false); // do NOT redirect.. handle it here // handle scenario where a cookie is unset in a subsequent iteration, or // where the same cookie name is later re-assigned a different value // ie, in these cases, do not simply (and dumbly) accumulate cookie // detritus. // first get all cookies set in the response TreeSet<HtmlParameter> cookiesTemp = msgRedirect.getResponseHeader().getCookieParams(); for (Iterator<HtmlParameter> redirectSetsCookieIterator = cookiesTemp .iterator(); redirectSetsCookieIterator.hasNext();) { HtmlParameter cookieJustSet = redirectSetsCookieIterator.next(); // loop through each of the cookies we know about in cookies, to see if // it matches by name. // if so, delete that cookie, and add the one that was just set to // cookies. // if not, add the one that was just set to cookies. for (Iterator<HtmlParameter> knownCookiesIterator = cookies .iterator(); knownCookiesIterator.hasNext();) { HtmlParameter knownCookie = knownCookiesIterator.next(); if (cookieJustSet.getName().equals(knownCookie.getName())) { knownCookiesIterator.remove(); break; // out of the loop for known cookies, back to the next // cookie set in the response } } // end of loop for cookies we already know about // we can now safely add the cookie that was just set into cookies, // knowing it does not clash with anything else in there. cookies.add(cookieJustSet); } // end of for loop for cookies just set in the redirect msgCpy = msgRedirect; // store the last redirect message into the MsgCpy, as // we will be using it's output in a moment.. } // end of loop to follow redirects // now that the redirections have all been handled.. was the request finally a // success or not? Successful or Failed Logins would normally both return an OK // HTTP status if (!HttpStatusCode.isSuccess(msgCpy.getResponseHeader().getStatusCode())) { log.warn("The modified URL [" + msgModifiedParam.getRequestHeader().getURI() + "] returned a non-OK HTTP status " + msgCpy.getResponseHeader().getStatusCode() + " (after " + i + 1 + " of " + numberOfRequests + " steps for [" + currentHtmlParameter.getType() + "] parameter " + currentHtmlParameter.getName() + "). Could be indicative of SQL Injection, or some other error. The URL is not stable enough to look at Username Enumeration"); continueForParameter = false; continue; // skip directly to the next parameter. Do not pass Go. Do not // collect $200. } if (this.debugEnabled) log.debug("Done following redirects!"); // append the response to the responses so far for this particular instance // this will give us a complete picture of the full set of actual traffic // associated with following redirects for the request responseB.append(msgCpy.getResponseHeader().getHeadersAsString()); responseB.append(msgCpy.getResponseBody().toString()); // 5) Compute the longest common subsequence (LCS) of B[] into LCS_B // Note: in the Freiling and Schinzel method, this is calculated recursively. We // calculate it iteratively, but using an equivalent method // first time in, the LCS is simple: it's the first HTML result.. no diffing // required if (i == 0) longestCommonSubstringB = responseB.toString(); // else get the LCS of the existing string, and the current result else longestCommonSubstringB = this.longestCommonSubsequence(longestCommonSubstringB, responseB.toString()); // optimisation step: if the LCS of B is 0 characters long already, then the URL // output is not stable, and we can abort now, and save some time if (longestCommonSubstringB.length() == 0) { // this might occur if the output returned for the URL changed mid-way. // Perhaps a CAPTCHA has fired, or a WAF has kicked in. Let's abort now so. log.warn("The modified URL [" + msgModifiedParam.getRequestHeader().getURI() + "] (for [" + currentHtmlParameter.getType() + "] parameter " + currentHtmlParameter.getName() + ") does not produce stable output (after " + i + 1 + " of " + numberOfRequests + " steps). There is no static element in the output that can be used as a basis of comparison with the static output of the original query. Perhaps a CAPTCHA or WAF has kicked in!!"); continueForParameter = false; continue; // skip directly to the next parameter. Do not pass Go. Do not // collect $200. // Note: if a CAPTCHA or WAF really has fired, the results of subsequent // iterations will likely not be accurate.. } } // if we didn't hit something with one of the iterations for the parameter (ie, if // the output when changing the parm is stable), // check if the parameter might be vulnerable by comparins its LCS with the original // LCS for a valid login if (continueForParameter == true) { // get rid of any remnants of cookie setting and Date headers in the responses, // as these cause false positives, and can be safely ignored // replace the content length with a non-variable placeholder // replace url parameters with a non-variable placeholder to eliminate tokens in // URLs in the output longestCommonSubstringB = longestCommonSubstringB .replaceAll("Set-Cookie:[^\\r\\n]+[\\r\\n]{1,2}", ""); longestCommonSubstringB = longestCommonSubstringB.replaceAll("Date:[^\\r\\n]+[\\r\\n]{1,2}", ""); longestCommonSubstringB = longestCommonSubstringB .replaceAll("Content-Length:[^\\r\\n]+[\\r\\n]{1,2}", "Content-Length: XXXX\n"); longestCommonSubstringB = longestCommonSubstringB .replaceAll("(?<=(&|\\?)[^\\?\"=&;]+=)[^\\?\"=&;]+(?=(&|\"))", "YYYY"); if (this.debugEnabled) log.debug("The LCS of B is [" + longestCommonSubstringB + "]"); // 6) If LCS_A <> LCS_B, then there is a Username Enumeration issue on the // current parameter if (!longestCommonSubstringA.equals(longestCommonSubstringB)) { // calculate line level diffs of the 2 Longest Common Substrings to aid the // user in deciding if the match is a false positive // get the diff as a series of patches Patch diffpatch = DiffUtils.diff( new LinkedList<String>(Arrays.asList(longestCommonSubstringA.split("\\n"))), new LinkedList<String>(Arrays.asList(longestCommonSubstringB.split("\\n")))); int numberofDifferences = diffpatch.getDeltas().size(); // and convert the list of patches to a String, joining using a newline // String diffAB = StringUtils.join(diffpatch.getDeltas(), "\n"); StringBuilder tempDiff = new StringBuilder(250); for (Delta delta : diffpatch.getDeltas()) { String changeType = null; if (delta.getType() == Delta.TYPE.CHANGE) changeType = "Changed Text"; else if (delta.getType() == Delta.TYPE.DELETE) changeType = "Deleted Text"; else if (delta.getType() == Delta.TYPE.INSERT) changeType = "Inserted text"; else changeType = "Unknown change type [" + delta.getType() + "]"; tempDiff.append("\n(" + changeType + ")\n"); // blank line before tempDiff.append("Output for Valid Username : " + delta.getOriginal() + "\n"); // no blank lines tempDiff.append("\nOutput for Invalid Username: " + delta.getRevised() + "\n"); // blank line before } String diffAB = tempDiff.toString(); String extraInfo = Constant.messages.getString( "ascanbeta.usernameenumeration.alert.extrainfo", currentHtmlParameter.getType(), currentHtmlParameter.getName(), currentHtmlParameter.getValue(), // original value invalidUsername.toString(), // new value diffAB, // the differences between the two sets of output numberofDifferences); // the number of differences String attack = Constant.messages.getString("ascanbeta.usernameenumeration.alert.attack", currentHtmlParameter.getType(), currentHtmlParameter.getName()); String vulnname = Constant.messages.getString("ascanbeta.usernameenumeration.name"); String vulndesc = Constant.messages.getString("ascanbeta.usernameenumeration.desc"); String vulnsoln = Constant.messages.getString("ascanbeta.usernameenumeration.soln"); // call bingo with some extra info, indicating that the alert is bingo(Alert.RISK_INFO, Alert.CONFIDENCE_LOW, vulnname, vulndesc, getBaseMsg().getRequestHeader().getURI().getURI(), currentHtmlParameter.getName(), attack, extraInfo, vulnsoln, getBaseMsg()); } else { if (this.debugEnabled) log.debug("[" + currentHtmlParameter.getType() + "] parameter [" + currentHtmlParameter.getName() + "] looks ok (Invalid Usernames cannot be distinguished from Valid usernames)"); } } } // end of the for loop around the parameter list } catch (Exception e) { // Do not try to internationalise this.. we need an error message in any event.. // if it's in English, it's still better than not having it at all. log.error("An error occurred checking a url for Username Enumeration issues", e); } }
From source file:org.hyperic.hq.autoinventory.agent.server.AICommandsService.java
private ServerSignature[] getAutoScanners(String type) { ArrayList sigs = new ArrayList(); Map plugins = _pluginManager.getPlatformPlugins(type); //XXX hack. we want the jboss plugin to run before tomcat //so jboss can drop a hint about the embedded tomcat. TreeSet detectors = new TreeSet(new Comparator() { public int compare(Object o1, Object o2) { String name1 = ((GenericPlugin) o1).getName(); String name2 = ((GenericPlugin) o2).getName(); return name1.compareTo(name2); }/* ww w . j a v a2 s .c om*/ }); for (Iterator i = plugins.entrySet().iterator(); i.hasNext();) { Map.Entry entry = (Map.Entry) i.next(); ServerDetector detector; if (!(entry.getValue() instanceof ServerDetector)) { continue; } detector = (ServerDetector) entry.getValue(); TypeInfo info = ((GenericPlugin) detector).getTypeInfo(); if (info.getType() != TypeInfo.TYPE_SERVER) { continue; } if (!(detector instanceof AutoServerDetector)) { continue; } detectors.add(detector); } for (Iterator i = detectors.iterator(); i.hasNext();) { ServerDetector detector = (ServerDetector) i.next(); sigs.add(detector.getServerSignature()); } return (ServerSignature[]) sigs.toArray(new ServerSignature[0]); }
From source file:com.autentia.intra.jsf.schedule.renderer.BitacoreScheduleDetailedDayRenderer.java
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer) throws IOException { final String clientId = schedule.getClientId(context); FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context); String formId = parentFormInfo == null ? null : parentFormInfo.getFormName(); TreeSet entrySet = new TreeSet(); for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) { entrySet.add(new EntryWrapper((ScheduleEntry) entryIterator.next(), day)); }// ww w . j a v a2 s . c o m EntryWrapper[] entries = (EntryWrapper[]) entrySet.toArray(new EntryWrapper[entrySet.size()]); //determine overlaps scanEntries(entries, 0); //determine the number of columns within this day int maxColumn = 0; for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); maxColumn = Math.max(wrapper.column, maxColumn); } int numberOfColumns = maxColumn + 1; //make sure the entries take up all available space horizontally maximizeEntries(entries, numberOfColumns); //now determine the width in percent of 1 column float columnWidth = 100 / numberOfColumns; //and now draw the entries in the columns for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); boolean selected = isSelected(schedule, wrapper); //compose the CSS style for the entry box StringBuffer entryStyle = new StringBuffer(); entryStyle.append(wrapper.getBounds(schedule, columnWidth)); String entryBorderColor = getEntryRenderer(schedule).getColor(context, schedule, wrapper.entry, selected); if (entryBorderColor != null) { entryStyle.append(" border-color: "); entryStyle.append(entryBorderColor); entryStyle.append(";"); } if (selected) { writer.startElement(HTML.DIV_ELEM, schedule); writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry-selected"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(HTML.DIV_ELEM); } else { //if the schedule is read-only, the entries should not be //hyperlinks writer.startElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM, schedule); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } if (!schedule.isReadonly()) { writer.writeAttribute("href", "#", null); writer.writeAttribute(HTML.ONMOUSEUP_ATTR, "fireEntrySelected('" + formId + "', '" + clientId + "', '" + wrapper.entry.getId() + "');", null); } writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(schedule.isReadonly() ? HTML.DIV_ELEM : "a"); } } }
From source file:com.autentia.tnt.jsf.schedule.renderer.BitacoreScheduleDetailedDayRenderer.java
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer) throws IOException { final String clientId = schedule.getClientId(context); FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context); String formId = parentFormInfo == null ? null : parentFormInfo.getFormName(); TreeSet entrySet = new TreeSet(); for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) { entrySet.add(new EntryWrapper((ScheduleEntry) entryIterator.next(), day)); }/*from www. j ava 2s . c o m*/ EntryWrapper[] entries = (EntryWrapper[]) entrySet.toArray(new EntryWrapper[entrySet.size()]); //determine overlaps scanEntries(entries, 0); //determine the number of columns within this day int maxColumn = 0; for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); maxColumn = Math.max(wrapper.column, maxColumn); } int numberOfColumns = maxColumn + 1; //make sure the entries take up all available space horizontally maximizeEntries(entries, numberOfColumns); //now determine the width in percent of 1 column float columnWidth = (float) 100 / numberOfColumns; //and now draw the entries in the columns for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); boolean selected = isSelected(schedule, wrapper); //compose the CSS style for the entry box StringBuffer entryStyle = new StringBuffer(); entryStyle.append(wrapper.getBounds(schedule, columnWidth)); String entryBorderColor = getEntryRenderer(schedule).getColor(context, schedule, wrapper.entry, selected); if (entryBorderColor != null) { entryStyle.append(" border-color: "); entryStyle.append(entryBorderColor); entryStyle.append(";"); } if (selected) { writer.startElement(HTML.DIV_ELEM, schedule); writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry-selected"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(HTML.DIV_ELEM); } else { //if the schedule is read-only, the entries should not be //hyperlinks writer.startElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM, schedule); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } if (!schedule.isReadonly()) { writer.writeAttribute("href", "#", null); writer.writeAttribute(HTML.ONMOUSEUP_ATTR, "fireEntrySelected('" + formId + "', '" + clientId + "', '" + wrapper.entry.getId() + "');", null); } writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry"), null); writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(schedule.isReadonly() ? HTML.DIV_ELEM : "a"); } } }
From source file:edu.ucla.stat.SOCR.analyses.gui.AnovaOneWay.java
protected void doGraph() { // graph Component is available here // data: variables double xData, yData, residuals, predicted are available here after doAnalysis() is run. ////System.out.println("\nAnovaOneWay doGraph call removeAll"); graphPanel.removeAll();/* ww w. j av a 2 s .c om*/ JPanel innerPanel = new JPanel(); JScrollPane graphPane = new JScrollPane(innerPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); graphPanel.add(graphPane); innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.Y_AXIS)); graphPanel.setLayout(new BoxLayout(graphPanel, BoxLayout.Y_AXIS)); // 1. Box plot of data: yData vs. xData (where xData is categorical) //int seriesCount = 3; // seriesCount //int categoryCount= 1; //double[][][] yValue = new double[seriesCount][categoryCount][]; //String[] seriesName = {"1", "2", "3"}; /* String[][] xNameData = new String[seriesCount][categoryCount]; // xNameData: category names. xNameData[0] = new String[] {""}; xNameData[1] = xNameData[0]; xNameData[2] = xNameData[0]; */ // data is for testing only. // the data below gives hallow triagle and circles. // static test data only /* yValue[0][0] = new double[] {14.67,13.72,13.84,13.90,14.56,13.88,14.30,14.11,13.84,13.90,14.56,13.88, 15, 16, 17}; yValue[1][0] = new double[] {13.94,14.40,14.14,14.59,13.59,14.24,14.05,11,12,13, 15, 20, 8}; yValue[2][0] = new double[] {14.24,14.05,14.65,13,10,19,20,10,11,12,23, 20, 23, 24}; */ /* the parameters to be passed are: 1.boxPlotTitle, xAxisLabel, YAxisLabel. 2. serieCount, categoryCount 3. seriesname (e.g. sex, race, etc) 4. category's name (e.g. height, weight, etc)--xData 5. yValue(double), */ /* JFreeChart scatterChart = chartFactory.getQQChart("Scatter Plot of " + dependentHeader + " vs " + independentHeader, independentHeader, dependentHeader, dependentHeader + " Value " , xData, yData, "Regression Line", intercept, slope, ""); ChartPanel chartPanel = new ChartPanel(scatterChart, false); chartPanel.setPreferredSize(new Dimension(plotWidth,plotHeight)); innerPanel.add(chartPanel); */ double xDataDouble[] = new double[xData.length]; String groupLegend = ""; boolean useStringLegend = false; TreeSet<String> treeSet = new TreeSet<String>(); try { for (int i = 0; i < xData.length; i++) { xDataDouble[i] = (new Double(xData[i])).doubleValue(); } } catch (Exception e) { useStringLegend = true; for (int i = 0; i < xData.length; i++) { treeSet.add((String) xData[i]); } } int groupSize = treeSet.size(); ////System.out.println("TreeSet.size() = " + groupSize); Iterator<String> iterator = treeSet.iterator(); int groupIndex = 1; String groupName = null; while (iterator.hasNext()) { groupName = (String) iterator.next(); //xDataDouble[groupIndex-1] = groupIndex; groupLegend += ("\t" + groupName + "=" + groupIndex + " "); for (int i = 0; i < xData.length; i++) { if (xData[i].equalsIgnoreCase(groupName)) { // xData[i] is a String. xDataDouble[i] = (double) groupIndex; } } groupIndex++; } if (useStringLegend) { groupLegend = "Group Names: " + groupLegend; groupLegend = groupLegend.substring(0, groupLegend.length() - 2); //System.out.println("groupLegend = " + groupLegend); // 1. scatter plot of data: yData vs. xData } //JFreeChart scatterChart = chartFactory.getQQChart("Scatter Plot", independentHeader, "Residuals", "Residual Value", xData, residuals, "At Residual = 0", 0, 0, ""); JFreeChart scatterChart = chartFactory.getQQChart("Scatter Plot", independentHeader, "Residuals", "Residual Value", xDataDouble, residuals, " " + groupLegend, 0, 0, ""); //JFreeChart scatterChart = chartFactory.getLineChart("Scatter Plot", independentHeader, dependentHeader, xDataDouble, yData);//getChart(title, xlabel, ylabel, xdata,ydata) ChartPanel chartPanel = new ChartPanel(scatterChart, false); chartPanel.setPreferredSize(new Dimension(plotWidth, plotHeight)); innerPanel.add(chartPanel); /* if (useStringLegend) { JPanel labelPanel = new JPanel(); labelPanel.setBackground(Color.WHITE); JLabel legendLabel1 = new JLabel(groupLegend); legendLabel1.setBackground(Color.WHITE); labelPanel.add(legendLabel1, BorderLayout.NORTH); innerPanel.add(labelPanel); } */ // this is only a test for having more than one charts in a boxlayout // 1.5. box plot of data //mapToArray(boxPlotNameValueMap); /* JFreeChart boxChart = chartFactory.getBoxAndWhiskerChart(boxPlotTitle, xAxisLabel, yAxisLabel, seriesCount, categoryCount, seriesName, xNameData, yValue); chartPanel = new ChartPanel(boxChart, false); chartPanel.setPreferredSize(new Dimension(plotWidth,plotHeight)); graphPanel.add(chartPanel); */ // 2. residual on fit plot: residuals vs. xData //JFreeChart rxChart = chartFactory.getLineChart("Residual on Covariate Plot", independentHeader, "Residuals", xDataDouble, residuals); JFreeChart rxChart = chartFactory.getQQChart("Residual on Covariate Plot", independentHeader, "Residuals", "Residuals", xDataDouble, residuals, " " + groupLegend, 0, 0, ""); chartPanel = new ChartPanel(rxChart, false); chartPanel.setPreferredSize(new Dimension(plotWidth, plotHeight)); innerPanel.add(chartPanel); // 3. residual on fit plot: residuals vs. predicted //JFreeChart rfChart = chartFactory.getLineChart("Residual on Fit Plot", "Predicted", "Residuals", predicted, residuals); JFreeChart rfChart = chartFactory.getQQChart("Residual on Fit Plot", "Predicted " + dependentHeader, "Residuals", "Residuals", predicted, residuals, "At Residual = 0", 0, 0, ""); chartPanel = new ChartPanel(rfChart, false); chartPanel.setPreferredSize(new Dimension(plotWidth, plotHeight)); innerPanel.add(chartPanel); // 4. Normal QQ plot: need residuals and standardized normal scores //JFreeChart qqChart = chartFactory.getLineChart("Residual Normal QQ Plot", "Theoretical Quantiles", "Standardized Residuals", sortedStandardizedNormalQuantiles, sortedStandardizedResiduals); int len = sortedNormalQuantiles.length; double slope = (sortedStandardizedResiduals[len - 1] - sortedStandardizedResiduals[0]) / (sortedNormalQuantiles[len - 1] - sortedNormalQuantiles[0]); double y0 = sortedStandardizedResiduals[len - 1] - slope * sortedNormalQuantiles[len - 1]; // max_x = Math.max (normalQuantiles[row_count-1],stdResiduals[row_count-1]); JFreeChart qqChart = chartFactory.getQQChart("Residual Normal QQ Plot", "Theoretical Quantiles", "Standardized Residuals", "Standardized Residual Value ", sortedStandardizedNormalQuantiles, sortedStandardizedResiduals, "At Standardized Residual = 0", y0, slope, "noshape"); //JFreeChart qqChart = chartFactory.getLineChart("Residual Normal QQ Plot", "Theoretical Quantiles", "Standardized Residuals", sortedStandardizedNormalQuantiles, sortedStandardizedResiduals, "noline"); chartPanel = new ChartPanel(qqChart, false); chartPanel.setPreferredSize(new Dimension(plotWidth, plotHeight)); innerPanel.add(chartPanel); graphPanel.validate(); }
From source file:net.sourceforge.fenixedu.presentationTier.Action.administrativeOffice.scholarship.utl.report.StudentLine.java
public LocalDate getFirstEnrolmentOnCurrentExecutionYear() { if (getRegistration() == null) { return null; }/* www . ja v a 2s.c o m*/ if (getRegistration().isInMobilityState()) { return getForExecutionYear().getBeginDateYearMonthDay().toLocalDate(); } TreeSet<Enrolment> orderedEnrolmentSet = new TreeSet<Enrolment>( Collections.reverseOrder(CurriculumModule.COMPARATOR_BY_CREATION_DATE)); orderedEnrolmentSet.addAll(getStudentCurricularPlan().getEnrolmentsByExecutionYear(getForExecutionYear())); return orderedEnrolmentSet.isEmpty() ? null : orderedEnrolmentSet.iterator().next().getCreationDateDateTime().toLocalDate(); }
From source file:com.idega.block.cal.renderer.ScheduleDetailedDayRenderer.java
protected void writeEntries(FacesContext context, HtmlSchedule schedule, ScheduleDay day, ResponseWriter writer, int index) throws IOException { //final String clientId = schedule.getClientId(context); //FormInfo parentFormInfo = RendererUtils.findNestingForm(schedule, context); //String formId = parentFormInfo == null ? null : parentFormInfo.getFormName(); TreeSet entrySet = new TreeSet(); for (Iterator entryIterator = day.iterator(); entryIterator.hasNext();) { entrySet.add(new EntryWrapper((ScheduleEntry) entryIterator.next(), day)); }//from w w w . jav a2 s .c o m EntryWrapper[] entries = (EntryWrapper[]) entrySet.toArray(new EntryWrapper[entrySet.size()]); //determine overlaps scanEntries(entries, 0); //determine the number of columns within this day int maxColumn = 0; for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); maxColumn = Math.max(wrapper.column, maxColumn); } int numberOfColumns = maxColumn + 1; //make sure the entries take up all available space horizontally maximizeEntries(entries, numberOfColumns); //now determine the width in percent of 1 column float columnWidth = 100 / numberOfColumns; //and now draw the entries in the columns for (Iterator entryIterator = entrySet.iterator(); entryIterator.hasNext();) { EntryWrapper wrapper = (EntryWrapper) entryIterator.next(); boolean selected = isSelected(schedule, wrapper); //compose the CSS style for the entry box StringBuffer entryStyle = new StringBuffer(); entryStyle.append(wrapper.getBounds(schedule, columnWidth, index)); if (selected) { writer.startElement(HTML.DIV_ELEM, schedule); writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry-selected"), null); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(HTML.DIV_ELEM); } else { //if the schedule is read-only, the entries should not be //hyperlinks writer.startElement(schedule.isReadonly() ? HTML.DIV_ELEM : HTML.ANCHOR_ELEM, schedule); //draw the tooltip if (showTooltip(schedule)) { getEntryRenderer(schedule).renderToolTip(context, writer, schedule, wrapper.entry, selected); } if (!schedule.isReadonly()) { DateFormat format; String pattern = null; if ((pattern != null) && (pattern.length() > 0)) { format = new SimpleDateFormat(pattern); } else { if (context.getApplication().getDefaultLocale() != null) { format = DateFormat.getDateInstance(DateFormat.MEDIUM, context.getApplication().getDefaultLocale()); } else { format = DateFormat.getDateInstance(DateFormat.MEDIUM); } } String startTime = format.format(wrapper.entry.getStartTime()); startTime += " "; startTime += wrapper.entry.getStartTime().getHours(); startTime += ":"; if (wrapper.entry.getStartTime().getMinutes() < 10) { startTime += "0"; startTime += wrapper.entry.getStartTime().getMinutes(); } else { startTime += wrapper.entry.getStartTime().getMinutes(); } String endTime = ""; endTime += wrapper.entry.getEndTime().getHours(); endTime += ":"; if (wrapper.entry.getEndTime().getMinutes() < 10) { endTime += "0"; endTime += wrapper.entry.getEndTime().getMinutes(); } else { endTime += wrapper.entry.getEndTime().getMinutes(); } writer.writeAttribute(HTML.HREF_ATTR, "javascript:void(0)", null); writer.writeAttribute("entryid", wrapper.entry.getId(), null); } if (schedule.getModel().size() == 1) { writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "entry"), null); } else { writer.writeAttribute(HTML.CLASS_ATTR, getStyleClass(schedule, "workweekEntry"), null); } writer.writeAttribute(HTML.STYLE_ATTR, entryStyle.toString(), null); //draw the content getEntryRenderer(schedule).renderContent(context, writer, schedule, day, wrapper.entry, false, selected); writer.endElement(schedule.isReadonly() ? HTML.DIV_ELEM : "a"); } } }
From source file:org.apache.fop.complexscripts.fonts.GlyphTable.java
/** * Obtain ordered list of all lookup tables, where order is by lookup identifier, which * lexicographic ordering follows the lookup list order. * @return (possibly empty) ordered list of all lookup tables *//*w w w.j a v a 2 s. co m*/ public List/*<LookupTable>*/ getLookupTables() { TreeSet/*<String>*/ lids = new TreeSet/*<String>*/ (lookupTables.keySet()); List/*<LookupTable>*/ ltl = new ArrayList/*<LookupTable>*/ (lids.size()); for (Iterator it = lids.iterator(); it.hasNext();) { String lid = (String) it.next(); ltl.add(lookupTables.get(lid)); } return ltl; }