def on_downloadBoundariesBtn_clicked(self, e): """Download puter ways of administrative boundaries from Overpass API """ adminLevel = self.adminLevelTagTextField.getText() name = self.nameTagTextField.getText() optional = self.optionalTagTextField.getText() if (adminLevel, name, optional) == ("", "", ""): JOptionPane.showMessageDialog(self, self.app.strings.getString("enter_a_tag_msg"), self.app.strings.getString("Warning"), JOptionPane.WARNING_MESSAGE) return optTag = "" if optional.find("=") != -1: if len(optional.split("=")) == 2: key, value = optional.split("=") optTag = '["%s"="%s"]' % (URLEncoder.encode(key, "UTF-8"), URLEncoder.encode(value.replace(" ", "%20"), "UTF-8")) self.create_new_zone_editing_layer() overpassurl = 'http://127.0.0.1:8111/import?url=' overpassurl += 'http://overpass-api.de/api/interpreter?data=' overpassquery = 'relation["admin_level"="%s"]' % adminLevel overpassquery += '["name"="%s"]' % URLEncoder.encode(name, "UTF-8") overpassquery += '%s;(way(r:"outer");node(w););out meta;' % optTag overpassurl += overpassquery.replace(" ", "%20") print overpassurl self.app.send_to_josm(overpassurl)
def onAdvEvent(self, event, npc, player): if event == 'ad': try: c = URL('http://duck5duck.mooo.com/l2jtw_ad/l2jtw_ad.php' ).openConnection() if c: c.setDoOutput(True) o = DataOutputStream(c.getOutputStream()) s = self.param % ( C.RATE_XP, C.RATE_SP, C.RATE_PARTY_XP, C.RATE_PARTY_SP, C.PARTY_XP_CUTOFF_LEVEL, C.PET_XP_RATE, C.RATE_DROP_ITEMS, C.RATE_DROP_ITEMS_BY_RAID, C.RATE_DROP_MANOR, C.RATE_QUEST_DROP, C.RATE_DROP_ITEMS_ID.get(57) or 1.0, C.BUFFS_MAX_AMOUNT, C.TRIGGERED_BUFFS_MAX_AMOUNT, C.DANCES_MAX_AMOUNT, C.RUN_SPD_BOOST, C.MAX_RUN_SPEED, C.MAX_PCRIT_RATE, C.MAX_MCRIT_RATE, C.MAX_PATK_SPEED, C.MAX_MATK_SPEED, C.MAX_EVASION, C.MAX_SUBCLASS, C.BASE_SUBCLASS_LEVEL, C.MAX_SUBCLASS_LEVEL, C.INVENTORY_MAXIMUM_NO_DWARF, C.INVENTORY_MAXIMUM_DWARF, C.INVENTORY_MAXIMUM_QUEST_ITEMS, C.WAREHOUSE_SLOTS_NO_DWARF, C.WAREHOUSE_SLOTS_DWARF, C.WAREHOUSE_SLOTS_CLAN, C.MAX_ADENA / 100000000, C.MAXIMUM_ONLINE_USERS, C.ENCHANT_CHANCE_ELEMENT_STONE, C.ENCHANT_CHANCE_ELEMENT_CRYSTAL, C.ENCHANT_CHANCE_ELEMENT_JEWEL, C.ENCHANT_CHANCE_ELEMENT_ENERGY, C.ENCHANT_SAFE_MAX, C.ENCHANT_SAFE_MAX_FULL, C.CLAN_LEVEL_6_COST, C.CLAN_LEVEL_7_COST, C.CLAN_LEVEL_8_COST, C.CLAN_LEVEL_9_COST, C.CLAN_LEVEL_10_COST, C.CLAN_LEVEL_11_COST, C.CLAN_LEVEL_6_REQUIREMENT, C.CLAN_LEVEL_7_REQUIREMENT, C.CLAN_LEVEL_8_REQUIREMENT, C.CLAN_LEVEL_9_REQUIREMENT, C. CLAN_LEVEL_10_REQUIREMENT, C.CLAN_LEVEL_11_REQUIREMENT, L2World.getInstance().getAllPlayersCount(), self.getRealOnline(), URLEncoder.encode(self.link, 'utf-8'), URLEncoder.encode(self.intro, 'utf-8')) o.write(s) o.flush() o.close() i = c.getInputStream() r = "" while True: ch = i.read() if ch == -1: break r += chr(ch) if len(r): print r i.close() c.disconnect() except: return
def __init__(self, key, value, count): self.__name = value[value.rfind("/") + 1:] fq = '%s:"%s"' % (key, value) self.__facetQuery = URLEncoder.encode(fq, "UTF-8") self.__id = md5.new(fq).hexdigest() self.__count = count self.__subFacets = ArrayList()
def post(targetURL, params, contentType="text/xml", username=None): if(type(params) is dict): paramStr = "" for aKey in params.keys(): paramStr+=aKey+"="+URLEncoder.encode(params[aKey], "UTF-8")+"&" paramStr=paramStr[:-1] else: paramStr = params url = URL(targetURL) print targetURL print paramStr print contentType connection = url.openConnection() if username!=None: userpass = username basicAuth = "Basic " + base64.b64encode(userpass); connection.setRequestProperty ("Authorization", basicAuth); connection.setRequestMethod("POST") if contentType != None: connection.setRequestProperty("Content-Type", contentType) connection.setRequestProperty("Content-Length", str(len(paramStr))) connection.setRequestProperty("Content-Language", "en-GB") connection.setUseCaches(0) connection.setDoInput(1) connection.setDoOutput(2) wr= DataOutputStream(connection.getOutputStream()) wr.writeBytes(paramStr) wr.flush() wr.close() return getResponse(connection);
def processTestcases(self, patt, messageInfo, payload): irequest = self._helpers.analyzeRequest(messageInfo) url = irequest.getUrl() response = messageInfo.getResponse() httpservice = messageInfo.getHttpService() inject = URLEncoder.encode(payload, "UTF-8") if self._callbacks.isInScope(url): #patt = "var (\w+).*=.*('|\")(.*)('|\")" words = [] x = re.findall(patt, self._helpers.bytesToString(response)) for y in x: words.append(y[0]) sortedwords = list(set(words)) if len(sortedwords) > 0: for word in sortedwords: param = self._helpers.buildParameter( word, inject, IParameter.PARAM_URL) newrequest = self._helpers.addParameter( messageInfo.getRequest(), param) t = threading.Thread(target=self.makeRequest, args=[ messageInfo.getHttpService(), newrequest, word, payload ]) t.daemon = True t.start()
def dataexport(self): guid = self.params.safeGetStringParam("guid") beginDate = self.params.safeGetStringParam("beginDate") endDate = self.params.safeGetStringParam("endDate") if guid == "": self.addActionError(u"没有查询的标识,请重新查询。") return self.ERROR qry = GroupDataQueryList(""" gdq.loginName, gdq.trueName, gdq.unitName, gdq.unitTitle, gdq.metaSubjectId, gdq.metaSubjectTitle, gdq.gradeId, gdq.gradeTitle, gdq.articleCount, gdq.bestArticleCount, gdq.resourceCount, gdq.bestResourceCount, gdq.topicCount, gdq.replyCount """) qry.objectGuid = guid data_list = qry.query_map(qry.count()) request.setAttribute("group", self.group) request.setAttribute("beginDate", beginDate) request.setAttribute("endDate", endDate) request.setAttribute("data_list", data_list) response.reset() request.setCharacterEncoding("utf-8") response.setContentType("application/vnd.ms-excel") response.setHeader("Content-Type", "application/vnd.ms-excel; charset=GB2312") #response.setCharacterEncoding("GB2312") #response.setLocale(Locale.SIMPLIFIED_CHINESE) codedfilename = URLEncoder.encode(self.group.groupTitle, "UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + codedfilename + ".xls") return "/WEB-INF/ftl/group/group_data_query_export.ftl"
def getAuthzRequestUrl(self, providerName): url = None if providerName in self.registeredProviders: print "Casa. getAuthzRequestUrl. Building an authz request URL for passport" isSaml = self.registeredProviders[providerName]["saml"] params = ["response_type", "client_id", "scope", "redirect_uri", "state", "nonce"] attrs = CdiUtil.bean(Identity).getSessionId().getSessionAttributes() authzParams = {} # use passport-* instead of casa authzParams["acr_values"] = self.getAcrFor(isSaml) # set the provider to use authzParams[self.preSelParams["saml" if isSaml else "social"]] = self.encodeProvider(providerName) # avoids passport flow updating the profile of user if he has been provisioned previously authzParams["skipPassportProfileUpdate"] = "true" # copy the params in the current casa request for param in params: authzParams[param] = URLEncoder.encode(attrs.get(param), "UTF-8") url = "/oxauth/restv1/authorize?" for param in authzParams: url += "&" + param + "=" + authzParams[param] else: print "Casa. getAuthzRequestUrl. Provider %s not recognized" % providerName return url
def post(targetURL, params, contentType="text/xml", username=None): if (type(params) is dict): paramStr = "" for aKey in params.keys(): paramStr += aKey + "=" + URLEncoder.encode(params[aKey], "UTF-8") + "&" paramStr = paramStr[:-1] else: paramStr = params url = URL(targetURL) print targetURL print paramStr print contentType connection = url.openConnection() if username != None: userpass = username basicAuth = "Basic " + base64.b64encode(userpass) connection.setRequestProperty("Authorization", basicAuth) connection.setRequestMethod("POST") if contentType != None: connection.setRequestProperty("Content-Type", contentType) connection.setRequestProperty("Content-Length", str(len(paramStr))) connection.setRequestProperty("Content-Language", "en-GB") connection.setUseCaches(0) connection.setDoInput(1) connection.setDoOutput(2) wr = DataOutputStream(connection.getOutputStream()) wr.writeBytes(paramStr) wr.flush() wr.close() return getResponse(connection)
def get(targetURL, params, username=None): paramStr = "" for aKey in params.keys(): paramStr+=aKey+"="+URLEncoder.encode(params[aKey], "UTF-8")+"&" paramStr=paramStr[:-1] url = URL(targetURL+"?"+paramStr) print url connection = url.openConnection() if username!=None: userpass = username basicAuth = "Basic " + base64.b64encode(userpass); #print basicAuth connection.setRequestProperty ("Authorization", basicAuth); connection.setRequestMethod("GET") connection.setRequestProperty("Content-Language", "en-GB") connection.setUseCaches(0) connection.setDoOutput(2) inStream= connection.getInputStream() rd= BufferedReader(InputStreamReader(inStream)) response = "" line = rd.readLine() while line != None: response +=line+"\r" line = rd.readLine() rd.close() return response
def update(self): """Update information shown by the dialog with those of currently selected error """ error = self.app.selectedError check = error.check view = check.view tool = view.tool text = "<html>" #user if error.user is not None: errorUserName = error.user.getName() text += "%s:" % self.app.strings.getString("Last_user") userUrl = "http://www.openstreetmap.org/user/%s/" % URLEncoder.encode(errorUserName, "UTF-8") userLink = "<a href='%s'>%s</a>" % (userUrl, errorUserName) msgUrl = "http://www.openstreetmap.org/message/new/%s" % URLEncoder.encode(errorUserName, "UTF-8") messageLink = "<a href='%s'>%s</a>" % (msgUrl, self.app.strings.getString("Send_a_message")) text += "<br>%s (%s)<br><br>" % (userLink, messageLink) #tool text += "%s:<br>%s" % (self.app.strings.getString("Error_reported_by_the_tool"), tool.title) if tool.uri != "": text += "<br>%s" % self.link(tool.uri) #error type if not tool.isLocal: text += "<br><br>%s:" % self.app.strings.getString("Type_of_error") text += "<br>%s --> %s" % (view.title, check.title) #error help, usually a link to a Wiki page describing this errror type #error link, e.g. a link to the error on the tool web page for propName, prop in ((self.app.strings.getString("Error_help"), check.helpUrl), (self.app.strings.getString("Error_link"), tool.error_url(error))): if prop != "": text += "<br><br>%s:" % propName text += "<br>%s" % self.link(prop) #error description, usually some info contained in the error file if error.desc != "": text += "<br><br>%s:" % self.app.strings.getString("Description") text += "<br>%s" % error.desc text += "</html>" self.infoPanel.setText(text) self.show()
def buildPostDataFortoken(self, encodedJWT, softwareStatementId) : postParameters = LinkedHashMap() postParameters.put("scope", self.clientScopes) postParameters.put("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") postParameters.put("grant_type", "client_credentials") postParameters.put("client_id", softwareStatementId) postParameters.put("client_assertion", encodedJWT) postData = StringBuilder() for param in postParameters.entrySet(): if postData.length() != 0: postData.append('&') postData.append(URLEncoder.encode(param.getKey(), "UTF-8")) postData.append('=') postData.append(URLEncoder.encode(String(param.getValue()), "UTF-8").replace("+", "%20")) print "Post data: "+postData.toString() return postData.toString()
def createRequest(self, providerId, params): """Create a redirect URL to send an authentication request to passport.""" url = None try: providerConfig = self.registeredProviders.get(providerId) if providerConfig is None: print("Passport. createRequest. Provider %s does not exist" % providerId) raise PassportError() facesContext = CdiUtil.bean(FacesContext) serverName = facesContext.getExternalContext().getRequest( ).getServerName() tokenEndpoint = "https://%s/passport/token" % serverName httpService = CdiUtil.bean(HttpService) httpclient = httpService.getHttpsClient() resultResponse = httpService.executeGet( httpclient, tokenEndpoint, Collections.singletonMap("Accept", "text/json")) httpResponse = resultResponse.getHttpResponse() bytes = httpService.getResponseContent(httpResponse) response = httpService.convertEntityToString(bytes) if response is not None: token = json.loads(response)["token_"] else: raise PassportError("Failed to obtain token from Passport") if params is not None: jsonParams = json.dumps(params) encryptedParams = CdiUtil.bean(EncryptionService).encrypt( jsonParams) # Need to translate from base64 to base64url to make it URL-friendly for passport # See RFC4648 section 5 encodedParams = StringUtils.replaceChars( encryptedParams, "/+", "_-") url = "/passport/auth/%s/%s/%s" % (providerId, token, encodedParams) if providerConfig["GCCF"]: # Need to set the language cookie langCode = { "en": "eng", "fr": "fra" }[params["ui_locales"][:2].lower()] url = "%s?lang=%s&return=%s" % ( self.passportConfig["languageCookieService"], langCode, URLEncoder.encode("https://" + serverName + url, "UTF8")) else: url = "/passport/auth/%s/%s" % (providerId, token) except: print("Passport. createRequest. Error building redirect URL: ", sys.exc_info()[1]) return url
def writeClientGetHTTP(self, writeOutTo, headers, data): """ generated source for method writeClientGetHTTP """ bw = BufferedWriter(OutputStreamWriter(writeOutTo.getOutputStream())) pw = PrintWriter(bw) pw.println("GET /" + URLEncoder.encode(data, "UTF-8") + " HTTP/1.0") if 0 > len(headers): pw.println(headers) pw.println("Content-length: 0") pw.println() pw.println() pw.flush()
def writeAsClientGET(cls, socket, hostField, data, playerName): """ generated source for method writeAsClientGET """ pw = PrintWriter(socket.getOutputStream()) pw.print_("GET /" + URLEncoder.encode(data, "UTF-8") + " HTTP/1.0\r\n") pw.print_("Accept: text/delim\r\n") pw.print_("Host: " + hostField + "\r\n") pw.print_("Sender: GAMESERVER\r\n") pw.print_("Receiver: " + playerName + "\r\n") pw.print_("\r\n") pw.print_("\r\n") pw.flush()
def __escapeQuery(self, q): eq = q # escape all solr/lucene special chars # from http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Escaping%20Special%20Characters for c in "+-&|!(){}[]^\"~*?:\\": eq = eq.replace(c, "\\%s" % c) ## Escape UTF8 try: return URLEncoder.encode(eq, "UTF-8") except UnsupportedEncodingException, e: print "Error during UTF8 escape! ", repr(eq) return eq
def __escapeQuery(self, q): eq = q # escape all solr/lucene special chars # from http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Escaping%20Special%20Characters for c in "+-&|!(){}[]^\"~*?:\\": eq = eq.replace(c, "\\%s" % c) ## Escape UTF8 try: return URLEncoder.encode(eq, "UTF-8") except UnsupportedEncodingException, e: self.log.error("Error during UTF8 escape! '{}'", repr(eq), e) return eq
def sayBugFixed(self, error, check): """Tell tool server that the current error is fixed """ url = "http://keepright.ipax.at/comment.php?" url += "st=ignore_t&" if len(error.other) != 0: #There is a comment on the error, copy it url += "co=%s&" % URLEncoder.encode(error.other[0], "UTF-8") url += "schema=%s&" % error.errorId.split(" ")[0] url += "id=%s" % error.errorId.split(" ")[1] self.reportToToolServer(url)
def setParams(self, format='json', action='', lgname='', lgpassword='', lgtoken='', language='', search='', id='', entity='', property='', new='', data='', meta='', type='', token='', summary=''): self.params='' if format: self.params+='&format=' + format if action: self.params+='&action=' + action if language: self.params+='&language=' + language if lgname: self.params+='&lgname=' + URLEncoder.encode(lgname, "UTF-8") if lgpassword: self.params+='&lgpassword='******'&lgtoken=' + URLEncoder.encode(lgtoken, "UTF-8") if search: self.params+='&search=' + URLEncoder.encode(search, "UTF-8") if id: self.params+='&id=' + URLEncoder.encode(id, "UTF-8") if entity: self.params+='&entity=' + URLEncoder.encode(entity, "UTF-8") if property: self.params+='&property=' + property if meta: self.params+='&meta=' + meta if type: self.params+='&type=' + type if new: self.params+='&new=' + new if data: self.params+='&data=' + URLEncoder.encode(data, "UTF-8") if summary: self.params+='&summary=' + URLEncoder.encode(summary, "UTF-8") if token: self.params+='&token=' + URLEncoder.encode(token, "UTF-8")
def __activate__(self, context): self.velocityContext = context self.services = context["Services"] self.request = context["request"] self.response = context["response"] self.contextPath = context["contextPath"] self.formData = context["formData"] self.page = context["page"] self.uaActivated = False useDownload = Boolean.parseBoolean(self.formData.get("download", "true")) self.__isPreview = Boolean.parseBoolean(self.formData.get("preview", "false")) self.__previewPid = None self.__hasPid = False uri = URLDecoder.decode(self.request.getAttribute("RequestURI")) matches = re.match("^(.*?)/(.*?)/(?:(.*?)/)?(.*)$", uri) if matches and matches.group(3): oid = matches.group(3) pid = matches.group(4) self.__metadata = JsonConfigHelper() self.__object = self.__getObject(oid) self.__oid = oid # If we have a PID if pid: self.__hasPid = True if useDownload: # Download the payload to support relative links download = DownloadData() download.__activate__(context) else: # Render the detail screen with the alternative preview self.__readMetadata(oid) self.__previewPid = pid # Otherwise, render the detail screen else: self.__readMetadata(oid) self.__previewPid = self.getPreview() if self.__previewPid: self.__previewPid = URLEncoder.encode(self.__previewPid, "UTF-8") else: # require trailing slash for relative paths q = "" if self.__isPreview: q = "?preview=true" self.response.sendRedirect("%s/%s/%s" % (self.contextPath, uri, q))
def setParams(self, format='json', action='', lgname='', lgpassword='', lgtoken='', language='', search='', id='', entity='', property='', new='', data='', meta='', type='', token='', summary=''): self.params = '' if format: self.params += '&format=' + format if action: self.params += '&action=' + action if language: self.params += '&language=' + language if lgname: self.params += '&lgname=' + URLEncoder.encode(lgname, "UTF-8") if lgpassword: self.params += '&lgpassword='******'&lgtoken=' + URLEncoder.encode(lgtoken, "UTF-8") if search: self.params += '&search=' + URLEncoder.encode(search, "UTF-8") if id: self.params += '&id=' + URLEncoder.encode(id, "UTF-8") if entity: self.params += '&entity=' + URLEncoder.encode(entity, "UTF-8") if property: self.params += '&property=' + property if meta: self.params += '&meta=' + meta if type: self.params += '&type=' + type if new: self.params += '&new=' + new if data: self.params += '&data=' + URLEncoder.encode(data, "UTF-8") if summary: self.params += '&summary=' + URLEncoder.encode(summary, "UTF-8") if token: self.params += '&token=' + URLEncoder.encode(token, "UTF-8")
def error_url(self, error): """Create a url to view an error in the web browser. """ from java.net import URL, URLEncoder # Custom variables: # https://github.com/ypid/opening_hours.js#library-api if error.check.url in ("opening_hours", "lit", "smoking_hours"): oh_mode = 0 elif error.check.url in ("collection_times", "service_times"): oh_mode = 2 return '%s?EXP=%s&lat=%f&lon=%f&mode=%d' % ( self.uri, URLEncoder.encode(error.other['oh_value'], "UTF-8").replace("+", "%20"), error.coords[0], error.coords[1], oh_mode )
def processTestcases(self, patt, messageInfo, payload): irequest = self._helpers.analyzeRequest(messageInfo) url = irequest.getUrl() response = messageInfo.getResponse() httpservice = messageInfo.getHttpService() inject = URLEncoder.encode(payload, "UTF-8") inScopeOnly = self.chxbox.isSelected() if inScopeOnly and not self._callbacks.isInScope(url): return if True: #patt = "var (\w+).*=.*('|\")(.*)('|\")" words = [] x = re.findall(patt, self._helpers.bytesToString(response)) for y in x: words.append(y[0]) sortedwords = list(set(words)) requestString = self._helpers.bytesToString( messageInfo.getRequest()) if 'GET /' in requestString: mthd = 'GET' elif 'POST /' in requestString: mthd = 'POST' else: mthd = 'GET' if len(sortedwords) > 0: for word in sortedwords: if mthd == 'GET': param = self._helpers.buildParameter( word, inject, IParameter.PARAM_URL) elif mthd == 'POST': param = self._helpers.buildParameter( word, inject, IParameter.PARAM_BODY) else: param = self._helpers.buildParameter( word, inject, IParameter.PARAM_URL) newrequest = self._helpers.addParameter( messageInfo.getRequest(), param) t = threading.Thread(target=self.makeRequest, args=[ messageInfo.getHttpService(), newrequest, word, payload ]) t.daemon = True t.start()
def post(targetURL, params, contentType="text/xml", username=None): #paramStr = params["data"] paramStr = "" for aKey in params.keys(): paramStr+=aKey+"="+URLEncoder.encode(params[aKey], "UTF-8")+"&" paramStr=paramStr[:-1] url = URL(targetURL) print targetURL print paramStr print contentType url = URL(targetURL+"?"+paramStr) print url connection = url.openConnection() if username!=None: userpass = username basicAuth = "Basic " + base64.b64encode(userpass); connection.setRequestProperty ("Authorization", basicAuth); connection.setRequestMethod("POST") if contentType != None: connection.setRequestProperty("Content-Type", contentType) connection.setRequestProperty("Content-Length", str(len(paramStr))) connection.setRequestProperty("Content-Language", "en-GB") connection.setUseCaches(0) connection.setDoInput(1) connection.setDoOutput(2) #wr= DataOutputStream(connection.getOutputStream()) #wr.writeBytes(paramStr) #wr.flush() #wr.close() inStream= connection.getInputStream() rd= BufferedReader(InputStreamReader(inStream)) response = "" line = rd.readLine() while line != None: response +=line+"\r" line = rd.readLine() rd.close() return response
def __init__(self): sessionDuration = grinder.properties.getInt( "player.sessionDurationInSeconds", 0) self.password = grinder.properties.getProperty("player.password") players_url = grinder.properties.getProperty("player.source-url") passwordHash = URLEncoder.encode( grinder.properties.getProperty("player.passwordHash"), "UTF-8") workers = grinder.properties.getInt("grinder.processes", 0) threads = grinder.properties.getInt("grinder.threads", 0) workerIndex = grinder.processNumber - grinder.firstProcessNumber threadsPerAgent = workers * threads agentIndex = grinder.agentNumber start = agentIndex * threadsPerAgent + workerIndex * threads if isLogEnabled: log("Worker will handle %s players starting from %d" % (threads, start)) playerRange = (start, threads) self.workerPlayers = [] params = "passwordHash=%s&minimumBalance=%s&startRow=%s&limit=%s" % ( passwordHash, str(sessionDuration / 5), str( playerRange[0]), str(threads)) urlStr = players_url + "?" + params try: data = StringBuffer() url = URL(urlStr) conn = url.openConnection() rd = BufferedReader(InputStreamReader(conn.getInputStream())) line = rd.readLine() while line is not None: data.append(line) line = rd.readLine() rd.close() if isLogEnabled: log(data.toString()) message = JSONValue.parse(str(String(data.toString(), "UTF-8"))) for entry in message: self.workerPlayers.append((entry.get(0), entry.get(1))) except Exception: raise Exception("Couldn't fetch players from %s: %s" % (urlStr, traceback.format_exc())) if isLogEnabled: log(str(self.workerPlayers))
def performPOST(cls, theURL, theAuth, theData): """ generated source for method performPOST """ message = URLEncoder.encode(theData, "UTF-8") try: connection.setDoOutput(True) connection.setRequestMethod("POST") writer.write("AUTH=" + theAuth + "&DATA=" + message) writer.close() if connection.getResponseCode() == HttpURLConnection.HTTP_OK: return BufferedReader(InputStreamReader(connection.getInputStream())).readLine() else: try: errorDescription = BufferedReader(InputStreamReader(connection.getInputStream())).readLine() except Exception as q: pass raise IOException(connection.getResponseCode() + ": " + errorDescription) except MalformedURLException as e: raise IOException(e) except IOException as e: raise e
def __init__(self): sessionDuration = grinder.properties.getInt("player.sessionDurationInSeconds", 0) self.password = grinder.properties.getProperty("player.password") players_url = grinder.properties.getProperty("player.source-url") passwordHash = URLEncoder.encode(grinder.properties.getProperty("player.passwordHash"), "UTF-8") workers = grinder.properties.getInt("grinder.processes", 0) threads = grinder.properties.getInt("grinder.threads", 0) workerIndex = grinder.processNumber - grinder.firstProcessNumber threadsPerAgent = workers * threads agentIndex = grinder.agentNumber start = agentIndex * threadsPerAgent + workerIndex * threads if isLogEnabled: log("Worker will handle %s players starting from %d" % (threads, start)) playerRange = (start, threads) self.workerPlayers = [] params = "passwordHash=%s&minimumBalance=%s&startRow=%s&limit=%s" % ( passwordHash, str(sessionDuration / 5), str(playerRange[0]), str(threads), ) urlStr = players_url + "?" + params try: data = StringBuffer() url = URL(urlStr) conn = url.openConnection() rd = BufferedReader(InputStreamReader(conn.getInputStream())) line = rd.readLine() while line is not None: data.append(line) line = rd.readLine() rd.close() if isLogEnabled: log(data.toString()) message = JSONValue.parse(str(String(data.toString(), "UTF-8"))) for entry in message: self.workerPlayers.append((entry.get(0), entry.get(1))) except Exception: raise Exception("Couldn't fetch players from %s: %s" % (urlStr, traceback.format_exc())) if isLogEnabled: log(str(self.workerPlayers))
def prepareForStep(self, configurationAttributes, requestParameters, step): print "Cert. Prepare for step %d" % step if step == 2: authenticationService = CdiUtil.bean(AuthenticationService) usrId = authenticationService.getAuthenticatedUser().getAttribute( "inum", False, False) rndKey = uuid.uuid4().hex CdiUtil.bean(Identity).setWorkingParameter("rndkey", rndKey) url = CdiUtil.bean(FacesContext).getExternalContext().getRequest( ).getServerName() url = "https://%s/casa/pl/cert-authn/index.zul" % url encr = CdiUtil.bean(EncryptionService).encrypt(rndKey + ";" + usrId) encr = URLEncoder.encode(encr, "UTF-8") url = "%s?key=%s" % (url, encr) CdiUtil.bean(FacesService).redirectToExternalURL(url) return True
def get(targetURL, params, username=None): paramStr = "" for aKey in params.keys(): paramStr += aKey + "=" + URLEncoder.encode(params[aKey], "UTF-8") + "&" paramStr = paramStr[:-1] url = URL(targetURL + "?" + paramStr) print url connection = url.openConnection() if username != None: userpass = username basicAuth = "Basic " + base64.b64encode(userpass) print basicAuth connection.setRequestProperty("Authorization", basicAuth) connection.setRequestMethod("GET") connection.setRequestProperty("Content-Language", "en-GB") connection.setUseCaches(0) connection.setDoOutput(2) return getResponse(connection)
def get(targetURL, params, username=None): paramStr = "" for aKey in params.keys(): paramStr+=aKey+"="+URLEncoder.encode(params[aKey], "UTF-8")+"&" paramStr=paramStr[:-1] url = URL(targetURL+"?"+paramStr) print url connection = url.openConnection() if username!=None: userpass = username basicAuth = "Basic " + base64.b64encode(userpass); print basicAuth connection.setRequestProperty ("Authorization", basicAuth); connection.setRequestMethod("GET") connection.setRequestProperty("Content-Language", "en-GB") connection.setUseCaches(0) connection.setDoOutput(2) return getResponse(connection);
def udp_received(src, data): console.info('probe response from:[%s] data:[%s]' % (src, data)) packet = json_decode(data) present = packet.get('present') if present is None: return for nodeName in present: if nodeName in nodeAddressesByName: # node already exists, so warn and continue console.warn('Node "%s" already exists' % nodeName) continue httpAddress = None for address in packet['addresses']: if address.startswith('http'): httpAddress = address httpAddress = httpAddress.replace( '%NODE%', URLEncoder.encode(nodeName, 'UTF-8')) if httpAddress is None: console.warn('No HTTP address for this node') continue nodeSimpleName = SimpleName(nodeName) # apply a name filter if present if len(reducedNameFilter) > 0: if reducedNameFilter not in nodeSimpleName.getReducedForMatchingName( ): continue nodeAddressesByName[nodeSimpleName] = httpAddress
def update(self): """Update information shown by the dialog with those of currently selected error """ from java.net import URL, URLEncoder from javax.xml.parsers import DocumentBuilderFactory error = self.app.selectedError check = error.check view = check.view tool = view.tool #user info if error.user is not None: errorUserName = error.user.getName() errorUserId = str(error.user.getId()) #download user info from OSM API accountDate = None changesetsNumber = None if errorUserId in self.app.users: userInfo = self.app.users[errorUserId] accountDate = userInfo["account date"] changesetsNumber = userInfo["changesets number"] else: docFactory = DocumentBuilderFactory.newInstance() docBuilder = docFactory.newDocumentBuilder() url = URL("http://api.openstreetmap.org/api/0.6/user/" + errorUserId) try: stream = url.openStream() doc = docBuilder.parse(stream) rootElement = doc.getDocumentElement() userNode = rootElement.getElementsByTagName("user").item(0) accountDate = userNode.getAttributes().getNamedItem("account_created").getNodeValue() changesetsNode = rootElement.getElementsByTagName("changesets").item(0) changesetsNumber = changesetsNode.getAttributes().getNamedItem("count").getNodeValue() except: print "I could not download user info from:\n", url pass if accountDate is not None: self.app.users[errorUserId] = {"account date": accountDate, "changesets number": changesetsNumber} #user links encodedErrorUserName = URLEncoder.encode(errorUserName, "UTF-8").replace("+", "%20") userUrl = "http://www.openstreetmap.org/user/%s/" % encodedErrorUserName msgUrl = "http://www.openstreetmap.org/message/new/%s" % encodedErrorUserName #update user info text = "<html><table>" text += "<tr><td>%s</td>" % self.app.strings.getString("User_name") text += "<td><a href='%s'>%s</a></td></tr>" % (userUrl, errorUserName) if accountDate is not None: text += "<tr>" text += "<td>%s</td>" % self.app.strings.getString("Changesets") text += "<td>%s</td>" % changesetsNumber text += "</tr><tr>" text += "<td>%s</td>" % self.app.strings.getString("Mapper_since") text += "<td>%s</td>" % accountDate[:10] text += "</tr>" text += "</table>" text += "<a href='%s'>%s</a>" % (msgUrl, self.app.strings.getString("Send_a_message")) text += "</html>" self.userInfoPanel.setText(text) #error info text = "<html>" #tool text += "%s:<br>%s" % (self.app.strings.getString("Error_reported_by_the_tool"), tool.title) if tool.uri != "": text += "<br>%s" % self.link(tool.uri) #error type if not tool.isLocal: text += "<br><br>%s:" % self.app.strings.getString("Type_of_error") text += "<br>%s --> %s" % (view.title, check.title) #error help, usually a link to a Wiki page describing this errror type #error link, e.g. a link to the error on the tool web page for propName, prop in ((self.app.strings.getString("Error_help"),\ check.helpUrl), (self.app.strings.getString("Error_link"), tool.error_url(error))): if prop != "": text += "<br><br>%s:" % propName text += "<br>%s" % self.link(prop) #error description, usually some info contained in the error file if error.desc != "": text += "<br><br>%s:" % self.app.strings.getString("Description") text += "<br>%s" % error.desc #OSM object if error.osmId != "": osmType = {"n": "node", "w": "way", "r": "relation"} osmLinks = "" osmIds = error.osmId.split("_") for i, osmId in enumerate(osmIds): osmIdUrl = "http://www.openstreetmap.org/%s/%s" % (osmType[osmId[0]], osmId[1:]) osmLinks += self.link(osmIdUrl) if i != len(osmIds) - 1: osmLinks += "<br>" text += "<br><br>%s:" % self.app.strings.getString("OSM_objects") text += "<br>%s" % osmLinks #OSM changeset if error.changeset is not None: changesetUrl = "http://www.openstreetmap.org/changeset/%s" % error.changeset text += "<br><br>%s:" % self.app.strings.getString("OSM_changeset") text += "<br>%s" % self.link(changesetUrl) text += "</html>" #Update error info self.errorInfoPanel.setText(text) self.show()
def __getAnnotates(self, aUrl): aUrl = URLEncoder.encode(aUrl, "utf-8") url = "%s?%s=%s" % (self.__baseUrl, "w3c_annotates", aUrl) s = self.__get(url) return s
from org.apache.commons.httpclient import URI from synchronize import make_synchronized import org.openqa.selenium.By as By import java.util.concurrent.TimeUnit as TimeUnit import org.openqa.selenium.firefox.FirefoxDriver as FirefoxDriver; import org.openqa.selenium.firefox.FirefoxOptions as FirefoxOptions; import org.openqa.selenium.support.ui.WebDriverWait as WebDriverWait; import org.openqa.selenium.support.ui.ExpectedConditions as ExpectedConditions; import org.parosproxy.paros.model.Model as Model import org.apache.http.client.utils.URLEncodedUtils as URLEncodedUtils import java.nio.charset.Charset as Charset; import java.net.URLEncoder as URLEncoder import java.nio.charset.StandardCharsets as StandardCharsets APP_ANGULAR_URL = 'http://localhost:8080/app-angular2'; ENCODED_APP_ANGULAR_URL=URLEncoder.encode(APP_ANGULAR_URL, StandardCharsets.UTF_8.toString()); KEYCLOAK_BASE_URL = 'http://localhost:8180/auth'; KEYCLOAK_REALM="master"; USERNAME = "******"; PASSWORD = "******"; #constants of cookie names AUTH_SESSION_ID_LEGACY_COOKIE_NAME="AUTH_SESSION_ID_LEGACY"; KC_RESTART_COOKIE_NAME="KC_RESTART"; KEYCLOAK_IDENTITY_LEGACY_COOKIE_NAME="KEYCLOAK_IDENTITY_LEGACY"; KEYCLOAK_SESSION_LEGACY_COOKIE_NAME="KEYCLOAK_SESSION_LEGACY"; ACCESS_TOKEN_KEY_NAME="ACCESS_TOKEN"; ACCESS_TOKEN_CREATION_TIMESTAMP_KEY_NAME="ACCESS_TOKEN_CREATE_TIMESTAMP";#needs to have a lenght < 30 for a key in GlobalVariables ACCESS_TOKEN_EXPIRY_IN_SECONDS_KEY_NAME="ACCESS_TOKEN_EXPIRY_IN_SEC";#needs to have a lenght < 30 for a key in GlobalVariables def sendingRequest(msg, initiator, helper):
def encode(self, url): return URLEncoder.encode(url, "UTF-8")
def stash(args): user = checkUser() try: from java.net import URLEncoder from com.atlassian.jira.component import ComponentAccessor from com.atlassian.sal.api.net.Request import MethodType componentClassManager = ComponentAccessor.getComponentClassManager() ApplicationId = componentClassManager.loadClass( 'com.atlassian.applinks.api.ApplicationId') ApplicationLinkResponseHandler = componentClassManager.loadClass( 'com.atlassian.applinks.api.ApplicationLinkResponseHandler') ApplicationLinkService = componentClassManager.loadClass( 'com.atlassian.applinks.api.ApplicationLinkService') appLinkService = ComponentAccessor.getComponentOfType( ApplicationLinkService) appLink = appLinkService.getApplicationLink( ApplicationId('12345678-abcd-90ef-123a-4b567c89e012')) req = None if args['method'] == 'createpullrequest' and 'review' in args: project = args['review']['project'] repo = URLEncoder.encode(args['review']['repo']) url = '/rest/api/1.0/projects/%s/repos/%s/pull-requests' % ( project, repo) title = '%s %s' % (args['review']['key'], args['review']['summary']) payload = { 'title': title[:255], 'description': None, 'state': 'OPEN', 'open': True, 'closed': False, 'fromRef': { 'id': 'refs/heads/%s' % args['review']['branch'], 'repository': { 'slug': args['review']['repo'], 'name': None, 'project': { 'key': project } } }, 'toRef': { 'id': 'refs/heads/master', 'repository': { 'slug': args['review']['repo'], 'name': None, 'project': { 'key': project } } }, 'reviewers': [{ 'user': { 'name': u } } for u in list(set(args['review']['reviewers'])) if u != ''] } req = appLink.createAuthenticatedRequestFactory().createRequest( MethodType.POST, url) req.setHeader('Content-Type', 'application/json; charset=UTF-8') req.setRequestBody(json.dumps(payload)) except Exception, e: log.error(str(e)) return {'result': False, 'error': str(e)}
def addTag(self, tag): encodedTag = URLEncoder.encode(tag, "UTF-8") tagNode = Tag(self.__model, "urn:tags:" + encodedTag, True) tagNode.setMeans(self.__model.createURI("urn:tags:" + encodedTag)) tagNode.setTaglabel(self.__model.createPlainLiteral(tag)) self.__content.addTagged(tagNode)
def escapeUrl(self, text): return URLEncoder.encode(text, "utf-8")
def verifyRoles(self, accessToken, softwareStatementId) : header = { "Authorization": "Bearer " + accessToken } try: sslContext = self.getSslContext() httpClient = HttpClients.custom().setSSLContext(sslContext).build() httpService = CdiUtil.bean(HttpService) http_service_response = httpService.executeGet(httpClient, self.tppUrl+"?filter="+ URLEncoder.encode(self.buildFilter(softwareStatementId)) + "&attributes=totalResults", header ) http_response = http_service_response.getHttpResponse() except: print "Client Registration. verification. Exception: ", sys.exc_info()[1] return False try: if not httpService.isResponseStastusCodeOk(http_response): print "Client Registration. verification. Got invalid response from validation server: ", str(http_response.getStatusLine().getStatusCode()) httpService.consume(http_response) return False response_bytes = httpService.getResponseContent(http_response) response_string = httpService.convertEntityToString(response_bytes) httpService.consume(http_response) finally: http_service_response.closeConnection() if response_string == None: print "Client Registration. verification. Got empty response from location server" return False response = json.loads(response_string) if int(response['totalResults']) <= 0 : print "Client Registration. verification. No matches found: '%s'" % response['totalResults'] return False return True
#m=latlonRE.match(str(coor)) #print 'match: ', m, 'new: ', element.isNew() if not(element.isNew()) and lon and lat:# and m: print 'Coordinates not yet present in Wikidata, building up coordStatements' coordStatement = Q_school + '\tP625\t@' + lat[:7] + '/' + lon[:7] + '\tS854\t"https://www.openstreetmap.org/' + type + '/' + str(element.getId()) + '"\n' coordStatements[Q_school] = coordStatement # pprint.pprint(coordStatements) else: print 'Coordinates already present in Wikidata' if coordStatements: number = 0; qs_url=''; doit = '&doit' for coordStatement in coordStatements: print coordStatements[coordStatement] qs_url += URLEncoder.encode(coordStatements[coordStatement], "UTF-8") if number > 8: OpenBrowser.displayUrl('http://tools.wmflabs.org/wikidata-todo/quick_statements.php?list=' + qs_url + doit) number = 0; qs_url='' else: number+=1 if qs_url: OpenBrowser.displayUrl('http://tools.wmflabs.org/wikidata-todo/quick_statements.php?list=' + qs_url + doit) if noNewSchools: print 'switching to regular account' if not(Main.pref.get("osm-server.username") == osm_account): Main.pref.put("osm-server.username", osm_account) JOptionPane.showMessageDialog(Main.parent, "Switched back to regular OSM account, please upload the usual way") else: print 'switching to import account and selecting all new schools' Main.pref.put("osm-server.username", osm_import_account)
def __getReplies(self, aUrl): aUrl = URLEncoder.encode(aUrl, "utf-8") url = "%s?%s=%s" % (self.__baseUrl, "w3c_reply_tree", aUrl) s = self.__get(url) return s
level = '' instanceof = 'Q3914' # school if 'Prim' in name: isced = '1' instanceof = 'Q9842' # primary school level = 'primary ' elif 'Nurser' in name: isced = '0' instanceof = 'Q1076052' # Nursery school level = 'nursery ' elif 'Sec' in name or 'High' or 'College' in name: isced = '2;3;4' instanceof = 'Q159334' # secondary school level = 'secondary ' params = '?action=wbsearchentities&search=' + URLEncoder.encode( name, "UTF-8") + '&language=en&format=json' url = baseurl + 'api.php' + params r1 = HttpClient.create(URL(url), "GET") r2 = r1.setHeader( "Content-Type", "application/x-www-form-urlencoded").connect().fetchContent() #print dir(r2) print r2 Q_school = QinJSONRE.search(r2) print Q_school if not (Q_school): districtStatement = '' if district: params = '?action=wbsearchentities&search=' + district + '%20District&language=en&format=json' url = baseurl + 'api.php' + params
def urlEncode(self, text): return URLEncoder.encode(text, "utf-8")
def escapeUrl(self, text): return URLEncoder.encode(text,"utf-8")
def __getJsonCouchDB(self): if self.__baseUrl is None: d = {"error":"no annotation server setup in the 'system-config.json' file!", "data":[]} return JsonConfigHelper(d).toString() method = formData.get("method") url = formData.get("url") if url is None: url = "" try: if method=="info": d = {"enabled": True, "storageType": self.__storageType, "baseUrl": self.__baseUrl} elif method=="getAnnotation": # _design/anno/_list/anno/anno?key= key = URLEncoder.encode('"' + url + '"', "utf-8") #json = self.__get(self.__baseUrl + url) json = self.__get(self.__baseUrl + "_design/anno/_list/anno/anno?key=" + key) return json elif method=="getAnnotates": u = self.__baseUrl + '_design/anno/_list/annosFor/annotations?key=%s' u = u % URLEncoder.encode('"' + url + '"', "utf-8") json = self.__get(u) return json elif method=="getReplies": d = {"data":[]} elif method=="delete": r = self.__delete(url) if r: d = {"deleted": "OK"} else: d = {"delete": "Failed"} elif method=="close": pass elif method=="create": annotates = formData.get("annotates") or "" elemId = formData.get("elemId") or "" body = formData.get("body") or "" creator = formData.get("creator") or "" date = formData.get("date") or "" bodyTitle = formData.get("bodyTitle") or "" title = formData.get("title") or "" annotationType = formData.get("annotationType") or "Comment" root = formData.get("root") or "" inReplyTo = formData.get("inReplyTo") or "" content = formData.get("content") or "" json = self.__createJson(annotates, elemId, body, creator, date, bodyTitle, title, annotationType, root, inReplyTo, content) status, reply = self.__post(self.__baseUrl, json) if status.startswith("2"): json = reply[:-1] + ', "status":"%s"}' % status print json return json else: d = {"status": status} elif method=="test": return "Testing" else: d = {"error": "Unknown method '%s'" % method, "data":[]} except Exception, e: d = {"error": "Exception '%s'" % repr(e)}
level = ''; instanceof = 'Q3914' # school if 'Prim' in name: isced = '1' instanceof = 'Q9842' # primary school level = 'primary ' elif 'Nurser' in name: isced = '0' instanceof = 'Q1076052' # Nursery school level = 'nursery ' elif 'Sec' in name or 'High' or 'College' in name: isced = '2;3;4' instanceof = 'Q159334' # secondary school level = 'secondary ' params = '?action=wbsearchentities&search=' + URLEncoder.encode(name, "UTF-8") + '&language=en&format=json' url = baseurl + 'api.php' + params r1 = HttpClient.create(URL(url), "GET") r2 = r1.setHeader("Content-Type", "application/x-www-form-urlencoded").connect().fetchContent() #print dir(r2) print r2 Q_school = QinJSONRE.search(r2) print Q_school if not(Q_school): districtStatement = '' if district: params = '?action=wbsearchentities&search=' + district + '%20District&language=en&format=json' url = baseurl + 'api.php' + params r1 = HttpClient.create(URL(url), "GET") r2 = r1.setHeader("Content-Type", "application/x-www-form-urlencoded").connect().fetchContent()
def sendRequestToTrishul(self,messageInfo): request = messageInfo.getRequest() req_time = datetime.datetime.today() requestURL = self._helpers.analyzeRequest(messageInfo).getUrl() messageInfo = self._callbacks.makeHttpRequest(self._helpers.buildHttpService(str(requestURL.getHost()), int(requestURL.getPort()), requestURL.getProtocol() == "https"), request) resp_time = datetime.datetime.today() time_taken = (resp_time - req_time).total_seconds() response = messageInfo.getResponse() #initialozations of default value SQLiimp = self.NOT_FOUND SSTIimp = self.NOT_FOUND XSSimp = self.NOT_FOUND Comp_req = messageInfo requestInfo = self._helpers.analyzeRequest(messageInfo) self.content_resp = self._helpers.analyzeResponse(response) requestURL = requestInfo.getUrl() parameters = requestInfo.getParameters() requeststring = self._helpers.bytesToString(request) headers = requestInfo.getHeaders() #Used to obtain GET, POST and JSON parameters from burp api param_new = [p for p in parameters if p.getType() == 0 or p.getType() == 1 or p.getType() == 6] i = 0 xssflag=0 sqliflag=0 sstiflag=0 resultxss = [] resultsqli = [] resultssti = [] xssreqresp = [] sqlireqresp = [] sstireqresp = [] ssti_description = [] sqli_description = [] xss_description = [] for i in range(len(param_new)): name = param_new[i].getName() ptype = param_new[i].getType() param_value = param_new[i].getValue() #check XSS if ticked if self.xsscheck.isSelected(): score = 0 flag1 = 0 XSSimp = self.NOT_FOUND payload_array = ["<", ">", "\\\\'asd", "\\\\\"asd", "\\", "'\""] json_payload_array = ["<", ">", "\\\\'asd", "\\\"asd", "\\", "\'\\\""] payload_all = "" json_payload = "" rand_str = "testtest" for payload in payload_array: payload_all = payload_all+rand_str+payload payload_all = URLEncoder.encode(payload_all, "UTF-8") for payload in json_payload_array: json_payload = json_payload+rand_str+payload json_payload = URLEncoder.encode(json_payload, "UTF-8") if ptype == 0 or ptype == 1: new_paramters_value = self._helpers.buildParameter(name, payload_all, ptype) updated_request = self._helpers.updateParameter(request, new_paramters_value) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_payload) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_payload+"\"") updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) attack = self.makeRequest(Comp_req, updated_request) response = attack.getResponse() response_str = self._helpers.bytesToString(response) xssreqresp.append(attack) if_found_payload = "" non_encoded_symbols = "" for check_payload in payload_array: if_found_payload = rand_str+check_payload if if_found_payload in response_str: non_encoded_symbols = non_encoded_symbols+"<br>"+check_payload.replace('<', '<') score = score+1 flag1 = 1 if score > 2: XSSimp = self.CHECK if score > 3: XSSimp = self.FOUND xssflag = self.checkBetterScore(score,xssflag) if non_encoded_symbols == " \\\\'asd": XSSimp = self.NOT_FOUND if non_encoded_symbols != '': xss_description.append("The Payload <b>" + payload_all.replace('<', '<') + "</b> was passed in the request for the paramater <b>" + self._helpers.urlDecode(name) + "</b>. Some Tags were observed in the output unfiltered. A payload can be generated with the observed tags.<br>Symbols not encoded for parameter <b>" + name + "</b>: " + non_encoded_symbols) else: xss_description.append("") else: XSSimp = "Disabled" resultxss.append(XSSimp) if self.sqlicheck.isSelected(): SQLiimp = self.NOT_FOUND score = 0 value = "%27and%28select%2afrom%28select%28sleep%285%29%29%29a%29--" orig_time = datetime.datetime.today() if ptype == 0 or ptype == 1: new_paramters_value = self._helpers.buildParameter(name, value, ptype) updated_request = self._helpers.updateParameter(request, new_paramters_value) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+value) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+value+"\"") updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) attack1 = self.makeRequest(Comp_req, updated_request) response1 = attack1.getResponse() new_time = datetime.datetime.today() response_str1 = self._helpers.bytesToString(response1) sqlireqresp.append(attack1) diff = (new_time - orig_time).total_seconds() if (diff - time_taken) > 3: score = 4 self.error_array = ["check the manual that corresponds to your", "You have an error", "syntax error", "SQL syntax", "SQL statement", "ERROR:", "Error:", "MySQL","Warning:","mysql_fetch_array()"] found_text = "" for error in self.error_array: if error in response_str1: found_text = found_text + error score = score + 1 if score > 1: SQLiimp = self.CHECK if score > 2: SQLiimp = self.FOUND sqliflag = self.checkBetterScore(score,sqliflag) if found_text != '': sqli_description.append("The payload <b>"+self._helpers.urlDecode(value)+"</b> was passed in the request for parameter <b>"+self._helpers.urlDecode(name)+"</b>. Some errors were generated in the response which confirms that there is an Error based SQLi. Please check the request and response for this parameter") elif (diff - time_taken) > 3: sqli_description.append("The payload <b>"+self._helpers.urlDecode(value)+"</b> was passed in the request for parameter <b>"+self._helpers.urlDecode(name)+"</b>. The response was in a delay of <b>"+str(diff)+"</b> seconds as compared to original <b>"+str(time_taken)+"</b> seconds. This indicates that there is a time based SQLi. Please check the request and response for this parameter") else: sqli_description.append("") else: SQLiimp = "Disabled" resultsqli.append(SQLiimp) if self.ssticheck.isSelected(): score = 0 SSTIimp = self.NOT_FOUND payload_array = ["${123*456}", "<%=123*567%>", "{{123*678}}"] json_payload_array = ["$\{123*456\}", "<%=123*567%>", "\{\{123*678\}\}"] payload_all = "" rand_str = "jjjjjjj" json_payload = "" for payload in payload_array: payload_all = payload_all+rand_str+payload for payload in json_payload_array: json_payload = json_payload+rand_str+payload payload_all = URLEncoder.encode(payload_all, "UTF-8") json_payload = URLEncoder.encode(json_payload, "UTF-8") if ptype == 0 or ptype == 1: new_paramters_value = self._helpers.buildParameter(name, payload_all, ptype) updated_request = self._helpers.updateParameter(request, new_paramters_value) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_payload) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_payload+"\"") updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) attack = self.makeRequest(Comp_req, updated_request) response = attack.getResponse() response_str = self._helpers.bytesToString(response) self.expected_output = ["56088","69741","83394","3885","777777777777777"] for output in self.expected_output: if_found_payload = rand_str+output if if_found_payload in response_str: if output == self.expected_output[0]: sstireqresp.append(attack) ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Java</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>56088</b>") score = 2 if output == self.expected_output[1]: sstireqresp.append(attack) ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Ruby</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>69741</b>") score = 2 if output == self.expected_output[2]: payload_new = "{{5*'777'}}" json_payload_ssti = "\{\{5*'777'\}\}" payload = URLEncoder.encode("{{5*'777'}}", "UTF-8") json_ssti = URLEncoder.encode("\{\{5*'777'\}\}", "UTF-8") if ptype == 0 or ptype == 1: new_paramters = self._helpers.buildParameter(name, payload, ptype) ssti_updated_request = self._helpers.updateParameter(request, new_paramters) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+json_ssti) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+json_ssti+"\"") ssti_updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) self.ssti_attack = self.makeRequest(Comp_req, ssti_updated_request) ssti_response = self.ssti_attack.getResponse() ssti_response_str = self._helpers.bytesToString(ssti_response) if self.expected_output[3] in ssti_response_str: sstireqresp.append(self.ssti_attack) ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Twig</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>3885</b>") score = 2 elif self.expected_output[4] in ssti_response_str: sstireqresp.append(self.ssti_attack) self.responseMarkString = "777777777777777" ssti_description.append("Parameter <b>" + self._helpers.urlDecode(name) + "</b> is using <b>Jinja2</b> Template<br>The value <b>" + payload_new + "</b> was passed which gave result as <b>777777777777777</b>") score = 2 if score > 0: SSTIimp = self.CHECK if score > 1: SSTIimp = self.FOUND sstiflag = self.checkBetterScore(score,sstiflag) else: SSTIimp = "Disabled" resultssti.append(SSTIimp) if self.blindxss.isSelected(): blindxss_value = self.BlindXSSText.getText() if ptype == 0 or ptype == 1: new_paramters_value = self._helpers.buildParameter(name, blindxss_value, ptype) updated_request = self._helpers.updateParameter(request, new_paramters_value) else: jsonreq = re.search(r"\s([{\[].*?[}\]])$", requeststring).group(1) new = jsonreq.split(name+"\":",1)[1] if new.startswith('\"'): newjsonreq = jsonreq.replace(name+"\":\""+param_value,name+"\":\""+blindxss_value) else: newjsonreq = jsonreq.replace(name+"\":"+param_value,name+"\":\""+blindxss_value+"\"") updated_request = self._helpers.buildHttpMessage(headers, newjsonreq) attack = self.makeRequest(Comp_req, updated_request) if XSSimp != "Disabled": if xssflag > 3: XSSimp = self.FOUND elif xssflag > 2: XSSimp = self.CHECK else: XSSimp = self.NOT_FOUND if SSTIimp != "Disabled": if sstiflag > 1: SSTIimp = self.FOUND elif sstiflag > 0: SSTIimp = self.CHECK else: SSTIimp = self.NOT_FOUND if SQLiimp != "Disabled": if sqliflag > 3: SQLiimp = self.FOUND elif sqliflag > 2: SQLiimp = self.CHECK else: SQLiimp = self.NOT_FOUND self.addToLog(messageInfo, XSSimp, SQLiimp, SSTIimp, param_new, resultxss, resultsqli, resultssti, xssreqresp, sqlireqresp, sstireqresp , xss_description, sqli_description, ssti_description, req_time.strftime('%H:%M:%S %m/%d/%y'))
def push_content(self): userId = self.params.safeGetIntParam("userId") # 组合 xml 格式的字符串,以便进行提交, orginId = 0 contentType = "blog" href = "" trueName = "" description = "" icon = "" subjectName = "" gradeName = "" unitName = "" unitTitle = "" unitId = 0 gradeId = 0 metaSubjectId = 0 pushUserName = "" platformGuid = "" platformName = "" productConfigService = __spring__.getBean("ProductConfigService") productConfigService.isValid() platformGuid = productConfigService.getProductGuid() platformName = productConfigService.getProductName() #提交以下字段信息: href = self.get_site_url() user = self.userService.getUserById(userId) if user == None: response.getWriter().write("User not found") return pushUser = self.userService.getUserById(user.pushUserId) if pushUser == None: pushUserName = u"无法加载指定的用户" else: pushUserName = pushUser.trueName if pushUserName == None or pushUserName == "": pushUserName = pushUser.loginName orginId = user.getUserId() trueName = user.trueName if trueName == None:trueName = user.nickName if trueName == None:trueName = user.loginName if user.getBlogIntroduce() != None:description = user.getBlogIntroduce() if user.getUserIcon() != None: icon = user.getUserIcon() else: icon = "images/default.gif" if user.getSubjectId() != None: metaSubject = self.subjectService.getMetaSubjectById(user.getSubjectId()) if metaSubject != None: metaSubjectId = user.getSubjectId() subjectName = metaSubject.msubjName if user.getGradeId() != None: grade = self.subjectService.getGrade(user.getGradeId()) if grade != None: gradeId = user.getGradeId() gradeName = grade.gradeName if user.getUnitId() != None: unit = self.unitService.getUnitById(user.getUnitId()) if unit != None: unitId = user.getUnitId() unitName = unit.unitName unitTitle = unit.unitTitle xml = "<root>" xml = xml + "<orginId>" + str(orginId) + "</orginId>" xml = xml + "<contentType>" + contentType + "</contentType>" xml = xml + "<href>" + CommonUtil.xmlEncode(href) + "</href>" xml = xml + "<trueName>" + CommonUtil.xmlEncode(trueName) + "</trueName>" xml = xml + "<description>" + CommonUtil.xmlEncode(description) + "</description>" xml = xml + "<icon>" + CommonUtil.xmlEncode(icon) + "</icon>" xml = xml + "<subjectName>" + CommonUtil.xmlEncode(subjectName) + "</subjectName>" xml = xml + "<gradeName>" + CommonUtil.xmlEncode(gradeName) + "</gradeName>" xml = xml + "<unitName>" + CommonUtil.xmlEncode(unitName) + "</unitName>" xml = xml + "<unitTitle>" + CommonUtil.xmlEncode(unitTitle) + "</unitTitle>" xml = xml + "<unitId>" + str(unitId) + "</unitId>" xml = xml + "<gradeId>" + str(gradeId) + "</gradeId>" xml = xml + "<metaSubjectId>" + str(metaSubjectId) + "</metaSubjectId>" xml = xml + "<platformGuid>" + CommonUtil.xmlEncode(platformGuid) + "</platformGuid>" xml = xml + "<platformName>" + CommonUtil.xmlEncode(platformName) + "</platformName>" xml = xml + "<pushUserName>" + CommonUtil.xmlEncode(pushUserName) + "</pushUserName>" xml = xml + "</root>" postData = "data=" + URLEncoder.encode(xml, "utf-8") pd = PushData() ret = pd.Push(postData, self.topsiteUrl + "mashup/receiver.py?type=bloggroup") if ret == True: #print "postData=",ret result = pd.getReturnResult() if result == "LOCKED": response.getWriter().write("LOCKED") return elif result == "DELETED": response.getWriter().write("DELETED") return self.userService.setPushed(user) response.getWriter().write("OK") else: response.getWriter().write("ERROR") return
def __createTag(self, tag): encodedTag = URLEncoder.encode(tag, "UTF-8") tagNode = Tag(self.__model, "urn:tags:" + encodedTag, True) tagNode.setMeans(self.__model.createURI("urn:tags:" + encodedTag)); tagNode.setTaglabel(self.__model.createPlainLiteral(tag)) return tagNode
def createTranslatorURLfromDTO( parOverwrite, parDTO, parTranslatorID, parTranslatorPass, parTranlateVersion): # num = gameobjectnummer # name = wdb_Name1 # type = wdb_Unk3 # model = wdb_ModellID # sound0 = wdb_Unk9 # sound1 = wdb_Unk10 # sound2 = wdb_Unk11 # sound3 = wdb_Unk12 # sound4 = wdb_Unk13 # sound5 = wdb_Unk14 # sound6 = wdb_Unk15 # sound7 = wdb_Unk16 # sound8 = wdb_Unk17 # sound9 = wdb_Unk18 # loot = Unknown in WDB format # size = Unknown in WDB format # flags = Unknown in WDB format # # tID # tpw # translateversion retValue = "" if parOverwrite == "yes": retValue = retValue + "overwrite=yes" else: retValue = retValue + "overwrite=no" # num retValue = retValue + "&num=" + parDTO.getColumnValue("wdb_ObjectID").toString() # name = wdb_Name1 retValue = retValue + "&name=" + URLEncoder.encode( parDTO.getColumnValue("wdb_Name1")) # type = wdb_Unk3 retValue = retValue + "&type=" + parDTO.getColumnValue("wdb_Unk3").toString() # model = wdb_ModellID retValue = retValue + "&model=" + parDTO.getColumnValue("wdb_ModellID").toString() # sound0 = wdb_Unk9 dtoVal = (parDTO.getColumnValue("wdb_Unk9") ) if dtoVal != 0: retValue = retValue + "&sound0=" + str(dtoVal) else: retValue = retValue + "&sound0=none" # sound1 = wdb_Unk10 dtoVal = (parDTO.getColumnValue("wdb_Unk10") ) if dtoVal != 0: retValue = retValue + "&sound1=" + str(dtoVal) else: retValue = retValue + "&sound1=none" # sound2 = wdb_Unk11 dtoVal = (parDTO.getColumnValue("wdb_Unk11") ) if dtoVal != 0: retValue = retValue + "&sound2=" + str(dtoVal) else: retValue = retValue + "&sound2=none" # sound3 = wdb_Unk12 dtoVal = (parDTO.getColumnValue("wdb_Unk12") ) if dtoVal != 0: retValue = retValue + "&sound3=" + str(dtoVal) else: retValue = retValue + "&sound3=none" # sound4 = wdb_Unk13 dtoVal = (parDTO.getColumnValue("wdb_Unk13") ) if dtoVal != 0: retValue = retValue + "&sound4=" + str(dtoVal) else: retValue = retValue + "&sound4=none" # sound5 = wdb_Unk14 dtoVal = (parDTO.getColumnValue("wdb_Unk14") ) if dtoVal != 0: retValue = retValue + "&sound5=" + str(dtoVal) else: retValue = retValue + "&sound5=none" # sound6 = wdb_Unk15 dtoVal = (parDTO.getColumnValue("wdb_Unk15") ) if dtoVal != 0: retValue = retValue + "&sound6=" + str(dtoVal) else: retValue = retValue + "&sound6=none" # sound7 = wdb_Unk16 dtoVal = (parDTO.getColumnValue("wdb_Unk16") ) if dtoVal != 0: retValue = retValue + "&sound7=" + str(dtoVal) else: retValue = retValue + "&sound7=none" # sound8 = wdb_Unk17 dtoVal = (parDTO.getColumnValue("wdb_Unk17") ) if dtoVal != 0: retValue = retValue + "&sound8=" + str(dtoVal) else: retValue = retValue + "&sound8=none" # sound9 = wdb_Unk18 dtoVal = (parDTO.getColumnValue("wdb_Unk18") ) if dtoVal != 0: retValue = retValue + "&sound9=" + str(dtoVal) else: retValue = retValue + "&sound9=none" # loot = Unknown in WDB format retValue = retValue + "&loot=none" # size = Unknown in WDB format retValue = retValue + "&size=none" # flags = Unknown in WDB format retValue = retValue + "&flags=none" # # tID = translatorID retValue = retValue + "&tID=" retValue = retValue + URLEncoder.encode(parTranslatorID) # tpw = translator's password retValue = retValue + "&tpw=" retValue = retValue + URLEncoder.encode(parTranslatorPass) # translateversion = translateversion retValue = retValue + "&translateversion=" retValue = retValue + URLEncoder.encode(parTranlateVersion) return retValue
def __init__(self, key, value, count): self.__key = key self.__value = URLEncoder.encode(value, "UTF-8") self.__count = count self.__subFacets = ArrayList()
def execute(self): channelId = self.params.safeGetIntParam("channelId") if channelId == 0: self.addActionError(u"您所访问的页面不存在!") return ActionResult.ACCESS_ERROR self.channel = self.channelPageService.getChannel(channelId) if self.channel == None: self.addActionError(u"无法加载指定的页面!") return ActionResult.ACCESS_ERROR map = HashMap() map.put("channel", self.channel) map.put("head_nav", "search") # 输出页头 headerContent = self.GenerateContentFromTemplateString( self.channel.headerTemplate) footerContent = self.GenerateContentFromTemplateString( self.channel.footerTemplate) # 输出主体部分: k = self.params.safeGetStringParam("k") f = self.params.safeGetStringParam("f") k = URLEncoder.encode(k, "utf-8") if k == "": mainContent = u"<div style='padding:20px;font-size:14px;color:red;text-align:center'>请输入关键字。<br/><br/><a href='channel.py?channelId=" + str( channelId) + u"'>重新输入</a></div>" else: if f == "article": response.sendRedirect( "channel.action?cmd=articlelist&channelId=" + str(self.channel.channelId) + "&k=" + k + "&f=title") return elif f == "resource": response.sendRedirect( "channel.action?cmd=resourcelist&channelId=" + str(self.channel.channelId) + "&k=" + k + "&f=title") return elif f == "video": response.sendRedirect( "channel.action?cmd=videolist&channelId=" + str(self.channel.channelId) + "&k=" + k + "&f=3") return elif f == "photo": response.sendRedirect( "channel.action?cmd=photolist&channelId=" + str(self.channel.channelId) + "&k=" + k + "&f=3") return elif f == "user": response.sendRedirect( "channel.action?cmd=userlist&channelId=" + str(self.channel.channelId) + "&k=" + k + "&f=trueName") return else: mainContent = u"<div style='padding:20px;font-size:14px;color:red;text-align:center'>查询的类别不正确。</div>" out = response.getWriter() if headerContent == "" and footerContent == "" and mainContent == "": out.println(u"该频道没有指定模板,无法显示页面内容。") return out.println(headerContent) out.println(mainContent) out.println(footerContent)
class OsmoseTool(Tool): def __init__(self, app): self.app = app #Tool title self.title = "Osmose" #Tool url self.uri = "http://osmose.openstreetmap.fr/" #Translations self.isTranslated = True #Corrected errors self.fixedFeedbackMode = "url" #False positives self.falseFeedbackMode = "url" #Additional preferences for this tool self.prefsGui = PrefsPanel(self.app) #Marker position self.markerPosition = (-8, -35) #x: x position of marker relative to the error #y: y position of marker relative to the error #None: the marker's center will be positioned at the error coordinates # useful for markers with the shape of a circle or a square #Tool checks #{view: [title, name, url, icon, marker], ...} self.toolInfo = { "10": [["0", "0", "0", "0"], ["1010", "1010", "1010", "1010"], ["1040", "1040", "1040", "1040"], ["1050", "1050", "1050", "1050"], ["1060", "1060", "1060", "1060"], ["1070", "1070", "1070", "1070"], ["1080", "1080", "1080", "1080"], ["1090", "1090", "1090", "1090"], ["1100", "1100", "1100", "1100"], ["1110", "1110", "1110", "1110"], ["1120", "1120", "1120", "1120"], ["1140", "1140", "1140", "1140"], ["1150", "1150", "1150", "1150"], ["1160", "1160", "1160", "1160"], ["1170", "1170", "1170", "1170"], ["1180", "1180", "1180", "1180"], ["1190", "1190", "1190", "1190"], ["1200", "1200", "1200", "1200"], ["1210", "1210", "1210", "1210"], ["1220", "1220", "1220", "1220"], ["1230", "1230", "1230", "1230"], ["1240", "1240", "1240", "1240"]], "20": [["2010", "2010", "2010", "2010"], ["2020", "2020", "2020", "2020"], ["2030", "2030", "2030", "2030"], ["2040", "2040", "2040", "2040"], ["2060", "2060", "2060", "2060"], ["2080", "2080", "2080", "2080"], ["2090", "2090", "2090", "2090"], ["2100", "2100", "2100", "2100"]], "30": [["3010", "3010", "3010", "3010"], ["3020", "3020", "3020", "3020"], ["3030", "3030", "3030", "3030"], ["3031", "3031", "3031", "3031"], ["3032", "3032", "3032", "3032"], ["3033", "3033", "3033", "3033"], ["3040", "3040", "3040", "3040"], ["3050", "3050", "3050", "3050"], ["3060", "3060", "3060", "3060"], ["3070", "3070", "3070", "3070"], ["3080", "3080", "3080", "3080"], ["3090", "3090", "3090", "3090"], ["3091", "3091", "3091", "3091"], ["3100", "3100", "3100", "3100"], ["3110", "3110", "3110", "3110"], ["3120", "3120", "3120", "3120"], ["3150", "3150", "3150", "3150"], ["3160", "3160", "3160", "3160"], ["3161", "3161", "3161", "3161"], ["3170", "3170", "3170", "3170"], ["3180", "3180", "3180", "3180"], ["3190", "3190", "3190", "3190"]], "40": [["4010", "4010", "4010", "4010"], ["4020", "4020", "4020", "4020"], ["4030", "4030", "4030", "4030"], ["4040", "4040", "4040", "4040"], ["4060", "4060", "4060", "4060"], ["4070", "4070", "4070", "4070"], ["4080", "4080", "4080", "4080"], ["4090", "4090", "4090", "4090"], ["4100", "4100", "4100", "4100"]], "50": [["5010", "5010", "5010", "5010"], ["5020", "5020", "5020", "5020"], ["5030", "5030", "5030", "5030"], ["5040", "5040", "5040", "5040"], ["5050", "5050", "5050", "5050"]], "60": [["6010", "6010", "6010", "6010"], ["6020", "6020", "6020", "6020"], ["6030", "6030", "6030", "6030"], ["6040", "6040", "6040", "6040"], ["6060", "6060", "6060", "6060"], ["6070", "6070", "6070", "6070"]], "70": [["7010", "7010", "7010", "7010"], ["7011", "7011", "7011", "7011"], ["7012", "7012", "7012", "7012"], ["7040", "7040", "7040", "7040"], ["7050", "7050", "7050", "7050"], ["7060", "7060", "7060", "7060"], ["7070", "7070", "7070", "7070"], ["7080", "7080", "7080", "7080"], ["7090", "7090", "7090", "7090"], ["7100", "7100", "7100", "7100"], ["7110", "7110", "7110", "7110"], ["7120", "7120", "7120", "7120"], ["7130", "7130", "7130", "7130"]], "80": [ ["8010", "8010", "8010", "8010"], ["8011", "8011", "8011", "8011"], ["8020", "8020", "8020", "8020"], ["8021", "8021", "8021", "8021"], ["8030", "8030", "8030", "8030"], ["8031", "8031", "8031", "8031"], ["8040", "8040", "8040", "8040"], ["8041", "8041", "8041", "8041"], ["8050", "8050", "8050", "8050"], ["8051", "8051", "8051", "8051"], ["8060", "8060", "8060", "8060"], ["8070", "8070", "8070", "8070"], ["8080", "8080", "8080", "8080"], ["8101", "8101", "8101", "8101"], ["8110", "8110", "8110", "8110"], ["8120", "8120", "8120", "8120"], ["8130", "8130", "8130", "8130"], ["8131", "8131", "8131", "8131"], ["8140", "8140", "8140", "8140"], ["8150", "8150", "8150", "8150"], ["8160", "8160", "8160", "8160"], ["8170", "8170", "8170", "8170"], ] } #add markers for view, checksInfo in self.toolInfo.iteritems(): for i, checkInfo in enumerate(checksInfo): icon = checkInfo[3] checksInfo[i].append("marker-b-%s" % icon) Tool.__init__(self, self.app) def download_urls(self, (zoneBbox, checks)): """Returns checks and urls for errors downloading """ #username username = self.app.toolsPrefs["osmose"]["username"] #level level = self.app.toolsPrefs["osmose"]["level"] #limit if (self.app.favouriteZoneStatus and self.app.favZone.zType in ("polygon", "boundary")) or len(checks) > 1: #if a limit exists it will be applied after the download limit = 500 else: if self.app.toolsPrefs["osmose"]["limit"] != "": self.app.toolsPrefs["osmose"]["limit"] = int( self.app.toolsPrefs["osmose"]["limit"]) limits = [ self.app.maxErrorsNumber, self.app.toolsPrefs["osmose"]["limit"] ] for i, l in enumerate(limits): if l == "" or l > 500: limits[i] = 500 limit = min(limits) url = "http://osmose.openstreetmap.fr/api/0.2/errors?" url += "bbox=%s" % ",".join([str(coord) for coord in zoneBbox]) url += "&item=%s&full=true" % ",".join([check.url for check in checks]) url += "&limit=%d" % limit url += "&level=%s" % level if username != "": url += "&username=%s" % URLEncoder.encode(username, "UTF-8") return [{"checks": checks, "url": url}]
def __init__(self): self.params = ParamUtil(request) if self.loginUser == None: response.sendRedirect(self.get_site_url() + "login.jsp?redUrl=" + URLEncoder.encode(self.get_site_url() + "evaluations.py","utf-8"))
def onAdvEvent(self, event, npc, player): if event == 'ad': try: c = URL('http://duck5duck.mooo.com/l2jtw_ad/l2jtw_ad.php').openConnection() if c: c.setDoOutput(True) o = DataOutputStream(c.getOutputStream()) s = self.param % ( C.RATE_XP , C.RATE_SP , C.RATE_PARTY_XP , C.RATE_PARTY_SP , C.PARTY_XP_CUTOFF_LEVEL , C.PET_XP_RATE , C.RATE_DROP_ITEMS , C.RATE_DROP_ITEMS_BY_RAID , C.RATE_DROP_MANOR , C.RATE_QUEST_DROP , C.RATE_DROP_ITEMS_ID.get(57) or 1.0 , C.BUFFS_MAX_AMOUNT , C.TRIGGERED_BUFFS_MAX_AMOUNT , C.DANCES_MAX_AMOUNT , C.RUN_SPD_BOOST , C.MAX_RUN_SPEED , C.MAX_PCRIT_RATE , C.MAX_MCRIT_RATE , C.MAX_PATK_SPEED , C.MAX_MATK_SPEED , C.MAX_EVASION , C.MAX_SUBCLASS , C.BASE_SUBCLASS_LEVEL , C.MAX_SUBCLASS_LEVEL , C.INVENTORY_MAXIMUM_NO_DWARF , C.INVENTORY_MAXIMUM_DWARF , C.INVENTORY_MAXIMUM_QUEST_ITEMS , C.WAREHOUSE_SLOTS_NO_DWARF , C.WAREHOUSE_SLOTS_DWARF , C.WAREHOUSE_SLOTS_CLAN , C.MAX_ADENA/100000000 , C.MAXIMUM_ONLINE_USERS , C.ENCHANT_CHANCE_ELEMENT_STONE , C.ENCHANT_CHANCE_ELEMENT_CRYSTAL , C.ENCHANT_CHANCE_ELEMENT_JEWEL , C.ENCHANT_CHANCE_ELEMENT_ENERGY , C.ENCHANT_SAFE_MAX , C.ENCHANT_SAFE_MAX_FULL , C.CLAN_LEVEL_6_COST , C.CLAN_LEVEL_7_COST , C.CLAN_LEVEL_8_COST , C.CLAN_LEVEL_9_COST , C.CLAN_LEVEL_10_COST , C.CLAN_LEVEL_11_COST , C.CLAN_LEVEL_6_REQUIREMENT , C.CLAN_LEVEL_7_REQUIREMENT , C.CLAN_LEVEL_8_REQUIREMENT , C.CLAN_LEVEL_9_REQUIREMENT , C.CLAN_LEVEL_10_REQUIREMENT , C.CLAN_LEVEL_11_REQUIREMENT , L2World.getInstance().getAllPlayersCount() , self.getRealOnline() , URLEncoder.encode(self.link, 'utf-8') , URLEncoder.encode(self.intro, 'utf-8') ) o.write(s) o.flush() o.close() i = c.getInputStream() r = "" while True: ch = i.read() if ch == -1: break r += chr(ch) if len(r): print r i.close() c.disconnect() except: return