⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 viewresultsfullvisualizer.java

📁 测试工具
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
						Style style = null;
						switch (responseLevel) {
						case 3:
							style = statsDoc.getStyle(STYLE_REDIRECT);
							break;
						case 4:
							style = statsDoc.getStyle(STYLE_CLIENT_ERROR);
							break;
						case 5:
							style = statsDoc.getStyle(STYLE_SERVER_ERROR);
							break;
						}

						statsBuff.append("Response code: ").append(responseCode).append(NL);
						statsDoc.insertString(statsDoc.getLength(), statsBuff.toString(), style);
						statsBuff = new StringBuffer(100); //reset for reuse

						// response message label
						String responseMsgStr = res.getResponseMessage();

						log.debug("valueChanged1 : response message - " + responseMsgStr);
						statsBuff.append("Response message: ").append(responseMsgStr).append(NL);

						statsBuff.append(NL).append("Response headers:").append(NL);
						statsBuff.append(res.getResponseHeaders()).append(NL);
						statsDoc.insertString(statsDoc.getLength(), statsBuff.toString(), null);
						statsBuff = null; // Done

						// get the text response and image icon
						// to determine which is NOT null
						if ((SampleResult.TEXT).equals(res.getDataType())) // equals(null) is OK
						{
							String response = getResponseAsString(res);
							if (command.equals(TEXT_COMMAND)) {
								showTextResponse(response);
							} else if (command.equals(HTML_COMMAND)) {
								showRenderedResponse(response, res);
							} else if (command.equals(JSON_COMMAND)) {
								showRenderJSONResponse(response);
							} else if (command.equals(XML_COMMAND)) {
								showRenderXMLResponse(response);
							}
						} else {
							byte[] responseBytes = res.getResponseData();
							if (responseBytes != null) {
								showImage(new ImageIcon(responseBytes)); //TODO implement other non-text types
							}
						}
					}
				}
				else if(userObject instanceof AssertionResult) {
					AssertionResult res = (AssertionResult) userObject;
					
					// We are displaying an AssertionResult
					setupTabPaneForAssertionResult();
					
					if (log.isDebugEnabled()) {
						log.debug("valueChanged1 : sample result - " + res);
					}

					if (res != null) {
						StringBuffer statsBuff = new StringBuffer(100);
						statsBuff.append("Assertion error: ").append(res.isError()).append(NL);
						statsBuff.append("Assertion failure: ").append(res.isFailure()).append(NL);
						statsBuff.append("Assertion failure message : ").append(res.getFailureMessage()).append(NL);
						statsDoc.insertString(statsDoc.getLength(), statsBuff.toString(), null);
						statsBuff = null;
					}
				}
			}
		} catch (BadLocationException exc) {
			log.error("Error setting statistics text", exc);
			stats.setText("");
		}
		log.debug("End : valueChanged1");
	}

	private void showImage(Icon image) {
		imageLabel.setIcon(image);
		resultsScrollPane.setViewportView(imageLabel);
		textButton.setEnabled(false);
		htmlButton.setEnabled(false);
		jsonButton.setEnabled(false);
		xmlButton.setEnabled(false);
	}

	protected void showTextResponse(String response) {
		results.setContentType("text/plain"); // $NON-NLS-1$
		results.setText(response == null ? "" : response); // $NON-NLS-1$
		results.setCaretPosition(0);
		resultsScrollPane.setViewportView(results);

		textButton.setEnabled(true);
		htmlButton.setEnabled(true);
		jsonButton.setEnabled(true);
		xmlButton.setEnabled(true);
	}

	// It might be useful also to make this available in the 'Request' tab, for
	// when posting JSON.
	private static String prettyJSON(String json) {
		StringBuffer pretty = new StringBuffer(json.length() * 2); // Educated guess

		final String tab = ":   "; // $NON-NLS-1$
		StringBuffer index = new StringBuffer();
		String nl = ""; // $NON-NLS-1$

		Matcher valueOrPair = VALUE_OR_PAIR_PATTERN.matcher(json);

		boolean misparse = false;

		for (int i = 0; i < json.length(); ) {
			final char currentChar = json.charAt(i);
			if ((currentChar == '{') || (currentChar == '[')) {
				pretty.append(nl).append(index).append(currentChar);
				i++;
				index.append(tab);
				misparse = false;
			}
			else if ((currentChar == '}') || (currentChar == ']')) {
				if (index.length() > 0) {
					index.delete(0, tab.length());
				}
				pretty.append(nl).append(index).append(currentChar);
				i++;
				int j = i;
				while ((j < json.length()) && Character.isWhitespace(json.charAt(j))) {
					j++;
				}
				if ((j < json.length()) && (json.charAt(j) == ',')) {
					pretty.append(","); // $NON-NLS-1$
					i=j+1;
				}
				misparse = false;
			}
			else if (valueOrPair.find(i) && valueOrPair.group().length() > 0) {
				pretty.append(nl).append(index).append(valueOrPair.group());
				i=valueOrPair.end();
				misparse = false;
			}
			else {
				if (!misparse) {
					pretty.append(nl).append("- Parse failed from:");
				}
				pretty.append(currentChar);
				i++;
				misparse = true;
			}
			nl = "\n"; // $NON-NLS-1$
		}
		return pretty.toString();
	}
	
	private void showRenderJSONResponse(String response) {
		results.setContentType("text/plain"); // $NON-NLS-1$
		results.setText(response == null ? "" : prettyJSON(response));
		results.setCaretPosition(0);
		resultsScrollPane.setViewportView(results);

		textButton.setEnabled(true);
		htmlButton.setEnabled(true);
		jsonButton.setEnabled(true);
		xmlButton.setEnabled(true);
	}

	private static final SAXErrorHandler saxErrorHandler = new SAXErrorHandler();

	private void showRenderXMLResponse(String response) {
		String parsable="";
		if (response == null) {
			results.setText(""); // $NON-NLS-1$
			parsable = ""; // $NON-NLS-1$
		} else {
			results.setText(response);
			int start = response.indexOf(XML_PFX);
			if (start > 0) {
			    parsable = response.substring(start);				
			} else {
			    parsable=response;
			}
		}
		results.setContentType("text/xml"); // $NON-NLS-1$
		results.setCaretPosition(0);

		Component view = results;

		// there is duplicate Document class. Therefore I needed to declare the
		// specific
		// class that I want
		org.w3c.dom.Document document = null;

		try {

			DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
			parserFactory.setValidating(false);
			parserFactory.setNamespaceAware(false);

			// create a parser:
			DocumentBuilder parser = parserFactory.newDocumentBuilder();

			parser.setErrorHandler(saxErrorHandler);
			document = parser.parse(new InputSource(new StringReader(parsable)));

			JPanel domTreePanel = new DOMTreePanel(document);

			document.normalize();

			view = domTreePanel;
		} catch (SAXParseException e) {
			showErrorMessageDialog(saxErrorHandler.getErrorMessage(), saxErrorHandler.getMessageType());
			log.debug(e.getMessage());
		} catch (SAXException e) {
			showErrorMessageDialog(e.getMessage(), JOptionPane.ERROR_MESSAGE);
			log.debug(e.getMessage());
		} catch (IOException e) {
			showErrorMessageDialog(e.getMessage(), JOptionPane.ERROR_MESSAGE);
			log.debug(e.getMessage());
		} catch (ParserConfigurationException e) {
			showErrorMessageDialog(e.getMessage(), JOptionPane.ERROR_MESSAGE);
			log.debug(e.getMessage());
		}
		resultsScrollPane.setViewportView(view);
		textButton.setEnabled(true);
		htmlButton.setEnabled(true);
		jsonButton.setEnabled(true);
		xmlButton.setEnabled(true);
	}

	private static String getResponseAsString(SampleResult res) {

		String response = null;
		if ((SampleResult.TEXT).equals(res.getDataType())) {
			// Showing large strings can be VERY costly, so we will avoid
			// doing so if the response
			// data is larger than 200K. TODO: instead, we could delay doing
			// the result.setText
			// call until the user chooses the "Response data" tab. Plus we
			// could warn the user
			// if this happens and revert the choice if he doesn't confirm
			// he's ready to wait.
			int len = res.getResponseData().length;
			if (len > 200 * 1024) {
				response = "Response too large to be displayed (" + len + " bytes).";
				log.warn(response);
			} else {
				response = res.getResponseDataAsString();
			}
		}
		return response;
	}

	/**
	 * Display the response as text or as rendered HTML. Change the text on the
	 * button appropriate to the current display.
	 * 
	 * @param e
	 *            the ActionEvent being processed
	 */
	public void actionPerformed(ActionEvent e) {
		command = e.getActionCommand();

		if (command != null
				&& (command.equals(TEXT_COMMAND) || command.equals(HTML_COMMAND)
 				|| command.equals(JSON_COMMAND) || command.equals(XML_COMMAND))) {

			textMode = command.equals(TEXT_COMMAND);

			DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree.getLastSelectedPathComponent();

			if (node == null) {
				results.setText("");
				return;
			}

			SampleResult res = (SampleResult) node.getUserObject();
			String response = getResponseAsString(res);

			if (command.equals(TEXT_COMMAND)) {
				showTextResponse(response);
			} else if (command.equals(HTML_COMMAND)) {
				showRenderedResponse(response, res);
			} else if (command.equals(JSON_COMMAND)) {
				showRenderJSONResponse(response);
			} else if (command.equals(XML_COMMAND)) {
				showRenderXMLResponse(response);
			}
		}
	}

	protected void showRenderedResponse(String response, SampleResult res) {
		if (response == null) {
			results.setText("");
			return;
		}

		int htmlIndex = response.indexOf("<HTML"); // could be <HTML lang=""> // $NON-NLS-1$

		// Look for a case variation
		if (htmlIndex < 0) {
			htmlIndex = response.indexOf("<html"); // ditto // $NON-NLS-1$
		}

		// If we still can't find it, just try using all of the text
		if (htmlIndex < 0) {
			htmlIndex = 0;
		}

		String html = response.substring(htmlIndex);

		/*
		 * To disable downloading and rendering of images and frames, enable the
		 * editor-kit. The Stream property can then be
		 */

		// Must be done before setContentType
		results.setEditorKitForContentType(TEXT_HTML, downloadAll.isSelected() ? defaultHtmlEditor : customisedEditor);

		results.setContentType(TEXT_HTML);

		if (downloadAll.isSelected()) {
			// Allow JMeter to render frames (and relative images)
			// Must be done after setContentType [Why?]
			results.getDocument().putProperty(Document.StreamDescriptionProperty, res.getURL());
		}

		/*
		 * Get round problems parsing <META http-equiv='content-type'
		 * content='text/html; charset=utf-8'> See
		 * http://issues.apache.org/bugzilla/show_bug.cgi?id=23315
		 * 
		 * Is this due to a bug in Java?
		 */
		results.getDocument().putProperty("IgnoreCharsetDirective", Boolean.TRUE); // $NON-NLS-1$

		results.setText(html);
		results.setCaretPosition(0);
		resultsScrollPane.setViewportView(results);

		textButton.setEnabled(true);
		htmlButton.setEnabled(true);
		jsonButton.setEnabled(true);
		xmlButton.setEnabled(true);
	}

	private Component createHtmlOrTextPane() {
		ButtonGroup group = new ButtonGroup();

		textButton = new JRadioButton(JMeterUtils.getResString("view_results_render_text")); // $NON-NLS-1$
		textButton.setActionCommand(TEXT_COMMAND);
		textButton.addActionListener(this);
		textButton.setSelected(textMode);
		group.add(textButton);

		htmlButton = new JRadioButton(JMeterUtils.getResString("view_results_render_html")); // $NON-NLS-1$
		htmlButton.setActionCommand(HTML_COMMAND);
		htmlButton.addActionListener(this);
		htmlButton.setSelected(!textMode);
		group.add(htmlButton);

		jsonButton = new JRadioButton(JMeterUtils.getResString("view_results_render_json")); // $NON-NLS-1$
		jsonButton.setActionCommand(JSON_COMMAND);
		jsonButton.addActionListener(this);
		jsonButton.setSelected(!textMode);
		group.add(jsonButton);

		xmlButton = new JRadioButton(JMeterUtils.getResString("view_results_render_xml")); // $NON-NLS-1$
		xmlButton.setActionCommand(XML_COMMAND);
		xmlButton.addActionListener(this);
		xmlButton.setSelected(!textMode);
		group.add(xmlButton);

		downloadAll = new JCheckBox(JMeterUtils.getResString("view_results_render_embedded")); // $NON-NLS-1$

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -