List of usage examples for java.net HttpCookie getValue
public String getValue()
From source file:com.tremolosecurity.proxy.filter.PostProcess.java
protected void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpResponse response, String finalURL, HttpFilterChain curChain, HttpRequestBase httpRequest) throws IOException, Exception { boolean isText; HttpEntity entity = null;/*from w ww .j av a 2s . c o m*/ try { entity = response.getEntity(); /*if (entity != null) { entity = new BufferedHttpEntity(entity); }*/ } catch (Throwable t) { throw new Exception(t); } InputStream ins = null; boolean entExists = false; if (entity == null) { resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); ins = new StringBufferInputStream(""); } else { try { ins = entity.getContent(); resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); entExists = true; } catch (IllegalStateException e) { //do nothing } } if (entExists) { org.apache.http.Header hdr = response.getFirstHeader("Content-Type"); org.apache.http.Header encoding = response.getFirstHeader("Content-Encoding"); /*if (hdr == null) { isText = false; } else { isText = response.getFirstHeader("Content-Type").getValue().startsWith("text"); if (encoding != null ) { isText = (! encoding.getValue().startsWith("gzip")) && (! encoding.getValue().startsWith("deflate")); } if (isText) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); resp.setLocale(response.getLocale()); } }*/ isText = false; try { resp.setCharacterEncoding(null); } catch (Throwable t) { //we're not doing anything } StringBuffer stmp = new StringBuffer(); if (response.getFirstHeader("Content-Type") != null) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); } if (response.getLocale() != null) { resp.setLocale(response.getLocale()); } org.apache.http.Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { org.apache.http.Header header = headers[i]; if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Length")) { if (!header.getValue().equals("0")) { continue; } } else if (header.getName().equals("Transfer-Encoding")) { continue; } else if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) { //System.out.println(header.getValue()); String cookieVal = header.getValue(); /*if (cookieVal.endsWith("HttpOnly")) { cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly")); } //System.out.println(cookieVal);*/ List<HttpCookie> cookies = HttpCookie.parse(cookieVal); Iterator<HttpCookie> it = cookies.iterator(); while (it.hasNext()) { HttpCookie cookie = it.next(); String cookieFinalName = cookie.getName(); if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) { stmp.setLength(0); stmp.append("JSESSIONID").append('-') .append(holder.getApp().getName().replaceAll(" ", "|")); cookieFinalName = stmp.toString(); } Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue()); respcookie.setComment(cookie.getComment()); if (cookie.getDomain() != null) { respcookie.setDomain(cookie.getDomain()); } if (cookie.hasExpired()) { respcookie.setMaxAge(0); } else { respcookie.setMaxAge((int) cookie.getMaxAge()); } respcookie.setPath(cookie.getPath()); respcookie.setSecure(cookie.getSecure()); respcookie.setVersion(cookie.getVersion()); resp.addCookie(respcookie); } } else if (header.getName().equals("Location")) { if (holder.isOverrideHost()) { fixRedirect(req, resp, finalURL, header); } else { resp.addHeader("Location", header.getValue()); } } else { resp.addHeader(header.getName(), header.getValue()); } } curChain.setIns(ins); curChain.setText(isText); curChain.setEntity(entity); curChain.setHttpRequestBase(httpRequest); //procData(req, resp, holder, isText, entity, ins); } else { isText = false; } }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to * local path and renames cookie to avoid collisions. *//*from w w w .j a v a 2 s .c om*/ protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String headerValue) { List<HttpCookie> cookies = HttpCookie.parse(headerValue); String path = servletRequest.getContextPath(); // path starts with / or // is empty string path += servletRequest.getServletPath(); // servlet path starts with / // or is empty string for (HttpCookie cookie : cookies) { // set cookie name prefixed w/ a proxy value so it won't collide w/ // other cookies String proxyCookieName = getCookieNamePrefix(cookie.getName()) + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); // set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:com.tremolosecurity.proxy.filters.PreAuthFilter.java
@Override public void doFilter(HttpFilterRequest request, HttpFilterResponse response, HttpFilterChain chain) throws Exception { AuthInfo userData = ((AuthController) request.getSession().getAttribute(ProxyConstants.AUTH_CTL)) .getAuthInfo();/* w ww.ja v a 2 s.c o m*/ ConfigManager cfg = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ); List<Cookie> cookies = null; if (userData.getAuthLevel() > 0 && userData.isAuthComplete()) { UrlHolder holder = (UrlHolder) request.getAttribute(ProxyConstants.AUTOIDM_CFG); HttpSession session = request.getSession(); String uid = (String) session.getAttribute("TREMOLO_PRE_AUTH"); if (uid == null || !uid.equals(userData.getUserDN())) { session.setAttribute("TREMOLO_PRE_AUTH", userData.getUserDN()); HashMap<String, String> uriParams = new HashMap<String, String>(); uriParams.put("fullURI", this.uri); UrlHolder remHolder = cfg.findURL(this.url); org.apache.http.client.methods.HttpRequestBase method = null; if (this.postSAML) { PrivateKey pk = holder.getConfig().getPrivateKey(this.keyAlias); java.security.cert.X509Certificate cert = holder.getConfig().getCertificate(this.keyAlias); Saml2Assertion assertion = new Saml2Assertion( userData.getAttribs().get(this.nameIDAttribute).getValues().get(0), pk, cert, null, this.issuer, this.assertionConsumerURL, this.audience, this.signAssertion, this.signResponse, false, this.nameIDType, this.authnCtxClassRef); String respXML = ""; try { respXML = assertion.generateSaml2Response(); } catch (Exception e) { throw new ServletException("Could not generate SAMLResponse", e); } List<NameValuePair> formparams = new ArrayList<NameValuePair>(); String base64 = Base64.encodeBase64String(respXML.getBytes("UTF-8")); formparams.add(new BasicNameValuePair("SAMLResponse", base64)); if (this.relayState != null && !this.relayState.isEmpty()) { formparams.add(new BasicNameValuePair("RelayState", this.relayState)); } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); HttpPost post = new HttpPost(this.assertionConsumerURL); post.setEntity(entity); method = post; } else { HttpGet get = new HttpGet(remHolder.getProxyURL(uriParams)); method = get; } LastMileUtil.addLastMile(cfg, userData.getAttribs().get(loginAttribute).getValues().get(0), this.loginAttribute, method, lastMileKeyAlias, true); BasicHttpClientConnectionManager bhcm = new BasicHttpClientConnectionManager( cfg.getHttpClientSocketRegistry()); try { CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(bhcm) .setDefaultRequestConfig(cfg.getGlobalHttpClientConfig()).build(); HttpResponse resp = httpclient.execute(method); if (resp.getStatusLine().getStatusCode() == 500) { BufferedReader in = new BufferedReader( new InputStreamReader(resp.getEntity().getContent())); StringBuffer error = new StringBuffer(); String line = null; while ((line = in.readLine()) != null) { error.append(line).append('\n'); } logger.warn("Pre-Auth Failed : " + error); } org.apache.http.Header[] headers = resp.getAllHeaders(); StringBuffer stmp = new StringBuffer(); cookies = new ArrayList<Cookie>(); for (org.apache.http.Header header : headers) { if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) { //System.out.println(header.getValue()); String cookieVal = header.getValue(); /*if (cookieVal.endsWith("HttpOnly")) { cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly")); } //System.out.println(cookieVal);*/ List<HttpCookie> cookiesx = HttpCookie.parse(cookieVal); for (HttpCookie cookie : cookiesx) { String cookieFinalName = cookie.getName(); if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) { stmp.setLength(0); stmp.append("JSESSIONID").append('-') .append(holder.getApp().getName().replaceAll(" ", "|")); cookieFinalName = stmp.toString(); } //logger.info("Adding cookie name '" + cookieFinalName + "'='" + cookie.getValue() + "'"); Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue()); respcookie.setComment(cookie.getComment()); if (cookie.getDomain() != null) { //respcookie.setDomain(cookie.getDomain()); } respcookie.setMaxAge((int) cookie.getMaxAge()); respcookie.setPath(cookie.getPath()); respcookie.setSecure(cookie.getSecure()); respcookie.setVersion(cookie.getVersion()); cookies.add(respcookie); if (request.getCookieNames().contains(respcookie.getName())) { request.removeCookie(cookieFinalName); } request.addCookie(new Cookie(cookie.getName(), cookie.getValue())); } } } } finally { bhcm.shutdown(); } } } chain.nextFilter(request, response, chain); if (cookies != null) { for (Cookie cookie : cookies) { response.addCookie(cookie); } } }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public String serializeLoginData() { Date loginTime = this.loginTime; if (refreshToken == null || loginTime == null) { return ""; }/*from w ww . j a v a2 s.c om*/ StringBuilder builder = new StringBuilder(); builder.append("6\n"); // version builder.append(frc); builder.append("\n"); builder.append(serial); builder.append("\n"); builder.append(deviceId); builder.append("\n"); builder.append(refreshToken); builder.append("\n"); builder.append(amazonSite); builder.append("\n"); builder.append(deviceName); builder.append("\n"); builder.append(accountCustomerId); builder.append("\n"); builder.append(loginTime.getTime()); builder.append("\n"); List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); builder.append(cookies.size()); builder.append("\n"); for (HttpCookie cookie : cookies) { writeValue(builder, cookie.getName()); writeValue(builder, cookie.getValue()); writeValue(builder, cookie.getComment()); writeValue(builder, cookie.getCommentURL()); writeValue(builder, cookie.getDomain()); writeValue(builder, cookie.getMaxAge()); writeValue(builder, cookie.getPath()); writeValue(builder, cookie.getPortlist()); writeValue(builder, cookie.getVersion()); writeValue(builder, cookie.getSecure()); writeValue(builder, cookie.getDiscard()); } return builder.toString(); }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public String registerConnectionAsApp(String oAutRedirectUrl) throws ConnectionException, IOException, URISyntaxException { URI oAutRedirectUri = new URI(oAutRedirectUrl); Map<String, String> queryParameters = new LinkedHashMap<String, String>(); String query = oAutRedirectUri.getQuery(); String[] pairs = query.split("&"); for (String pair : pairs) { int idx = pair.indexOf("="); queryParameters.put(URLDecoder.decode(pair.substring(0, idx), StandardCharsets.UTF_8.name()), URLDecoder.decode(pair.substring(idx + 1), StandardCharsets.UTF_8.name())); }/*w w w .j a v a2 s. c o m*/ String accessToken = queryParameters.get("openid.oa2.access_token"); Map<String, String> cookieMap = new HashMap<String, String>(); List<JsonWebSiteCookie> webSiteCookies = new ArrayList<JsonWebSiteCookie>(); for (HttpCookie cookie : getSessionCookies("https://www.amazon.com")) { cookieMap.put(cookie.getName(), cookie.getValue()); webSiteCookies.add(new JsonWebSiteCookie(cookie.getName(), cookie.getValue())); } JsonWebSiteCookie[] webSiteCookiesArray = new JsonWebSiteCookie[webSiteCookies.size()]; webSiteCookiesArray = webSiteCookies.toArray(webSiteCookiesArray); JsonRegisterAppRequest registerAppRequest = new JsonRegisterAppRequest(serial, accessToken, frc, webSiteCookiesArray); String registerAppRequestJson = gson.toJson(registerAppRequest); HashMap<String, String> registerHeaders = new HashMap<String, String>(); registerHeaders.put("x-amzn-identity-auth-domain", "api.amazon.com"); String registerAppResultJson = makeRequestAndReturnString("POST", "https://api.amazon.com/auth/register", registerAppRequestJson, true, registerHeaders); JsonRegisterAppResponse registerAppResponse = parseJson(registerAppResultJson, JsonRegisterAppResponse.class); Response response = registerAppResponse.response; if (response == null) { throw new ConnectionException("Error: No response received from register application"); } Success success = response.success; if (success == null) { throw new ConnectionException("Error: No success received from register application"); } Tokens tokens = success.tokens; if (tokens == null) { throw new ConnectionException("Error: No tokens received from register application"); } Bearer bearer = tokens.bearer; if (bearer == null) { throw new ConnectionException("Error: No bearer received from register application"); } this.refreshToken = bearer.refresh_token; if (StringUtils.isEmpty(this.refreshToken)) { throw new ConnectionException("Error: No refresh token received"); } String usersMeResponseJson = makeRequestAndReturnString("GET", "https://alexa.amazon.com/api/users/me?platform=ios&version=2.2.223830.0", null, false, null); JsonUsersMeResponse usersMeResponse = parseJson(usersMeResponseJson, JsonUsersMeResponse.class); URI uri = new URI(usersMeResponse.marketPlaceDomainName); String host = uri.getHost(); setAmazonSite(host); try { exhangeToken(); } catch (Exception e) { logout(); throw e; } String deviceName = null; Extensions extensions = success.extensions; if (extensions != null) { DeviceInfo deviceInfo = extensions.device_info; if (deviceInfo != null) { deviceName = deviceInfo.device_name; } } if (deviceName == null) { deviceName = "Unknown"; } this.deviceName = deviceName; return deviceName; }
From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java
public HttpsURLConnection makeRequest(String verb, String url, @Nullable String postData, boolean json, boolean autoredirect, @Nullable Map<String, String> customHeaders) throws IOException, URISyntaxException { String currentUrl = url;// ww w . ja v a2 s . c o m for (int i = 0; i < 30; i++) // loop for handling redirect, using automatic redirect is not possible, because // all response headers must be catched { int code; HttpsURLConnection connection = null; try { logger.debug("Make request to {}", url); connection = (HttpsURLConnection) new URL(currentUrl).openConnection(); connection.setRequestMethod(verb); connection.setRequestProperty("Accept-Language", "en-US"); if (customHeaders == null || !customHeaders.containsKey("User-Agent")) { connection.setRequestProperty("User-Agent", userAgent); } connection.setRequestProperty("Accept-Encoding", "gzip"); connection.setRequestProperty("DNT", "1"); connection.setRequestProperty("Upgrade-Insecure-Requests", "1"); if (customHeaders != null) { for (String key : customHeaders.keySet()) { String value = customHeaders.get(key); if (StringUtils.isNotEmpty(value)) { connection.setRequestProperty(key, value); } } } connection.setInstanceFollowRedirects(false); // add cookies URI uri = connection.getURL().toURI(); if (customHeaders == null || !customHeaders.containsKey("Cookie")) { StringBuilder cookieHeaderBuilder = new StringBuilder(); for (HttpCookie cookie : cookieManager.getCookieStore().get(uri)) { if (cookieHeaderBuilder.length() > 0) { cookieHeaderBuilder.append(";"); } cookieHeaderBuilder.append(cookie.getName()); cookieHeaderBuilder.append("="); cookieHeaderBuilder.append(cookie.getValue()); if (cookie.getName().equals("csrf")) { connection.setRequestProperty("csrf", cookie.getValue()); } } if (cookieHeaderBuilder.length() > 0) { String cookies = cookieHeaderBuilder.toString(); connection.setRequestProperty("Cookie", cookies); } } if (postData != null) { logger.debug("{}: {}", verb, postData); // post data byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8); int postDataLength = postDataBytes.length; connection.setFixedLengthStreamingMode(postDataLength); if (json) { connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); } else { connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } connection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); if (verb == "POST") { connection.setRequestProperty("Expect", "100-continue"); } connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(postDataBytes); outputStream.close(); } // handle result code = connection.getResponseCode(); String location = null; // handle response headers Map<String, List<String>> headerFields = connection.getHeaderFields(); for (Map.Entry<String, List<String>> header : headerFields.entrySet()) { String key = header.getKey(); if (StringUtils.isNotEmpty(key)) { if (key.equalsIgnoreCase("Set-Cookie")) { // store cookie for (String cookieHeader : header.getValue()) { if (StringUtils.isNotEmpty(cookieHeader)) { List<HttpCookie> cookies = HttpCookie.parse(cookieHeader); for (HttpCookie cookie : cookies) { cookieManager.getCookieStore().add(uri, cookie); } } } } if (key.equalsIgnoreCase("Location")) { // get redirect location location = header.getValue().get(0); if (StringUtils.isNotEmpty(location)) { location = uri.resolve(location).toString(); // check for https if (location.toLowerCase().startsWith("http://")) { // always use https location = "https://" + location.substring(7); logger.debug("Redirect corrected to {}", location); } } } } } if (code == 200) { logger.debug("Call to {} succeeded", url); return connection; } if (code == 302 && location != null) { logger.debug("Redirected to {}", location); currentUrl = location; if (autoredirect) { continue; } return connection; } } catch (IOException e) { if (connection != null) { connection.disconnect(); } logger.warn("Request to url '{}' fails with unkown error", url, e); throw e; } catch (Exception e) { if (connection != null) { connection.disconnect(); } throw e; } if (code != 200) { throw new HttpException(code, verb + " url '" + url + "' failed: " + connection.getResponseMessage()); } } throw new ConnectionException("Too many redirects"); }
From source file:com.web.server.WebServer.java
/** * This methos is the implementation of the HTPP request and sends the response. *//*from w w w . j a v a2s . c o m*/ public void run() { byte[] response; byte[] content; byte[] uploadData = null; HttpHeaderClient httpHeaderClient = null; InputStream istream = null; OutputStream ostream = null; HttpHeaderServer serverParam = new HttpHeaderServer(); StringBuffer buffer = new StringBuffer(); String value; char c; String endvalue = "\r\n\r\n"; String urlFormEncoded; int responseCode; try { ////System.out.println("value="); istream = socket.getInputStream(); BufferedInputStream bistr = new BufferedInputStream(istream); //socket.setReceiveBufferSize(10000); //System.out.println("value1="); int availbleStream; int totalBytRead = 0; int ch; ByteArrayOutputStream bytout = new ByteArrayOutputStream(); ByteArrayOutputStream contentout = new ByteArrayOutputStream(); //System.out.println(istream.available()); int bytesRead; int endbytIndex = 0; int contentbytIndex = 0; boolean httpHeaderEndFound = false; byte[] byt; while ((ch = bistr.read()) != -1) { bytout.write(ch); if (!httpHeaderEndFound && (char) ch == endvalue.charAt(endbytIndex)) { endbytIndex++; if (endbytIndex == endvalue.length()) { byt = bytout.toByteArray(); value = new String(ObtainBytes(byt, 0, byt.length - 4)); //System.out.println(value); httpHeaderClient = parseHttpHeaders(value); httpHeaderEndFound = true; bytout.close(); endbytIndex = 0; if (httpHeaderClient.getContentLength() == null) break; } } else { endbytIndex = 0; } if (httpHeaderClient != null && httpHeaderEndFound) { contentout.write(ch); contentbytIndex++; if (httpHeaderClient.getContentLength() != null && contentbytIndex >= Integer.parseInt(httpHeaderClient.getContentLength())) { break; } } totalBytRead++; } /*while(totalBytRead==0){ while((ch = bistr.read())!=-1){ System.out.println((char)ch); ////System.out.println("availableStream="+availbleStream); bytarrayOutput.write(ch); totalBytRead++; } }*/ if (totalBytRead == 0) { System.out.println("Since byte is 0 sock and istream os closed"); //istream.close(); socket.close(); return; } //istream.read(bt,0,9999999); System.out.println("bytes read"); byte[] contentByte = contentout.toByteArray(); contentout.close(); //System.out.println("String="+new String(bt)); /*int index=containbytes(bt,endvalue.getBytes()); if(index==-1)index=totalBytRead; value=new String(ObtainBytes(bt,0,index));*/ System.out.println("value2="); ConcurrentHashMap<String, HttpCookie> httpCookies = httpHeaderClient.getCookies(); HttpSessionServer session = null; if (httpCookies != null) { Iterator<String> cookieNames = httpCookies.keySet().iterator(); for (; cookieNames.hasNext();) { String cookieName = cookieNames.next(); //System.out.println(cookieName+" "+httpCookies.get(cookieName).getValue()); if (cookieName.equals("SERVERSESSIONID")) { session = (HttpSessionServer) sessionObjects.get(httpCookies.get(cookieName).getValue()); httpHeaderClient.setSession(session); //break; } } } //System.out.println("Session="+session); if (session == null) { HttpCookie cookie = new HttpCookie(); cookie.setKey("SERVERSESSIONID"); cookie.setValue(UUID.randomUUID().toString()); httpCookies.put("SERVERSESSIONID", cookie); session = new HttpSessionServer(); sessionObjects.put(cookie.getValue(), session); httpHeaderClient.setSession(session); } if (httpHeaderClient.getContentType() != null && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)) { ////System.out.println(new String(uploadData)); ConcurrentHashMap paramMap = new MultipartFormData().parseContent(contentByte, httpHeaderClient); httpHeaderClient.setParameters(paramMap); ////logger.info(uploadData); } else if (httpHeaderClient.getContentType() != null && httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)) { urlFormEncoded = new String(contentByte); ConcurrentHashMap paramMap = parseUrlEncoded(urlFormEncoded); httpHeaderClient.setParameters(paramMap); } ////logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain()); ////System.out.println("value3="); ////logger.info(new String(bt)); serverParam.setContentType("text/html"); URLDecoder decoder = new URLDecoder(); System.out.println("content Length= " + socket); responseCode = 200; File file = new File(deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain())); FileContent fileContent = (FileContent) cache.get(httpHeaderClient.getResourceToObtain()); if (fileContent != null && file.lastModified() == fileContent.getLastModified()) { System.out.println("In cache"); content = (byte[]) fileContent.getContent(); } else { content = ObtainContentExecutor(deployDirectory, httpHeaderClient.getResourceToObtain(), httpHeaderClient, serverdigester, urlClassLoaderMap, servletMapping, session); System.out.println("content Length2= " + content); if (content == null) { //System.out.println("In caching content"); content = obtainContent( deployDirectory + decoder.decode(httpHeaderClient.getResourceToObtain())); if (content != null) { fileContent = new FileContent(); fileContent.setContent(content); fileContent.setFileName(httpHeaderClient.getResourceToObtain()); fileContent.setLastModified(file.lastModified()); cache.put(httpHeaderClient.getResourceToObtain(), fileContent); } } ////System.out.println("value4="); } if (content == null) { responseCode = 404; content = ("<html><body><H1>The Request resource " + httpHeaderClient.resourceToObtain + " Not Found</H1><body></html>").getBytes(); } ////System.out.println("content Length3= "); serverParam.setContentLength("" + (content.length + 4)); if (httpHeaderClient.getResourceToObtain().endsWith(".ico")) { serverParam.setContentType("image/png"); } ////System.out.println("value5="); ////System.out.println("content Length4= "); response = formHttpResponseHeader(responseCode, serverParam, content, httpHeaderClient.getCookies()); ////System.out.println("value6="); ostream = socket.getOutputStream(); //logger.info("Response="+new String(response)); //System.out.println("value6="); //logger.info("Response="+new String(response)); ////System.out.println("content "+"Response="+new String(response)); ostream.write(response); ostream.flush(); ostream.close(); socket.close(); } catch (IOException e) { Socket socket; e.printStackTrace(); //logger.error(e); try { socket = new Socket("localhost", shutdownPort); OutputStream outputStream = socket.getOutputStream(); outputStream.write("shutdown WebServer\r\n\r\n".getBytes()); outputStream.close(); } catch (Exception ex) { ex.printStackTrace(); } e.printStackTrace(); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.web.server.WebServer.java
/** * This method forms the http response//w w w . j a v a 2s. c om * @param responseCode * @param httpHeader * @param content * @return */ private byte[] formHttpResponseHeader(int responseCode, HttpHeaderServer httpHeader, byte[] content, ConcurrentHashMap<String, HttpCookie> httpCookies) { StringBuffer buffer = new StringBuffer(); String colon = ": "; String crlf = "\r\n"; if (responseCode == 200) { buffer.append("HTTP/1.1 200 OK"); buffer.append(crlf); buffer.append(HttpHeaderServerParamNames.DATE); buffer.append(colon); buffer.append(httpHeader.getDate()); buffer.append(crlf); buffer.append(HttpHeaderServerParamNames.SERVER); buffer.append(colon); buffer.append(httpHeader.getServer()); buffer.append(crlf); buffer.append(HttpHeaderServerParamNames.CONTENT_TYPE); buffer.append(colon); buffer.append(httpHeader.getContentType()); buffer.append(crlf); buffer.append(HttpHeaderServerParamNames.CONTENT_LENGTH); buffer.append(colon); buffer.append(httpHeader.getContentLength()); buffer.append(crlf); buffer.append(HttpHeaderServerParamNames.LAST_MODIFIED); buffer.append(colon); buffer.append(httpHeader.getLastModified()); if (httpCookies != null) { Iterator<String> cookieNames = httpCookies.keySet().iterator(); HttpCookie httpCookie; for (; cookieNames.hasNext();) { String cookieName = cookieNames.next(); httpCookie = (HttpCookie) httpCookies.get(cookieName); buffer.append(crlf); buffer.append(HttpHeaderServerParamNames.SETCOOKIE); buffer.append(colon); buffer.append(httpCookie.getKey()); buffer.append("="); buffer.append(httpCookie.getValue()); if (httpCookie.getExpires() != null) { buffer.append("; "); buffer.append(HttpHeaderServerParamNames.SETCOOKIEEXPIRES); buffer.append("="); buffer.append(httpCookie.getExpires()); } } } } else if (responseCode == 404) { buffer.append("HTTP/1.1 404 Not Found"); } buffer.append(crlf); buffer.append(crlf); byte[] byt1 = buffer.toString().getBytes(); byte[] byt2 = new byte[byt1.length + content.length + crlf.length() * 2]; /////System.out.println("Header="+new String(byt1)); for (int count = 0; count < byt1.length; count++) { byt2[count] = byt1[count]; } for (int count = 0; count < content.length; count++) { byt2[count + byt1.length] = content[count]; } for (int count = 0; count < crlf.length() * 2; count++) { byt2[count + byt1.length + content.length] = (byte) crlf.charAt(count % 2); } ////System.out.println("Header with content="+new String(byt2)); /*try { buffer.append(new String(content, "UTF-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ return byt2; }
From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java
@Override public synchronized String getLogin() { try {//from ww w . j a v a2 s.c o m startHttpClient(); if (mUseRemoteService) { mZWaySessionId = null; mZWayRemoteSessionId = null; // Build request body String body = "act=login&login=" + mRemoteId + "/" + mUsername + "&pass=" + mPassword; logger.info("Remote login body: {}", body); logger.info("Remote path: {}", getTopLevelUrl() + "/" + REMOTE_PATH_LOGIN); Request request = mHttpClient.newRequest(getTopLevelUrl() + "/" + REMOTE_PATH_LOGIN) .method(HttpMethod.POST) .header(HttpHeader.CONTENT_TYPE, "application/x-www-form-urlencoded") .content(new StringContentProvider(body), "application/x-www-form-urlencoded"); ContentResponse response = request.send(); // Check HTTP status code int statusCode = response.getStatus(); if (statusCode != HttpStatus.OK_200) { String reason = response.getReason(); mCaller.httpStatusError(statusCode, reason, true); logger.debug("Communication with Z-Way server failed: {} {}", statusCode, reason); } CookieStore cookieStore = mHttpClient.getCookieStore(); List<HttpCookie> cookies = cookieStore.get(URI.create("https://find.z-wave.me/")); for (HttpCookie cookie : cookies) { if (cookie.getName().equals("ZWAYSession")) { mZWaySessionId = cookie.getValue(); } else if (cookie.getName().equals("ZBW_SESSID")) { mZWayRemoteSessionId = cookie.getValue(); } logger.info("HTTP cookie: {} - {}", cookie.getName(), cookie.getValue()); } if (mZWayRemoteSessionId != null && mZWaySessionId != null) { mCaller.getLoginResponse(mZWaySessionId); return mZWaySessionId; } else { logger.warn("Response doesn't contain required cookies"); mCaller.responseFormatError("Response doesn't contain required cookies", true); } } else { // Build request body LoginForm loginForm = new LoginForm(true, mUsername, mPassword, false, 1); Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_LOGIN) .method(HttpMethod.POST).header(HttpHeader.ACCEPT, "application/json") .header(HttpHeader.CONTENT_TYPE, "application/json") .content(new StringContentProvider(new Gson().toJson(loginForm)), "application/json"); ContentResponse response = request.send(); // Check HTTP status code int statusCode = response.getStatus(); if (statusCode != HttpStatus.OK_200) { String reason = response.getReason(); mCaller.httpStatusError(statusCode, reason, true); logger.debug("Communication with Z-Way server failed: {} {}", statusCode, reason); } String responseBody = response.getContentAsString(); try { Gson gson = new Gson(); // Response -> String -> Json -> extract data field JsonObject responseDataAsJson = gson.fromJson(responseBody, JsonObject.class).get("data") .getAsJsonObject(); // extract data field mZWaySessionId = responseDataAsJson.get("sid").getAsString(); // extract SID field mCaller.getLoginResponse(mZWaySessionId); return mZWaySessionId; } catch (JsonParseException e) { logger.warn("Unexpected response format: {}", e.getMessage()); mCaller.responseFormatError("Unexpected response format: " + e.getMessage(), true); } } } catch (Exception e) { logger.warn("Request getLogin() failed: {}", e.getMessage()); mCaller.apiError(e.getMessage(), true); } finally { stopHttpClient(); } mZWaySessionId = null; mZWayRemoteSessionId = null; mCaller.authenticationError(); return null; }