List of usage examples for java.net URL getQuery
public String getQuery()
From source file:org.hyperledger.fabric_ca.sdk.HFCAClient.java
/** * HFCAClient constructor/*from w w w. j a v a 2s.c o m*/ * * @param url Http URL for the Fabric's certificate authority services endpoint * @param properties PEM used for SSL .. not implemented. * <p> * Supported properties * <ul> * <li>pemFile - File location for x509 pem certificate for SSL.</li> * <li>allowAllHostNames - boolen(true/false) override certificates CN Host matching -- for development only.</li> * </ul> * @throws MalformedURLException */ HFCAClient(String caName, String url, Properties properties) throws MalformedURLException { logger.debug(format("new HFCAClient %s", url)); this.url = url; this.caName = caName; //name may be null URL purl = new URL(url); final String proto = purl.getProtocol(); if (!"http".equals(proto) && !"https".equals(proto)) { throw new IllegalArgumentException("HFCAClient only supports http or https not " + proto); } final String host = purl.getHost(); if (Utils.isNullOrEmpty(host)) { throw new IllegalArgumentException("HFCAClient url needs host"); } final String path = purl.getPath(); if (!Utils.isNullOrEmpty(path)) { throw new IllegalArgumentException( "HFCAClient url does not support path portion in url remove path: '" + path + "'."); } final String query = purl.getQuery(); if (!Utils.isNullOrEmpty(query)) { throw new IllegalArgumentException( "HFCAClient url does not support query portion in url remove query: '" + query + "'."); } isSSL = "https".equals(proto); if (properties != null) { this.properties = (Properties) properties.clone(); //keep our own copy. } else { this.properties = null; } }
From source file:com.couchbase.lite.router.Router.java
/** * Router+Handlers/* w w w. ja v a 2 s. c o m*/ */ private void setResponseLocation(URL url) { String location = url.getPath(); String query = url.getQuery(); if (query != null) { int startOfQuery = location.indexOf(query); if (startOfQuery > 0) { location = location.substring(0, startOfQuery); } } connection.getResHeader().add("Location", location); }
From source file:com.wavemaker.tools.ws.WebServiceToolsManager.java
/** * Generates the REST settings using the given request URL. This method will make a HTTP GET call using the request * URL and by using the XML response, it will then try to generate the REST settings. * // ww w. j a v a2 s.com * @param endpointAddress The actual request URL. * @param method Request method (GET, POST) * @param contentType Mime content type * @param postData post data * @return * @throws WebServiceException * @throws IOException * @throws XmlException */ public RESTWsdlSettings generateRESTWsdlSettings(String endpointAddress, String method, String contentType, String postData, boolean basicAuth, String userName, String password, Map<String, String> headers) throws WebServiceException, IOException, XmlException { RESTWsdlSettings settings = new RESTWsdlSettings(); URL serviceUrl = new URL(endpointAddress); serviceUrl.getHost(); String serviceName = constructServiceName(serviceUrl); QName serviceQName = new QName(constructNamespace(endpointAddress), serviceName); // TODO: For now, we only support the xml contenty type. It should be // extended to cover other content // TODO: types such as text/plain. String cType = contentType + "; charset=UTF-8"; DataSource postSource = HTTPBindingSupport.createDataSource(cType, postData); BindingProperties bp = null; if (basicAuth) { bp = new BindingProperties(); bp.setHttpBasicAuthUsername(userName); bp.setHttpBasicAuthPassword(password); } Map<String, Object> headerParams = new HashMap<String, Object>(); Set<Entry<String, String>> entries = headers.entrySet(); for (Map.Entry<String, String> entry : entries) { headerParams.put(entry.getKey(), entry.getValue()); } String responseString = HTTPBindingSupport.getResponseString(serviceQName, serviceQName, endpointAddress, HTTPRequestMethod.valueOf(method), postSource, bp, headerParams); String outputType = null; String xmlSchemaText = null; try { xmlSchemaText = convertXmlToSchema(responseString); outputType = getXmlRootElementType(responseString); } catch (Exception e) { // can't generate schema, so just set the output type to raw string outputType = "string"; } String query = serviceUrl.getQuery(); List<RESTInputParam> inputs = new ArrayList<RESTInputParam>(); String parameterizedUrl = null; if (query != null) { StringBuilder sb = new StringBuilder(); sb.append(getUrlOmitQuery(endpointAddress)); sb.append("?"); String[] qparts = query.split("&"); for (String qpart : qparts) { int i = qpart.indexOf('='); if (i > -1) { String name = qpart.substring(0, i); sb.append(name); sb.append("={"); sb.append(name); sb.append("}&"); inputs.add(new RESTInputParam(name, "string")); } else { sb.append(qpart); sb.append("&"); } } if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '&') { sb.deleteCharAt(sb.length() - 1); } parameterizedUrl = sb.toString(); } else { parameterizedUrl = endpointAddress; } Set<Entry<String, String>> headerEntries = headers.entrySet(); for (Map.Entry<String, String> entry : headerEntries) { inputs.add(new RESTInputParam(entry.getKey(), RESTInputParam.InputType.STRING, RESTInputParam.InputLocation.HEADER)); } settings.setServiceName(serviceName); settings.setOperationName("invoke"); settings.setInputs(inputs); settings.setParameterizedUrl(parameterizedUrl); settings.setOutputType(outputType); settings.setXmlSchemaText(xmlSchemaText); return settings; }
From source file:org.wso2.carbon.wsdl2form.WSDL2FormGenerator.java
/** * This method should be used if the mocking service is an internal service. If the service is * an external one, use {@code getExternalMockit} method * * @param result Result object containing the generated form * @param configCtx ConfigurationContext of the tenant. In standalone mode, this should be * main ConfigurationContext. * @param mockitWSDL URL of the service that need to be tried out. * @param serviceName Name of the service when multiple services are available in the WSDL. If * {@code serviceName} is {@code null}, then the fist service in the WSDL * will be used.//w w w . j a v a 2s. c o m * @param operationName Operation of the service that need to be tried out. If this is {@code * null}, all operations will be available. * @param taskID Task ID value to be sent along with form submission. * @param proxyUrl Proxy url where the form response will be posted. * @param fullPage set {@code true} if you want to get a full html page. {@code false} will * create a div. * * @return URL for the mocked service. * @throws CarbonException Throws when an error occurred during the execution */ public String getInternalMockit(Result result, ConfigurationContext configCtx, String mockitWSDL, String serviceName, String operationName, String taskID, String proxyUrl, boolean fullPage) throws CarbonException { try { URL url = new URL(mockitWSDL); String serviceContextRoot = configCtx.getServiceContextPath(); if (!serviceContextRoot.endsWith("/")) { serviceContextRoot = serviceContextRoot + "/"; } AxisService axisService = getAxisService(mockitWSDL, serviceContextRoot, configCtx); if (axisService != null) { if (axisService.isActive()) { // This is a fix for Mashup-861. If the transport is disabled we redirect the user to // the alternative transport if (!axisService.isEnableAllTransports() && !axisService.isExposedTransport(url.getProtocol())) { String redirectURL; if (ServerConstants.HTTP_TRANSPORT.equals(url.getProtocol()) && axisService.isExposedTransport(ServerConstants.HTTPS_TRANSPORT)) { TransportInDescription httpsTransport = configCtx.getAxisConfiguration() .getTransportIn(ServerConstants.HTTPS_TRANSPORT); Parameter parameter = httpsTransport.getParameter("proxyPort"); String port = ""; if (parameter != null && !"-1".equals(parameter.getValue())) { String value = (String) parameter.getValue(); if (!"443".equals(value)) { port = ":" + value; } } else { port = ":" + CarbonUtils.getTransportPort(configCtx, ServerConstants.HTTPS_TRANSPORT); } redirectURL = ServerConstants.HTTPS_TRANSPORT + "://" + url.getHost() + ":" + port + url.getPath() + "?" + url.getQuery(); return redirectURL; } else if (ServerConstants.HTTPS_TRANSPORT.equals(url.getProtocol()) && axisService.isExposedTransport(ServerConstants.HTTP_TRANSPORT)) { TransportInDescription httpsTransport = configCtx.getAxisConfiguration() .getTransportIn(ServerConstants.HTTP_TRANSPORT); Parameter parameter = httpsTransport.getParameter("proxyPort"); String port = ""; if (parameter != null && !"-1".equals(parameter.getValue())) { String value = (String) parameter.getValue(); if (!"80".equals(value)) { port = ":" + value; } } else { port = ":" + CarbonUtils.getTransportPort(configCtx, ServerConstants.HTTP_TRANSPORT); } redirectURL = ServerConstants.HTTPS_TRANSPORT + "://" + url.getHost() + ":" + port + url.getPath() + "?" + url.getQuery(); return redirectURL; } } Map<String, String> paramMap = new HashMap<String, String>(); DOMSource xmlSource = Util.getSigStream(axisService, null); paramMap.put("image-path", "?wsdl2form&type=image&resource="); paramMap.put("show-alternate", "false"); paramMap.put("fixendpoints", "true"); paramMap.put("task-id", taskID); paramMap.put("proxyAddress", proxyUrl); if (serviceName != null && !serviceName.equals("")) { paramMap.put("service", serviceName); } if (operationName != null && !operationName.equals("")) { paramMap.put("operation", operationName); } if (fullPage) { paramMap.put("full-page", "true"); } Util.generateMockit(xmlSource, result, paramMap); return WSDL2FormGenerator.SUCCESS; } else { throw new CarbonException(WSDL2FormGenerator.SERVICE_INACTIVE); } } else { throw new CarbonException(WSDL2FormGenerator.SERVICE_NOT_FOUND); } } catch (MalformedURLException e) { log.error(e.getMessage(), e); throw new CarbonException(e); } catch (OMException e) { log.error(e.getMessage(), e); throw new CarbonException(e); } catch (ParserConfigurationException e) { log.error(e.getMessage(), e); throw new CarbonException(e); } catch (TransformerException e) { log.error(e.getMessage(), e); throw new CarbonException(e); } catch (AxisFault e) { log.error(e.getMessage(), e); throw new CarbonException(e); } }
From source file:com.amalto.workbench.utils.Util.java
private static URL checkAndAddSuffix(URL url) { String protocol = url.getProtocol(); if (protocol.equals("http") || protocol.equals("https")) {//$NON-NLS-1$ //$NON-NLS-2$ String suffix = "wsdl"; //$NON-NLS-1$ if (!suffix.equalsIgnoreCase(url.getQuery())) { try { url = new URL(url.toString() + "?wsdl"); //$NON-NLS-1$ } catch (MalformedURLException e) { log.error(e.getMessage(), e); }//from w w w. j a va 2 s.c om } } return url; }
From source file:lucee.runtime.tag.Http.java
private void _doEndTag() throws PageException, IOException { long start = System.nanoTime(); HttpClientBuilder builder = HTTPEngine4Impl.getHttpClientBuilder(); ssl(builder);/*from w w w .jav a 2 s.c om*/ // redirect if (redirect) builder.setRedirectStrategy(new DefaultRedirectStrategy()); else builder.disableRedirectHandling(); // cookies BasicCookieStore cookieStore = new BasicCookieStore(); builder.setDefaultCookieStore(cookieStore); ConfigWeb cw = pageContext.getConfig(); HttpRequestBase req = null; HttpContext httpContext = null; CacheHandler cacheHandler = null; String cacheId = null; // HttpRequestBase req = init(pageContext.getConfig(),this,client,params,url,port); { if (StringUtil.isEmpty(charset, true)) charset = ((PageContextImpl) pageContext).getWebCharset().name(); else charset = charset.trim(); // check if has fileUploads boolean doUploadFile = false; for (int i = 0; i < this.params.size(); i++) { if ((this.params.get(i)).getType() == HttpParamBean.TYPE_FILE) { doUploadFile = true; break; } } // parse url (also query string) int len = this.params.size(); StringBuilder sbQS = new StringBuilder(); for (int i = 0; i < len; i++) { HttpParamBean param = this.params.get(i); int type = param.getType(); // URL if (type == HttpParamBean.TYPE_URL) { if (sbQS.length() > 0) sbQS.append('&'); sbQS.append(param.getEncoded() ? urlenc(param.getName(), charset) : param.getName()); sbQS.append('='); sbQS.append(param.getEncoded() ? urlenc(param.getValueAsString(), charset) : param.getValueAsString()); } } String host = null; HttpHost httpHost; try { URL _url = HTTPUtil.toURL(url, port, encoded); httpHost = new HttpHost(_url.getHost(), _url.getPort()); host = _url.getHost(); url = _url.toExternalForm(); if (sbQS.length() > 0) { // no existing QS if (StringUtil.isEmpty(_url.getQuery())) { url += "?" + sbQS; } else { url += "&" + sbQS; } } } catch (MalformedURLException mue) { throw Caster.toPageException(mue); } // cache if (cachedWithin != null) { cacheId = createCacheId(); cacheHandler = pageContext.getConfig().getCacheHandlerCollection(Config.CACHE_TYPE_HTTP, null) .getInstanceMatchingObject(cachedWithin, null); if (cacheHandler instanceof CacheHandlerPro) { CacheItem cacheItem = ((CacheHandlerPro) cacheHandler).get(pageContext, cacheId, cachedWithin); if (cacheItem instanceof HTTPCacheItem) { pageContext.setVariable(result, ((HTTPCacheItem) cacheItem).getData()); return; } } else if (cacheHandler != null) { // TODO this else block can be removed when all cache handlers implement CacheHandlerPro CacheItem cacheItem = cacheHandler.get(pageContext, cacheId); if (cacheItem instanceof HTTPCacheItem) { pageContext.setVariable(result, ((HTTPCacheItem) cacheItem).getData()); return; } } } // cache not found, process and cache result if needed // select best matching method (get,post, post multpart (file)) boolean isBinary = false; boolean doMultiPart = doUploadFile || this.multiPart; HttpEntityEnclosingRequest eeReqPost = null; HttpEntityEnclosingRequest eeReq = null; if (this.method == METHOD_GET) { req = new HttpGetWithBody(url); eeReq = (HttpEntityEnclosingRequest) req; } else if (this.method == METHOD_HEAD) { req = new HttpHead(url); } else if (this.method == METHOD_DELETE) { isBinary = true; req = new HttpDeleteWithBody(url); eeReq = (HttpEntityEnclosingRequest) req; } else if (this.method == METHOD_PUT) { isBinary = true; HttpPut put = new HttpPut(url); eeReqPost = put; req = put; eeReq = put; } else if (this.method == METHOD_TRACE) { isBinary = true; req = new HttpTrace(url); } else if (this.method == METHOD_OPTIONS) { isBinary = true; req = new HttpOptions(url); } else if (this.method == METHOD_PATCH) { isBinary = true; eeReq = HTTPPatchFactory.getHTTPPatch(url); req = (HttpRequestBase) eeReq; } else { isBinary = true; eeReqPost = new HttpPost(url); req = (HttpPost) eeReqPost; eeReq = eeReqPost; } boolean hasForm = false; boolean hasBody = false; boolean hasContentType = false; // Set http params ArrayList<FormBodyPart> parts = new ArrayList<FormBodyPart>(); StringBuilder acceptEncoding = new StringBuilder(); java.util.List<NameValuePair> postParam = eeReqPost != null ? new ArrayList<NameValuePair>() : null; for (int i = 0; i < len; i++) { HttpParamBean param = this.params.get(i); int type = param.getType(); // URL if (type == HttpParamBean.TYPE_URL) { // listQS.add(new BasicNameValuePair(translateEncoding(param.getName(), http.charset),translateEncoding(param.getValueAsString(), // http.charset))); } // Form else if (type == HttpParamBean.TYPE_FORM) { hasForm = true; if (this.method == METHOD_GET) throw new ApplicationException( "httpparam with type formfield can only be used when the method attribute of the parent http tag is set to post"); if (eeReqPost != null) { if (doMultiPart) { parts.add(new FormBodyPart(param.getName(), new StringBody(param.getValueAsString(), CharsetUtil.toCharset(charset)))); } else { postParam.add(new BasicNameValuePair(param.getName(), param.getValueAsString())); } } // else if(multi!=null)multi.addParameter(param.getName(),param.getValueAsString()); } // CGI else if (type == HttpParamBean.TYPE_CGI) { if (param.getEncoded()) req.addHeader(urlenc(param.getName(), charset), urlenc(param.getValueAsString(), charset)); else req.addHeader(param.getName(), param.getValueAsString()); } // Header else if (type == HttpParamBean.TYPE_HEADER) { if (param.getName().equalsIgnoreCase("content-type")) hasContentType = true; if (param.getName().equalsIgnoreCase("Content-Length")) { } else if (param.getName().equalsIgnoreCase("Accept-Encoding")) { acceptEncoding.append(headerValue(param.getValueAsString())); acceptEncoding.append(", "); } else req.addHeader(param.getName(), headerValue(param.getValueAsString())); } // Cookie else if (type == HttpParamBean.TYPE_COOKIE) { HTTPEngine4Impl.addCookie(cookieStore, host, param.getName(), param.getValueAsString(), "/", charset); } // File else if (type == HttpParamBean.TYPE_FILE) { hasForm = true; if (this.method == METHOD_GET) throw new ApplicationException( "httpparam type file can't only be used, when method of the tag http equal post"); // if(param.getFile()==null) throw new ApplicationException("httpparam type file can't only be used, when method of the tag http equal // post"); String strCT = getContentType(param); ContentType ct = HTTPUtil.toContentType(strCT, null); String mt = "text/xml"; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); if (doMultiPart) { try { Resource res = param.getFile(); parts.add(new FormBodyPart(param.getName(), new ResourceBody(res, mt, res.getName(), cs))); // parts.add(new ResourcePart(param.getName(),new ResourcePartSource(param.getFile()),getContentType(param),_charset)); } catch (FileNotFoundException e) { throw new ApplicationException("can't upload file, path is invalid", e.getMessage()); } } } // XML else if (type == HttpParamBean.TYPE_XML) { ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null); String mt = "text/xml"; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); hasBody = true; hasContentType = true; req.addHeader("Content-type", mt + "; charset=" + cs); if (eeReq == null) throw new ApplicationException( "type xml is only supported for methods get, delete, post, and put"); HTTPEngine4Impl.setBody(eeReq, param.getValueAsString(), mt, cs); } // Body else if (type == HttpParamBean.TYPE_BODY) { ContentType ct = HTTPUtil.toContentType(param.getMimeType(), null); String mt = null; if (ct != null && !StringUtil.isEmpty(ct.getMimeType(), true)) mt = ct.getMimeType(); String cs = charset; if (ct != null && !StringUtil.isEmpty(ct.getCharset(), true)) cs = ct.getCharset(); hasBody = true; if (eeReq == null) throw new ApplicationException( "type body is only supported for methods get, delete, post, and put"); HTTPEngine4Impl.setBody(eeReq, param.getValue(), mt, cs); } else { throw new ApplicationException("invalid type [" + type + "]"); } } // post params if (postParam != null && postParam.size() > 0) eeReqPost.setEntity(new org.apache.http.client.entity.UrlEncodedFormEntity(postParam, charset)); if (compression) { acceptEncoding.append("gzip"); } else { acceptEncoding.append("deflate;q=0"); req.setHeader("TE", "deflate;q=0"); } req.setHeader("Accept-Encoding", acceptEncoding.toString()); // multipart if (doMultiPart && eeReq != null) { hasContentType = true; boolean doIt = true; if (!this.multiPart && parts.size() == 1) { ContentBody body = parts.get(0).getBody(); if (body instanceof StringBody) { StringBody sb = (StringBody) body; try { org.apache.http.entity.ContentType ct = org.apache.http.entity.ContentType .create(sb.getMimeType(), sb.getCharset()); String str = IOUtil.toString(sb.getReader()); StringEntity entity = new StringEntity(str, ct); eeReq.setEntity(entity); } catch (IOException e) { throw Caster.toPageException(e); } doIt = false; } } if (doIt) { MultipartEntityBuilder mpeBuilder = MultipartEntityBuilder.create().setStrictMode(); // enabling the line below will append charset=... to the Content-Type header // if (!StringUtil.isEmpty(charset, true)) // mpeBuilder.setCharset(CharsetUtil.toCharset(charset)); Iterator<FormBodyPart> it = parts.iterator(); while (it.hasNext()) { FormBodyPart part = it.next(); mpeBuilder.addPart(part); } eeReq.setEntity(mpeBuilder.build()); } // eem.setRequestEntity(new MultipartRequestEntityFlex(parts.toArray(new Part[parts.size()]), eem.getParams(),http.multiPartType)); } if (hasBody && hasForm) throw new ApplicationException("mixing httpparam type file/formfield and body/XML is not allowed"); if (!hasContentType) { if (isBinary) { if (hasBody) req.addHeader("Content-type", "application/octet-stream"); else req.addHeader("Content-type", "application/x-www-form-urlencoded; charset=" + charset); } else { if (hasBody) req.addHeader("Content-type", "text/html; charset=" + charset); } } // set User Agent if (!hasHeaderIgnoreCase(req, "User-Agent")) req.setHeader("User-Agent", this.useragent); // set timeout setTimeout(builder, checkRemainingTimeout()); // set Username and Password if (this.username != null) { if (this.password == null) this.password = ""; if (AUTH_TYPE_NTLM == this.authType) { if (StringUtil.isEmpty(this.workStation, true)) throw new ApplicationException( "attribute workstation is required when authentication type is [NTLM]"); if (StringUtil.isEmpty(this.domain, true)) throw new ApplicationException( "attribute domain is required when authentication type is [NTLM]"); HTTPEngine4Impl.setNTCredentials(builder, this.username, this.password, this.workStation, this.domain); } else httpContext = HTTPEngine4Impl.setCredentials(builder, httpHost, this.username, this.password, preauth); } // set Proxy ProxyData proxy = null; if (!StringUtil.isEmpty(this.proxyserver)) { proxy = ProxyDataImpl.getInstance(this.proxyserver, this.proxyport, this.proxyuser, this.proxypassword); } if (pageContext.getConfig().isProxyEnableFor(host)) { proxy = pageContext.getConfig().getProxyData(); } HTTPEngine4Impl.setProxy(builder, req, proxy); } CloseableHttpClient client = null; try { if (httpContext == null) httpContext = new BasicHttpContext(); Struct cfhttp = new StructImpl(); cfhttp.setEL(ERROR_DETAIL, ""); pageContext.setVariable(result, cfhttp); /////////////////////////////////////////// EXECUTE ///////////////////////////////////////////////// client = builder.build(); Executor4 e = new Executor4(pageContext, this, client, httpContext, req, redirect); HTTPResponse4Impl rsp = null; if (timeout == null || timeout.getMillis() <= 0) { try { rsp = e.execute(httpContext); } catch (Throwable t) { ExceptionUtil.rethrowIfNecessary(t); if (!throwonerror) { if (t instanceof SocketTimeoutException) setRequestTimeout(cfhttp); else setUnknownHost(cfhttp, t); return; } throw toPageException(t, rsp); } } else { e.start(); try { synchronized (this) {// print.err(timeout); this.wait(timeout.getMillis()); } } catch (InterruptedException ie) { throw Caster.toPageException(ie); } if (e.t != null) { if (!throwonerror) { setUnknownHost(cfhttp, e.t); return; } throw toPageException(e.t, rsp); } rsp = e.response; if (!e.done) { req.abort(); if (throwonerror) throw new HTTPException("408 Request Time-out", "a timeout occurred in tag http", 408, "Time-out", rsp == null ? null : rsp.getURL()); setRequestTimeout(cfhttp); return; // throw new ApplicationException("timeout"); } } /////////////////////////////////////////// EXECUTE ///////////////////////////////////////////////// Charset responseCharset = CharsetUtil.toCharset(rsp.getCharset()); int statCode = 0; // Write Response Scope // String rawHeader=httpMethod.getStatusLine().toString(); String mimetype = null; String contentEncoding = null; // status code cfhttp.set(STATUSCODE, ((rsp.getStatusCode() + " " + rsp.getStatusText()).trim())); cfhttp.set(STATUS_CODE, new Double(statCode = rsp.getStatusCode())); cfhttp.set(STATUS_TEXT, (rsp.getStatusText())); cfhttp.set(HTTP_VERSION, (rsp.getProtocolVersion())); // responseHeader lucee.commons.net.http.Header[] headers = rsp.getAllHeaders(); StringBuffer raw = new StringBuffer(rsp.getStatusLine() + " "); Struct responseHeader = new StructImpl(); Struct cookie; Array setCookie = new ArrayImpl(); Query cookies = new QueryImpl( new String[] { "name", "value", "path", "domain", "expires", "secure", "httpOnly" }, 0, "cookies"); for (int i = 0; i < headers.length; i++) { lucee.commons.net.http.Header header = headers[i]; // print.ln(header); raw.append(header.toString() + " "); if (header.getName().equalsIgnoreCase("Set-Cookie")) { setCookie.append(header.getValue()); parseCookie(cookies, header.getValue()); } else { // print.ln(header.getName()+"-"+header.getValue()); Object value = responseHeader.get(KeyImpl.getInstance(header.getName()), null); if (value == null) responseHeader.set(KeyImpl.getInstance(header.getName()), header.getValue()); else { Array arr = null; if (value instanceof Array) { arr = (Array) value; } else { arr = new ArrayImpl(); responseHeader.set(KeyImpl.getInstance(header.getName()), arr); arr.appendEL(value); } arr.appendEL(header.getValue()); } } // Content-Type if (header.getName().equalsIgnoreCase("Content-Type")) { mimetype = header.getValue(); if (mimetype == null) mimetype = NO_MIMETYPE; } // Content-Encoding if (header.getName().equalsIgnoreCase("Content-Encoding")) { contentEncoding = header.getValue(); } } cfhttp.set(RESPONSEHEADER, responseHeader); cfhttp.set(KeyConstants._cookies, cookies); responseHeader.set(STATUS_CODE, new Double(statCode = rsp.getStatusCode())); responseHeader.set(EXPLANATION, (rsp.getStatusText())); if (setCookie.size() > 0) responseHeader.set(SET_COOKIE, setCookie); // is text boolean isText = mimetype == null || mimetype == NO_MIMETYPE || HTTPUtil.isTextMimeType(mimetype); // is multipart boolean isMultipart = MultiPartResponseUtils.isMultipart(mimetype); cfhttp.set(KeyConstants._text, Caster.toBoolean(isText)); // mimetype charset // boolean responseProvideCharset=false; if (!StringUtil.isEmpty(mimetype, true)) { if (isText) { String[] types = HTTPUtil.splitMimeTypeAndCharset(mimetype, null); if (types[0] != null) cfhttp.set(KeyConstants._mimetype, types[0]); if (types[1] != null) cfhttp.set(CHARSET, types[1]); } else cfhttp.set(KeyConstants._mimetype, mimetype); } else cfhttp.set(KeyConstants._mimetype, NO_MIMETYPE); // File Resource file = null; if (strFile != null && strPath != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strPath).getRealResource(strFile); } else if (strFile != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strFile); } else if (strPath != null) { file = ResourceUtil.toResourceNotExisting(pageContext, strPath); // Resource dir = file.getParentResource(); if (file.isDirectory()) { file = file.getRealResource(req.getURI().getPath());// TODO was getName() // ->http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/URI.html#getName() } } if (file != null) pageContext.getConfig().getSecurityManager().checkFileLocation(file); // filecontent InputStream is = null; if (isText && getAsBinary != GET_AS_BINARY_YES) { String str; try { // read content if (method != METHOD_HEAD) { is = rsp.getContentAsStream(); if (is != null && isGzipEncoded(contentEncoding)) is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is); } try { try { str = is == null ? "" : IOUtil.toString(is, responseCharset, checkRemainingTimeout().getMillis()); } catch (EOFException eof) { if (is instanceof CachingGZIPInputStream) { str = IOUtil.toString(is = ((CachingGZIPInputStream) is).getRawData(), responseCharset, checkRemainingTimeout().getMillis()); } else throw eof; } } catch (UnsupportedEncodingException uee) { str = IOUtil.toString(is, (Charset) null, checkRemainingTimeout().getMillis()); } } catch (IOException ioe) { throw Caster.toPageException(ioe); } finally { IOUtil.closeEL(is); } if (str == null) str = ""; if (resolveurl) { // if(e.redirectURL!=null)url=e.redirectURL.toExternalForm(); str = new URLResolver().transform(str, e.response.getTargetURL(), false); } cfhttp.set(KeyConstants._filecontent, str); try { if (file != null) { IOUtil.write(file, str, ((PageContextImpl) pageContext).getWebCharset(), false); } } catch (IOException e1) { } if (name != null) { Query qry = CSVParser.toQuery(str, delimiter, textqualifier, columns, firstrowasheaders); pageContext.setVariable(name, qry); } } // Binary else { byte[] barr = null; if (isGzipEncoded(contentEncoding)) { if (method != METHOD_HEAD) { is = rsp.getContentAsStream(); is = rsp.getStatusCode() != 200 ? new CachingGZIPInputStream(is) : new GZIPInputStream(is); } try { try { barr = is == null ? new byte[0] : IOUtil.toBytes(is); } catch (EOFException eof) { if (is instanceof CachingGZIPInputStream) barr = IOUtil.toBytes(((CachingGZIPInputStream) is).getRawData()); else throw eof; } } catch (IOException t) { throw Caster.toPageException(t); } finally { IOUtil.closeEL(is); } } else { try { if (method != METHOD_HEAD) barr = rsp.getContentAsByteArray(); else barr = new byte[0]; } catch (IOException t) { throw Caster.toPageException(t); } } // IF Multipart response get file content and parse parts if (barr != null) { if (isMultipart) { cfhttp.set(KeyConstants._filecontent, MultiPartResponseUtils.getParts(barr, mimetype)); } else { cfhttp.set(KeyConstants._filecontent, barr); } } else cfhttp.set(KeyConstants._filecontent, ""); if (file != null) { try { if (barr != null) IOUtil.copy(new ByteArrayInputStream(barr), file, true); } catch (IOException ioe) { throw Caster.toPageException(ioe); } } } // header cfhttp.set(KeyConstants._header, raw.toString()); if (!isStatusOK(rsp.getStatusCode())) { String msg = rsp.getStatusCode() + " " + rsp.getStatusText(); cfhttp.setEL(ERROR_DETAIL, msg); if (throwonerror) { throw new HTTPException(msg, null, rsp.getStatusCode(), rsp.getStatusText(), rsp.getURL()); } } // TODO: check if we can use statCode instead of rsp.getStatusCode() everywhere and cleanup the code if (cacheHandler != null && rsp.getStatusCode() == 200) { // add to cache cacheHandler.set(pageContext, cacheId, cachedWithin, new HTTPCacheItem(cfhttp, url, System.nanoTime() - start)); } } finally { if (client != null) client.close(); } }
From source file:io.hummer.util.ws.AbstractNode.java
@SuppressWarnings("all") public static void deploy(final Object service, String url, Handler<?>... handler) throws AbstractNodeException { long t1 = System.currentTimeMillis(); try {// w w w .j a v a 2 s . co m URL u = new URL(url); if (strUtil.isEmpty(System.getProperty(SYSPROP_HTTP_SERVER_PROVIDER_CLASS))) { System.setProperty(SYSPROP_HTTP_SERVER_PROVIDER_CLASS, JettyHttpServerProvider.class.getName()); } ContextHandlerCollection chc = new ContextHandlerCollection(); // disable log output from Metro and Jetty java.util.logging.Logger.getAnonymousLogger().getParent().setLevel(Level.WARNING); Class<?> cls3 = org.eclipse.jetty.server.Server.class; Class<?> cls4 = org.eclipse.jetty.server.AbstractConnector.class; org.apache.log4j.Level lev3 = Logger.getLogger(cls3).getLevel(); org.apache.log4j.Level lev4 = Logger.getLogger(cls4).getLevel(); Logger.getLogger(cls3).setLevel(org.apache.log4j.Level.WARN); Logger.getLogger(cls4).setLevel(org.apache.log4j.Level.WARN); JettyHttpServer httpServer = httpServers.get(u.getPort()); Server server = servers.get(u.getPort()); if (httpServer == null) { org.eclipse.jetty.util.log.Log.setLog(new Slf4jLog()); server = new Server(u.getPort()); SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(u.getPort()); connector.setAcceptQueueSize(1000); connector.setThreadPool(new ExecutorThreadPool(GlobalThreadPool.getExecutorService())); server.setConnectors(new Connector[] { connector }); server.setHandler(chc); httpServer = new JettyHttpServer(server, true); httpServers.put(u.getPort(), httpServer); servers.put(u.getPort(), server); if (!server.isStarted()) server.start(); } JettyHttpContext wsContext1 = (JettyHttpContext) httpServer.createContext(u.getPath()); Endpoint endpoint = Endpoint.create(service); if (service instanceof AbstractNode) { if (((AbstractNode) service).endpoint != null) logger.warn("AbstractNode " + service + " has apparently been double-deployed, " + "because there already exists an endpoint for this instance."); ((AbstractNode) service).endpoint = endpoint; } // add JAX-WS handlers (e.g., needed for TeCoS invocation intercepting...) List<Handler> handlers = endpoint.getBinding().getHandlerChain(); handlers.addAll(Arrays.asList(handler)); endpoint.getBinding().setHandlerChain(handlers); if (service instanceof AbstractNode) { AbstractNode a = (AbstractNode) service; for (Handler h : handlers) if (!a.activeHandlers.contains(h)) a.activeHandlers.add(h); } Class<?> cls1 = org.eclipse.jetty.util.component.AbstractLifeCycle.class; Class<?> cls2 = org.eclipse.jetty.server.handler.ContextHandler.class; org.apache.log4j.Level lev1 = Logger.getLogger(cls1).getLevel(); org.apache.log4j.Level lev2 = Logger.getLogger(cls2).getLevel(); try { String bindUrl = u.getProtocol() + "://0.0.0.0:" + u.getPort() + u.getPath(); if (u.getQuery() != null) { bindUrl += "?" + u.getQuery(); } Logger.getLogger(cls1).setLevel(org.apache.log4j.Level.OFF); Logger.getLogger(cls2).setLevel(org.apache.log4j.Level.WARN); logger.info("Binding service to " + bindUrl); endpoint.publish(bindUrl); } catch (Exception e) { if (e instanceof BindException || (e.getCause() != null && e.getCause() instanceof BindException) || (e.getCause() != null && e.getCause().getCause() != null && e.getCause().getCause() instanceof BindException)) { /** we expect a BindException here, just swallow */ } else { logger.warn("Unexpected error.", e); } } finally { Logger.getLogger(cls1).setLevel(lev1); Logger.getLogger(cls2).setLevel(lev2); Logger.getLogger(cls3).setLevel(lev3); Logger.getLogger(cls4).setLevel(lev4); } Field f = endpoint.getClass().getDeclaredField("actualEndpoint"); f.setAccessible(true); // DO NOT do this (the two lines below), because HttpEndpoint creates some nasty // compile-time dependencies with respect to JAXWS-RT. At runtime, we can (hopefully) // assume that this class is present, in all newer Sun JVM implementations.. //HttpEndpoint httpEndpoint = (HttpEndpoint)f.get(e1); //httpEndpoint.publish(wsContext1); Object httpEndpoint = f.get(endpoint); httpEndpoint.getClass().getMethod("publish", Object.class).invoke(httpEndpoint, wsContext1); Endpoint e2 = Endpoint.create(new CrossdomainXML()); JettyHttpContext wsContext2 = (JettyHttpContext) httpServer.createContext("/crossdomain.xml"); e2.publish(wsContext2); // Also deploy as RESTful service.. if (service instanceof AbstractNode) { AbstractNode node = (AbstractNode) service; if (node.isRESTfulService()) { String path = u.getPath(); if (!path.contains("/")) path = "/"; path = "/rest"; String wadlURL = netUtil.getUrlBeforePath(u) + path + "/application.wadl"; if (logger.isDebugEnabled()) logger.debug("Deploying node as RESTful service: " + wadlURL); JettyHttpContext wsContext3 = (JettyHttpContext) httpServer.createContext(path); ResourceConfig rc = new PackagesResourceConfig(service.getClass().getPackage().getName(), AbstractNode.class.getPackage().getName()); HttpHandler h = RuntimeDelegate.getInstance().createEndpoint(rc, HttpHandler.class); wsContext3.setHandler(h); node.setWadlURL(wadlURL); } deployedNodes.put(url, node); } final HttpHandler h = wsContext1.getHandler(); wsContext1.setHandler(new HttpHandler() { public void handle(com.sun.net.httpserver.HttpExchange ex) throws IOException { if (!ex.getRequestMethod().equals("OPTIONS")) { addCORSHeaders(ex); h.handle(ex); //System.out.println(ex.getRequestMethod() + ": " + ex.getResponseHeaders() + " - " + new HashMap<>(ex.getResponseHeaders())); return; } if (ex.getRequestMethod().equals("OPTIONS")) { addCORSHeaders(ex); ex.sendResponseHeaders(200, -1); ex.getResponseBody().close(); return; } //System.out.println(new HashMap<>(ex.getResponseHeaders())); } }); // add shutdown task for this node if (service instanceof AbstractNode) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { Runnable r = ((AbstractNode) service).getTerminateTask(null); if (r != null) r.run(); } catch (Exception e) { } } }); } } catch (Exception e) { throw new AbstractNodeException(e); } long diff = System.currentTimeMillis() - t1; logger.info("Deployment took " + diff + "ms"); }
From source file:com.atlassian.jira.webtests.JIRAWebTest.java
public String getRedirect() { URL url = getDialog().getResponse().getURL(); String queryString = url.getQuery() != null ? '?' + url.getQuery() : ""; return url.getPath() + queryString; }
From source file:org.wso2.carbon.http2.transport.util.Http2TargetRequestUtil.java
/** * Extracts necessary headers for http2 request * * @param msgContext/* w w w .j ava2 s .c om*/ * @return * @throws AxisFault */ public Http2Headers getHeaders(MessageContext msgContext) throws AxisFault { Http2Headers http2Headers = new DefaultHttp2Headers(); Map<String, String> reqeustHeaders = new TreeMap<>(); String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD); if (httpMethod == null) { httpMethod = "POST"; } reqeustHeaders.put(Http2Headers.PseudoHeaderName.METHOD.value().toString(), httpMethod); EndpointReference epr = PassThroughTransportUtils.getDestinationEPR(msgContext); String targetEPR = epr.getAddress(); if (targetEPR.toLowerCase().contains("http2://")) { targetEPR = targetEPR.replaceFirst("http2://", "http://"); } else if (targetEPR.toLowerCase().contains("https2://")) { targetEPR = targetEPR.replaceFirst("https2://", "https://"); } epr.setAddress(targetEPR); URL url = null; try { url = new URL(epr.getAddress()); } catch (MalformedURLException e) { throw new AxisFault("endpoint url parsing failed : ", e); } //this code block is needed to replace the host header in service chaining with REQUEST_HOST_HEADER //adding host header since it is not available in response message. //otherwise Host header will not replaced after first call if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) { Object headers = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); if (headers != null) { Map headersMap = (Map) headers; if (!headersMap.containsKey(HTTPConstants.HEADER_HOST)) { headersMap.put(HttpHeaderNames.HOST, msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER)); } } } // headers PassThroughTransportUtils.removeUnwantedHeaders(msgContext, configuration); Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); if (o != null && o instanceof Map) { Map headers = (Map) o; for (Object entryObj : headers.entrySet()) { Map.Entry entry = (Map.Entry) entryObj; if (entry.getValue() != null && entry.getKey() instanceof String && entry.getValue() instanceof String) { if (HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) entry.getKey()) && !configuration.isPreserveHttpHeader(HTTPConstants.HEADER_HOST)) { if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) { reqeustHeaders.put(((String) entry.getKey()).toLowerCase(), (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER)); } } else { if (!defaultHttp2Headers.contains(entry.getKey())) reqeustHeaders.put(((String) entry.getKey()).toLowerCase(), (String) entry.getValue()); else { String keyV = ":" + entry.getKey().toString().toLowerCase(); reqeustHeaders.put(keyV, (String) entry.getValue()); } } } } } String cType = null; try { cType = getContentType(msgContext, configuration.isPreserveHttpHeader(HTTP.CONTENT_TYPE)); } catch (AxisFault axisFault) { axisFault.printStackTrace(); } if (cType != null && (!httpMethod.equals("GET") && !httpMethod.equals("DELETE"))) { String messageType = (String) msgContext.getProperty("messageType"); if (messageType != null) { boolean builderInvoked = false; final Pipe pipe = (Pipe) msgContext.getProperty(PassThroughConstants.PASS_THROUGH_PIPE); if (pipe != null) { builderInvoked = Boolean.TRUE .equals(msgContext.getProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED)); } // if multipart related message type and unless if message // not get build we should // skip of setting formatter specific content Type if (messageType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED) == -1 && messageType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_FORM_DATA) == -1) { Map msgCtxheaders = (Map) o; if (msgCtxheaders != null && !cType.isEmpty()) { msgCtxheaders.put(HTTP.CONTENT_TYPE, cType); } reqeustHeaders.put(HttpHeaderNames.CONTENT_TYPE.toString(), cType); } // if messageType is related to multipart and if message // already built we need to set new // boundary related content type at Content-Type header if (builderInvoked && (((messageType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_RELATED) != -1) || (messageType.indexOf(HTTPConstants.MEDIA_TYPE_MULTIPART_FORM_DATA) != -1)))) { reqeustHeaders.put(HttpHeaderNames.CONTENT_TYPE.toString(), cType); } } else { reqeustHeaders.put(HttpHeaderNames.CONTENT_TYPE.toString(), cType); } } // version String forceHttp10 = (String) msgContext.getProperty(PassThroughConstants.FORCE_HTTP_1_0); if ("true".equals(forceHttp10)) { //request.setVersion(HttpVersion.HTTP_1_0); } // keep alive String noKeepAlie = (String) msgContext.getProperty(PassThroughConstants.NO_KEEPALIVE); if ("true".equals(noKeepAlie)) { keepAlive = false; } // port port = url.getPort(); // chunk String disableChunking = (String) msgContext.getProperty(PassThroughConstants.DISABLE_CHUNKING); if ("true".equals(disableChunking)) { disableChunk = true; } // full url String fullUr = (String) msgContext.getProperty(PassThroughConstants.FULL_URI); if ("true".equals(fullUr)) { fullUrl = true; } // Add excess respsonse header. String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS; Map excessHeaders = (Map) msgContext.getProperty(excessProp); if (excessHeaders != null) { for (Iterator iterator = excessHeaders.keySet().iterator(); iterator.hasNext();) { String key = (String) iterator.next(); for (String excessVal : (Collection<String>) excessHeaders.get(key)) { reqeustHeaders.put(key.toLowerCase(), (String) excessVal); } } } String path = fullUrl || (route.getProxyHost() != null && !route.isTunnelled()) ? url.toString() : url.getPath() + (url.getQuery() != null ? "?" + url.getQuery() : ""); if ((("GET").equals(msgContext.getProperty(Constants.Configuration.HTTP_METHOD))) || (("DELETE").equals(msgContext.getProperty(Constants.Configuration.HTTP_METHOD)))) { try { hasEntityBody = false; MessageFormatter formatter = MessageProcessorSelector.getMessageFormatter(msgContext); OMOutputFormat format = PassThroughTransportUtils.getOMOutputFormat(msgContext); if (formatter != null && format != null) { URL _url = formatter.getTargetAddress(msgContext, format, url); if (_url != null && !_url.toString().isEmpty()) { if (msgContext.getProperty(NhttpConstants.POST_TO_URI) != null && Boolean.TRUE.toString() .equals(msgContext.getProperty(NhttpConstants.POST_TO_URI))) { path = _url.toString(); } else { path = _url.getPath() + ((_url.getQuery() != null && !_url.getQuery().isEmpty()) ? ("?" + _url.getQuery()) : ""); } } if (reqeustHeaders.containsKey(HttpHeaderNames.CONTENT_TYPE)) reqeustHeaders.remove(HttpHeaderNames.CONTENT_TYPE); } } catch (Exception e) { e.printStackTrace(); } } //fix for POST_TO_URI if (msgContext.isPropertyTrue(NhttpConstants.POST_TO_URI)) { path = url.toString(); } if (path != null || !path.isEmpty()) { reqeustHeaders.put(Http2Headers.PseudoHeaderName.PATH.value().toString(), path); } if (hasEntityBody) { long contentLength = -1; String contentLengthHeader = null; if (reqeustHeaders.containsKey(HttpHeaderNames.CONTENT_LENGTH.toString()) && Integer.parseInt(reqeustHeaders.get(HttpHeaderNames.CONTENT_LENGTH).toString()) > 0) { contentLengthHeader = reqeustHeaders.get(HttpHeaderNames.CONTENT_LENGTH).toString(); } if (contentLengthHeader != null) { contentLength = Integer.parseInt(contentLengthHeader); reqeustHeaders.remove(HttpHeaderNames.CONTENT_LENGTH); } if (msgContext.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH) != null) { contentLength = (Long) msgContext.getProperty(PassThroughConstants.PASSTROUGH_MESSAGE_LENGTH); } boolean forceContentLength = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH); boolean forceContentLengthCopy = msgContext .isPropertyTrue(PassThroughConstants.COPY_CONTENT_LENGTH_FROM_INCOMING); if (forceContentLength) { if (forceContentLengthCopy && contentLength > 0) { reqeustHeaders.put(HttpHeaderNames.CONTENT_LENGTH.toString(), Long.toString(contentLength)); } } else { if (contentLength != -1) { reqeustHeaders.put(HttpHeaderNames.CONTENT_LENGTH.toString(), Long.toString(contentLength)); } } } String soapAction = msgContext.getSoapAction(); if (soapAction == null) { soapAction = msgContext.getWSAAction(); msgContext.getAxisOperation().getInputAction(); } if (msgContext.isSOAP11() && soapAction != null && soapAction.length() > 0) { String existingHeader = reqeustHeaders.get(HTTPConstants.HEADER_SOAP_ACTION).toString(); if (existingHeader != null) { reqeustHeaders.remove(existingHeader); } MessageFormatter messageFormatter = MessageFormatterDecoratorFactory .createMessageFormatterDecorator(msgContext); reqeustHeaders.put(HTTPConstants.HEADER_SOAP_ACTION.toLowerCase(), messageFormatter.formatSOAPAction(msgContext, null, soapAction)); request.setHeader(HTTPConstants.USER_AGENT.toLowerCase(), "Synapse-PT-HttpComponents-NIO"); } if (reqeustHeaders.containsKey(HttpHeaderNames.HOST)) { reqeustHeaders.remove(HttpHeaderNames.HOST); } if (reqeustHeaders.containsKey(Http2Headers.PseudoHeaderName.SCHEME.value())) reqeustHeaders.remove(Http2Headers.PseudoHeaderName.SCHEME.value()); reqeustHeaders.put(Http2Headers.PseudoHeaderName.SCHEME.value().toString(), route.getTargetHost().getSchemeName()); if (reqeustHeaders.containsKey(Http2Headers.PseudoHeaderName.AUTHORITY.value())) reqeustHeaders.remove(Http2Headers.PseudoHeaderName.AUTHORITY.value()); reqeustHeaders.put(Http2Headers.PseudoHeaderName.AUTHORITY.value().toString(), route.getTargetHost().toString()); Iterator<Map.Entry<String, String>> iterator = reqeustHeaders.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> head = iterator.next(); http2Headers.add(head.getKey(), head.getValue()); } return http2Headers; }