List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:fr.inrialpes.exmo.align.service.HTTPTransport.java
/** * Starts a HTTP server to given port./*www.j av a 2s . c o m*/ * * @param params: the parameters of the connection, including HTTP port and host * @param manager: the manager which will deal with connections * @param serv: the set of services to be listening on this connection * @throws AServException when something goes wrong (e.g., socket already in use) */ public void init(Properties params, AServProtocolManager manager, Vector<AlignmentServiceProfile> serv) throws AServException { this.manager = manager; services = serv; tcpPort = Integer.parseInt(params.getProperty("http")); tcpHost = params.getProperty("host"); // ******************************************************************** // JE: Jetty implementation server = new Server(tcpPort); // The handler deals with the request // most of its work is to deal with large content sent in specific ways Handler handler = new AbstractHandler() { public void handle(String String, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String method = request.getMethod(); String uri = request.getPathInfo(); Properties params = new Properties(); try { decodeParams(request.getQueryString(), params); } catch (Exception ex) { logger.debug("IGNORED EXCEPTION: {}", ex); } ; // I do not decode them here because it is useless // See below how it is done. Properties header = new Properties(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); header.setProperty(headerName, request.getHeader(headerName)); } // Get the content if any // This is supposed to be only an uploaded file // Note that this could be made more uniform // with the text/xml part stored in a file as well. String mimetype = request.getContentType(); // Multi part: the content provided by an upload HTML form if (mimetype != null && mimetype.startsWith("multipart/form-data")) { try { //if ( !ServletFileUpload.isMultipartContent( request ) ) { // logger.debug( "Does not detect multipart" ); //} DiskFileItemFactory factory = new DiskFileItemFactory(); File tempDir = new File(System.getProperty("java.io.tmpdir")); factory.setRepository(tempDir); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); for (FileItem fi : items) { if (fi.isFormField()) { logger.trace(" >> {} = {}", fi.getFieldName(), fi.getString()); params.setProperty(fi.getFieldName(), fi.getString()); } else { logger.trace(" >> {} : {}", fi.getName(), fi.getSize()); logger.trace(" Stored at {}", fi.getName(), fi.getSize()); try { // FilenameUtils.getName() needed for Internet Explorer problem File uploadedFile = new File(tempDir, FilenameUtils.getName(fi.getName())); fi.write(uploadedFile); params.setProperty("filename", uploadedFile.toString()); params.setProperty("todiscard", "true"); } catch (Exception ex) { logger.warn("Cannot load file", ex); } // Another solution is to run this in /* InputStream uploadedStream = item.getInputStream(); ... uploadedStream.close(); */ } } ; } catch (FileUploadException fuex) { logger.trace("Upload Error", fuex); } } else if (mimetype != null && mimetype.startsWith("text/xml")) { // Most likely Web service request (REST through POST) int length = request.getContentLength(); if (length > 0) { char[] mess = new char[length + 1]; try { new BufferedReader(new InputStreamReader(request.getInputStream())).read(mess, 0, length); } catch (Exception e) { logger.debug("IGNORED Exception", e); } params.setProperty("content", new String(mess)); } // File attached to SOAP messages } else if (mimetype != null && mimetype.startsWith("application/octet-stream")) { File alignFile = new File(File.separator + "tmp" + File.separator + newId() + "XXX.rdf"); // check if file already exists - and overwrite if necessary. if (alignFile.exists()) alignFile.delete(); FileOutputStream fos = new FileOutputStream(alignFile); InputStream is = request.getInputStream(); try { byte[] buffer = new byte[4096]; int bytes = 0; while (true) { bytes = is.read(buffer); if (bytes < 0) break; fos.write(buffer, 0, bytes); } } catch (Exception e) { } finally { fos.flush(); fos.close(); } is.close(); params.setProperty("content", ""); params.setProperty("filename", alignFile.getAbsolutePath()); } // Get the answer (HTTP) HTTPResponse r = serve(uri, method, header, params); // Return it response.setContentType(r.getContentType()); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println(r.getData()); ((Request) request).setHandled(true); } }; server.setHandler(handler); // Common part try { server.start(); } catch (Exception e) { throw new AServException("Cannot launch HTTP Server", e); } //server.join(); // ******************************************************************** //if ( params.getProperty( "wsdl" ) != null ){ // wsmanager = new WSAServProfile(); // if ( wsmanager != null ) wsmanager.init( params, manager ); //} //if ( params.getProperty( "http" ) != null ){ // htmanager = new HTMLAServProfile(); // if ( htmanager != null ) htmanager.init( params, manager ); //} myId = "LocalHTMLInterface"; serverId = manager.serverURL(); logger.info("Launched on {}/html/", serverId); localId = 0; }
From source file:ro.raisercostin.web.DebuggingFilter.java
public String debug(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, DebuggingPrinter debuggingPrinter, boolean debugAll, boolean debugRequest) { final JspFactory jspFactory = JspFactory.getDefaultFactory(); HttpSession session = request.getSession(); debuggingPrinter.addHeader();/* w ww . j av a 2 s. co m*/ debuggingPrinter.addSection("Request Parameters"); for (Iterator iterator = request.getParameterMap().entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> parameter = (Map.Entry<String, Object>) iterator.next(); addRow(debuggingPrinter, parameter.getKey(), StringUtils.arrayToCommaDelimitedString((Object[]) parameter.getValue())); } debuggingPrinter.endSection(); if (debugRequest) { debuggingPrinter.addSection("Request Header"); for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { String parameterName = (String) e.nextElement(); addRow(debuggingPrinter, parameterName, debuggingPrinter.transform(request.getHeader(parameterName))); } debuggingPrinter.endSection(); debuggingPrinter.addSection("Request Attributes"); java.util.Enumeration en = request.getAttributeNames(); while (en.hasMoreElements()) { String attrName = (String) en.nextElement(); try { addRow(debuggingPrinter, split(attrName, 50), toString2(request.getAttribute(attrName), 120)); } catch (Exception e) { addRow(debuggingPrinter, split(attrName, 50), toString(e, 120)); } } debuggingPrinter.endSection(); debuggingPrinter.addSection("Session Attributes"); en = session.getAttributeNames(); while (en.hasMoreElements()) { String attrName = (String) en.nextElement(); try { addRow(debuggingPrinter, split(attrName, 50), toString2(session.getAttribute(attrName), 120)); } catch (Exception e) { addRow(debuggingPrinter, split(attrName, 50), toString(e, 120)); } } debuggingPrinter.endSection(); debuggingPrinter.addSection("Request Info"); addRow(debuggingPrinter, "AuthType", request.getAuthType()); addRow(debuggingPrinter, "ContextPath", request.getContextPath()); addRow(debuggingPrinter, "Method", request.getMethod()); addRow(debuggingPrinter, "PathInfo", request.getPathInfo()); addRow(debuggingPrinter, "PathTranslated", request.getPathTranslated()); addRow(debuggingPrinter, "Protocol", request.getProtocol()); addRow(debuggingPrinter, "QueryString", request.getQueryString()); addRow(debuggingPrinter, "RemoteAddr", request.getRemoteAddr()); addRow(debuggingPrinter, "RemoteUser", request.getRemoteUser()); addRow(debuggingPrinter, "RequestedSessionId", request.getRequestedSessionId()); addRow(debuggingPrinter, "RequestURI", request.getRequestURI()); addRow(debuggingPrinter, "RequestURL", request.getRequestURL().toString()); addRow(debuggingPrinter, "ServletPath", request.getServletPath()); addRow(debuggingPrinter, "Scheme", request.getScheme()); addRow(debuggingPrinter, "ServletPath", request.getServletPath()); } if (debugAll) { debuggingPrinter.addSection("Server"); addRow(debuggingPrinter, "Server Info", servletContext.getServerInfo()); addRow(debuggingPrinter, "Servlet Engine Version", servletContext.getMajorVersion() + "." + servletContext.getMinorVersion()); addRow(debuggingPrinter, "JSP Version", jspFactory.getEngineInfo().getSpecificationVersion()); debuggingPrinter.endSection(); debuggingPrinter.addSection("JVM Properties"); for (Enumeration e = System.getProperties().propertyNames(); e.hasMoreElements();) { String parameterName = (String) e.nextElement(); addRow(debuggingPrinter, parameterName, debuggingPrinter.transform(System.getProperty(parameterName))); } debuggingPrinter.endSection(); debuggingPrinter.addSection("Environment"); for (Map.Entry<String, String> property : System.getenv().entrySet()) { addRow(debuggingPrinter, property.getKey(), debuggingPrinter.transform(property.getValue())); } debuggingPrinter.endSection(); debuggingPrinter.addSection("Debugger Provided by"); addRow(debuggingPrinter, "provided by", "raisercostin"); debuggingPrinter.addRow("source", "<a target='_blank' href='http://code.google.com/p/raisercostin/wiki/DebuggingFilter'>http://code.google.com/p/raisercostin/wiki/DebuggingFilter</a>"); addRow(debuggingPrinter, "version", "1.0"); addRow(debuggingPrinter, "timestamp", "2008.June.14"); addRow(debuggingPrinter, "license", "<a target='_blank' href='http://www.apache.org/licenses/LICENSE-2.0.html'>Apache License 2.0</a>"); debuggingPrinter.endSection(); } debuggingPrinter.addFooter(); return debuggingPrinter.getString(); }
From source file:com.iorga.webappwatcher.RequestLogFilter.java
@SuppressWarnings("unchecked") private RequestEventLog createRequestEventLog(final HttpServletRequest httpRequest, final String requestURI) { final RequestEventLog logRequest = EventLogManager.getInstance().addEventLog(RequestEventLog.class); logRequest.setRequestURI(requestURI); logRequest.setMethod(httpRequest.getMethod()); final Enumeration<String> parameterNames = httpRequest.getParameterNames(); final List<Parameter> parameters = new LinkedList<Parameter>(); while (parameterNames.hasMoreElements()) { final String parameterName = parameterNames.nextElement(); parameters.add(new Parameter(parameterName, httpRequest.getParameterValues(parameterName))); }//from w ww .j ava 2s . co m logRequest.setParameters(parameters.toArray(new Parameter[parameters.size()])); final Enumeration<String> headerNames = httpRequest.getHeaderNames(); final List<Header> headers = new LinkedList<Header>(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); headers.add(new Header(headerName, httpRequest.getHeader(headerName))); } logRequest.setHeaders(headers.toArray(new Header[headers.size()])); final Principal userPrincipal = httpRequest.getUserPrincipal(); if (userPrincipal != null) { logRequest.setPrincipal(userPrincipal.getName()); } final Thread currentThread = Thread.currentThread(); logRequest.setThreadName(currentThread.getName()); logRequest.setThreadId(currentThread.getId()); return logRequest; }
From source file:org.wso2.carbon.identity.sts.passive.ui.PassiveSTS.java
private void sendToAuthenticationFramework(HttpServletRequest request, HttpServletResponse response, String sessionDataKey, SessionDTO sessionDTO) throws IOException { String commonAuthURL = IdentityUtil.getServerURL(FrameworkConstants.COMMONAUTH); String selfPath = URLEncoder.encode("/" + FrameworkConstants.PASSIVE_STS, StandardCharsets.UTF_8.name()); //Authentication context keeps data which should be sent to commonAuth endpoint AuthenticationRequest authenticationRequest = new AuthenticationRequest(); authenticationRequest.setRelyingParty(sessionDTO.getRealm()); authenticationRequest.setCommonAuthCallerPath(selfPath); authenticationRequest.setForceAuth(false); authenticationRequest.setRequestQueryParams(request.getParameterMap()); //adding headers in out going request to authentication request context for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement().toString(); authenticationRequest.addHeader(headerName, request.getHeader(headerName)); }/* w w w. j av a 2 s.c om*/ //Add authenticationRequest cache entry to cache AuthenticationRequestCacheEntry authRequest = new AuthenticationRequestCacheEntry(authenticationRequest); FrameworkUtils.addAuthenticationRequestToCache(sessionDataKey, authRequest); StringBuilder queryStringBuilder = new StringBuilder(); queryStringBuilder.append("?").append(FrameworkConstants.SESSION_DATA_KEY).append("=") .append(sessionDataKey).append("&").append(FrameworkConstants.RequestParams.TYPE).append("=") .append(FrameworkConstants.PASSIVE_STS); response.sendRedirect(commonAuthURL + queryStringBuilder.toString()); }
From source file:com.funambol.transport.http.server.Sync4jServlet.java
/** * Extracts the request headers and returns them in a <i>Map</i> * * @param request the request/*from w w w . jav a 2 s .c o m*/ * @return the http headers */ private Map getRequestHeaders(HttpServletRequest request) { Map headers = new HashMap(); String headerName = null; for (Enumeration e = request.getHeaderNames(); e.hasMoreElements();) { headerName = (String) e.nextElement(); headers.put(headerName.toLowerCase(), request.getHeader(headerName)); } return headers; }
From source file:com.xpandit.fusionplugin.pentaho.content.FusionApi.java
/** * Parameter adapter. We use it so we're able to run the ParameterParser class without the IParameterProvider map given by the old Content Generator. * @param request HTTP Request with header and request parameters. * @param jsonStr JSON string obtained through POST calls. * @return A map with the IParameterProviders "request", "headers", "path". *//*w w w . ja va 2s . com*/ private Map<String, IParameterProvider> getParameterProviders(HttpServletRequest request, String jsonStr) { Map<String, IParameterProvider> parameterProviders = new HashMap<String, IParameterProvider>(); // Create request parameters SimpleParameterProvider requestParams = new SimpleParameterProvider(); Enumeration paramKeys = request.getParameterNames(); while (paramKeys.hasMoreElements()) { String key = (String) paramKeys.nextElement(); String value = request.getParameter(key); requestParams.setParameter(key, value); } // If there's a JSON string it should be put together with the request parameters so it can be correctly parsed if (jsonStr != null) { requestParams.setParameter("json", jsonStr); } // Create header parameters SimpleParameterProvider headerParams = new SimpleParameterProvider(); Enumeration names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); String value = request.getHeader(name); headerParams.setParameter(name, value); } // Populate IParameterProvider map parameterProviders.put(IParameterProvider.SCOPE_REQUEST, requestParams); parameterProviders.put("headers", headerParams); parameterProviders.put("path", new SimpleParameterProvider()); return parameterProviders; }
From source file:org.disit.servicemap.SparqlProxy.java
private void redirectToLog(HttpServletRequest theReq, HttpServletResponse theResp) throws Exception { HttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = null;/*from w w w . j a v a 2s . c o m*/ HttpResponse response = null; long startTime = System.nanoTime(); String theServerHost = Configuration.getInstance().get("sparqlEndpoint", null); if (theServerHost == null) theServerHost = "http://192.168.0.207:8890/sparql"; //String aEncodedQuery = URLEncoder.encode(query, "UTF-8"); //String serviceUri = theReq.getParameter("query"); String theReqUrl = theServerHost + "?"; String query = theReq.getParameter("query"); if (query != null) { String aEncodedQuery = URLEncoder.encode(query, "UTF-8"); theReqUrl += "query=" + aEncodedQuery; } String format = theReq.getParameter("format"); if (format != null) theReqUrl += "&format=" + format; try { httpget = new HttpGet(theReqUrl); //System.out.println("request header:"); Enumeration<String> aHeadersEnum = theReq.getHeaderNames(); while (aHeadersEnum.hasMoreElements()) { String aHeaderName = aHeadersEnum.nextElement(); String aHeaderVal = theReq.getHeader(aHeaderName); httpget.setHeader(aHeaderName, aHeaderVal); //System.out.println(" " + aHeaderName + ": " + aHeaderVal); } if (log.isDebugEnabled()) { log.debug("executing request " + httpget.getURI()); } // Create a response handler response = httpclient.execute(httpget); //System.out.println("response header:"); // set the same Headers for (Header aHeader : response.getAllHeaders()) { if (!aHeader.getName().equals("Transfer-Encoding") || !aHeader.getValue().equals("chunked")) { theResp.setHeader(aHeader.getName(), aHeader.getValue()); } //System.out.println(" " + aHeader.getName() + ": " + aHeader.getValue()); } // set the same locale if (response.getLocale() != null) { theResp.setLocale(response.getLocale()); } // set the content theResp.setContentLength((int) response.getEntity().getContentLength()); theResp.setContentType(response.getEntity().getContentType().getValue()); // set the same status theResp.setStatus(response.getStatusLine().getStatusCode()); // redirect the output InputStream aInStream = null; OutputStream aOutStream = null; try { aInStream = response.getEntity().getContent(); aOutStream = theResp.getOutputStream(); byte[] buffer = new byte[1024]; int r = 0; do { r = aInStream.read(buffer); if (r != -1) { aOutStream.write(buffer, 0, r); } } while (r != -1); /* int data = aInStream.read(); while (data != -1) { aOutStream.write(data); data = aInStream.read(); } */ } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (aInStream != null) { aInStream.close(); } if (aOutStream != null) { aOutStream.close(); } } } finally { httpclient.getConnectionManager().closeExpiredConnections(); httpclient.getConnectionManager().shutdown(); } ServiceMap.logQuery(query, "SPARQL", theReq.getRemoteAddr(), theReq.getHeader("User-Agent"), System.nanoTime() - startTime); }
From source file:com.portfolio.data.attachment.XSLService.java
HttpURLConnection CreateConnection(String url, HttpServletRequest request) throws MalformedURLException, IOException { /// Create connection URL urlConn = new URL(url); HttpURLConnection connection = (HttpURLConnection) urlConn.openConnection(); connection.setDoOutput(true);//w ww .j a v a 2 s .c om connection.setUseCaches(false); /// We don't want to cache data connection.setInstanceFollowRedirects(false); /// Let client follow any redirection String method = request.getMethod(); connection.setRequestMethod(method); String context = request.getContextPath(); connection.setRequestProperty("app", context); /// Transfer headers String key = ""; String value = ""; Enumeration<String> header = request.getHeaderNames(); while (header.hasMoreElements()) { key = header.nextElement(); value = request.getHeader(key); connection.setRequestProperty(key, value); } return connection; }
From source file:com.sun.socialsite.web.rest.servlets.ProxyServlet.java
/** * Handles the HTTP <code>POST</code> method. * @param req servlet request//ww w . j ava2 s.c o m * @param resp servlet response */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { URL url = getURL(req, req.getParameter("uri")); HttpURLConnection con = (HttpURLConnection) (url.openConnection()); con.setDoOutput(true); con.setAllowUserInteraction(false); con.setUseCaches(false); // TODO: figure out why this is necessary for HTTPS URLs if (con instanceof HttpsURLConnection) { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) { return true; } else { log.error("URL Host: " + urlHostName + " vs. " + session.getPeerHost()); return false; } } }; ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv); } // pass along all appropriate HTTP headers Enumeration headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String hname = (String) headerNames.nextElement(); if (!unproxiedHeaders.contains(hname.toLowerCase())) { con.addRequestProperty(hname, req.getHeader(hname)); } } con.connect(); // read POST data from incoming request, write to outgoing request BufferedInputStream in = new BufferedInputStream(req.getInputStream()); BufferedOutputStream out = new BufferedOutputStream(con.getOutputStream()); byte buffer[] = new byte[8192]; for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); // read result headers of POST, write to response Map<String, List<String>> headers = con.getHeaderFields(); for (String key : headers.keySet()) { if (key != null) { // TODO: why is this check necessary! List<String> header = headers.get(key); if (header.size() > 0) resp.setHeader(key, header.get(0)); } } // read result data of POST, write out to response in = new BufferedInputStream(con.getInputStream()); out = new BufferedOutputStream(resp.getOutputStream()); for (int count = 0; count != -1;) { count = in.read(buffer, 0, 8192); if (count != -1) out.write(buffer, 0, count); } in.close(); out.close(); out.flush(); con.disconnect(); }
From source file:com.netflix.genie.web.controllers.JobRestControllerUnitTests.java
/** * Make sure directory forwarding happens when all conditions are met. * * @throws IOException on error/*from www . j ava 2s. c o m*/ * @throws ServletException on error * @throws GenieException on error */ @Test public void canHandleForwardJobOutputRequestWithSuccess() throws IOException, ServletException, GenieException { this.jobsProperties.getForwarding().setEnabled(true); final String jobId = UUID.randomUUID().toString(); final String forwardedFrom = null; final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class); Mockito.doNothing().when(this.genieResourceHttpRequestHandler).handleRequest(request, response); final String jobHostName = UUID.randomUUID().toString(); Mockito.when(this.jobSearchService.getJobHost(jobId)).thenReturn(jobHostName); //Mock parts of the http request final String http = "http"; Mockito.when(request.getScheme()).thenReturn(http); final int port = 8080; Mockito.when(request.getServerPort()).thenReturn(port); final String requestURI = "/" + jobId + "/" + UUID.randomUUID().toString(); Mockito.when(request.getRequestURI()).thenReturn(requestURI); final Set<String> headerNames = Sets.newHashSet(HttpHeaders.ACCEPT); Mockito.when(request.getHeaderNames()).thenReturn(Collections.enumeration(headerNames)); Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.APPLICATION_JSON_VALUE); final String requestUrl = UUID.randomUUID().toString(); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl)); //Mock parts of forward response final HttpResponse forwardResponse = Mockito.mock(HttpResponse.class); final StatusLine statusLine = Mockito.mock(StatusLine.class); Mockito.when(forwardResponse.getStatusLine()).thenReturn(statusLine); final int successCode = 200; Mockito.when(statusLine.getStatusCode()).thenReturn(successCode); final Header contentTypeHeader = Mockito.mock(Header.class); Mockito.when(contentTypeHeader.getName()).thenReturn(HttpHeaders.CONTENT_TYPE); Mockito.when(contentTypeHeader.getValue()).thenReturn(MediaType.TEXT_PLAIN_VALUE); Mockito.when(forwardResponse.getAllHeaders()).thenReturn(new Header[] { contentTypeHeader }); final String text = UUID.randomUUID().toString() + UUID.randomUUID().toString() + UUID.randomUUID().toString(); final ByteArrayInputStream bis = new ByteArrayInputStream(text.getBytes(UTF_8)); final HttpEntity entity = Mockito.mock(HttpEntity.class); Mockito.when(entity.getContent()).thenReturn(bis); Mockito.when(forwardResponse.getEntity()).thenReturn(entity); final ByteArrayServletOutputStream bos = new ByteArrayServletOutputStream(); Mockito.when(response.getOutputStream()).thenReturn(bos); final ClientHttpRequestFactory factory = Mockito.mock(ClientHttpRequestFactory.class); final ClientHttpRequest clientHttpRequest = Mockito.mock(ClientHttpRequest.class); Mockito.when(clientHttpRequest.execute()) .thenReturn(new MockClientHttpResponse(text.getBytes(UTF_8), HttpStatus.OK)); Mockito.when(clientHttpRequest.getHeaders()).thenReturn(new HttpHeaders()); Mockito.when(factory.createRequest(Mockito.any(), Mockito.any())).thenReturn(clientHttpRequest); final RestTemplate template = new RestTemplate(factory); final Registry registry = Mockito.mock(Registry.class); final Counter counter = Mockito.mock(Counter.class); Mockito.when(registry.counter(Mockito.anyString())).thenReturn(counter); final JobRestController jobController = new JobRestController(Mockito.mock(JobCoordinatorService.class), this.jobSearchService, Mockito.mock(AttachmentService.class), Mockito.mock(ApplicationResourceAssembler.class), Mockito.mock(ClusterResourceAssembler.class), Mockito.mock(CommandResourceAssembler.class), Mockito.mock(JobResourceAssembler.class), Mockito.mock(JobRequestResourceAssembler.class), Mockito.mock(JobExecutionResourceAssembler.class), Mockito.mock(JobSearchResultResourceAssembler.class), this.hostname, template, this.genieResourceHttpRequestHandler, this.jobsProperties, registry); jobController.getJobOutput(jobId, forwardedFrom, request, response); Assert.assertThat(new String(bos.toByteArray(), UTF_8), Matchers.is(text)); Mockito.verify(request, Mockito.times(1)).getHeader(HttpHeaders.ACCEPT); Mockito.verify(this.jobSearchService, Mockito.times(1)).getJobHost(Mockito.eq(jobId)); Mockito.verify(response, Mockito.never()).sendError(Mockito.anyInt()); Mockito.verify(this.genieResourceHttpRequestHandler, Mockito.never()).handleRequest(request, response); }