Example usage for java.net HttpCookie HttpCookie

List of usage examples for java.net HttpCookie HttpCookie

Introduction

In this page you can find the example usage for java.net HttpCookie HttpCookie.

Prototype

public HttpCookie(String name, String value) 

Source Link

Document

Constructs a cookie with a specified name and value.

Usage

From source file:org.openhab.binding.amazonechocontrol.internal.WebSocketConnection.java

public WebSocketConnection(String amazonSite, List<HttpCookie> sessionCookies,
        IWebSocketCommandHandler webSocketCommandHandler) throws IOException {
    this.webSocketCommandHandler = webSocketCommandHandler;
    listener = new Listener();

    SslContextFactory sslContextFactory = new SslContextFactory();
    webSocketClient = new WebSocketClient(sslContextFactory);

    try {/*  ww  w  .  j a  v  a2  s  .co  m*/
        String host;
        if (StringUtils.equalsIgnoreCase(amazonSite, "amazon.com")) {
            host = "dp-gw-na-js." + amazonSite;
        } else {
            host = "dp-gw-na." + amazonSite;
        }

        String deviceSerial = "";
        List<HttpCookie> cookiesForWs = new ArrayList<HttpCookie>();
        for (HttpCookie cookie : sessionCookies) {
            if (cookie.getName().equals("ubid-acbde")) {
                deviceSerial = cookie.getValue();
            }
            // Clone the cookie without the security attribute, because the web socket implementation ignore secure
            // cookies
            String value = cookie.getValue().replaceAll("^\"|\"$", "");
            HttpCookie cookieForWs = new HttpCookie(cookie.getName(), value);
            cookiesForWs.add(cookieForWs);
        }
        deviceSerial += "-" + new Date().getTime();
        URI uri;

        uri = new URI(
                "wss://" + host + "/?x-amz-device-type=ALEGCNGL9K0HM&x-amz-device-serial=" + deviceSerial);

        try {
            webSocketClient.start();
        } catch (Exception e) {
            logger.warn("Web socket start failed: {}", e);
            throw new IOException("Web socket start failed");
        }

        ClientUpgradeRequest request = new ClientUpgradeRequest();
        request.setHeader("host", host);
        request.setHeader("Cache-Control", "no-cache");
        request.setHeader("Pragma", "no-cache");
        request.setHeader("Origin", "alexa." + amazonSite);

        request.setCookies(cookiesForWs);

        initPongTimeoutTimer();
        webSocketClient.connect(listener, uri, request);

    } catch (URISyntaxException e) {
        logger.debug("Initialize web socket failed: {}", e);
    }
}

From source file:interactivespaces.service.web.server.internal.netty.NettyHttpRequest.java

public static HttpCookie convertFromNettyCookie(Cookie cookie) {
    HttpCookie httpCookie = new HttpCookie(cookie.getName(), cookie.getValue());
    httpCookie.setComment(cookie.getComment());
    httpCookie.setDomain(cookie.getDomain());
    httpCookie.setMaxAge(cookie.getMaxAge());
    httpCookie.setPath(cookie.getPath());
    httpCookie.setPortlist(createPortString(cookie.getPorts()));
    httpCookie.setVersion(cookie.getVersion());
    httpCookie.setSecure(cookie.isSecure());
    httpCookie.setDiscard(cookie.isDiscard());

    return httpCookie;
}

From source file:org.apache.zeppelin.notebook.repo.zeppelinhub.websocket.ZeppelinhubClient.java

private ClientUpgradeRequest setConnectionrequest(String token) {
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    request.setCookies(Lists.newArrayList(new HttpCookie(ZeppelinHubRepo.TOKEN_HEADER, token)));
    return request;
}

From source file:org.wso2.carbon.appmgt.usage.publisher.APPMgtGoogleAnalayticsHandler.java

private String findCookie(String cookieString, String cookieName) {
    String[] rawCookies = null;//ww w  .ja va2  s  .  com
    if (cookieString != null) {
        rawCookies = cookieString.split(";");

        List<HttpCookie> cookies = new ArrayList<HttpCookie>();
        for (String cookie : rawCookies) {
            String[] split = cookie.split("=");
            if (split.length >= 2) {
                HttpCookie c = new HttpCookie(split[0].trim(), split[1].trim());
                cookies.add(c);
            }
        }

        for (HttpCookie cookie : cookies) {
            if (cookie.getName().equals(cookieName)) {
                return cookie.getValue();
            }
        }
    }

    return null;
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

/**
* 
*//*from  w w  w.j  a  va 2 s. com*/
@Override
public void setCookie(TankCookie cookie) {

    HttpCookie httpCookie = new HttpCookie(cookie.getName(), cookie.getValue());
    httpCookie.setDomain(cookie.getDomain());
    httpCookie.setPath(cookie.getPath());
    try {
        ((CookieManager) okHttpClient.getCookieHandler()).getCookieStore().add(null, httpCookie);
    } catch (Exception e) {
        LOG.error("Error setting cookie: " + e, e);
    }

}

From source file:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java

private HttpCookie toHttpCookie(Cookie cookie) {
    HttpCookie httpCookie = new HttpCookie(cookie.getName(), cookie.getValue());
    httpCookie.setComment(cookie.getComment());
    httpCookie.setDomain(cookie.getDomain());
    if (cookie.getExpiryDate() != null) {
        httpCookie.setMaxAge(cookie.getExpiryDate().getTime() / 1000);
    }/*from ww w  .  j a  v  a  2 s  . c o  m*/
    httpCookie.setPath(cookie.getPath());
    httpCookie.setSecure(cookie.isSecure());
    httpCookie.setVersion(cookie.getVersion());
    return httpCookie;
}

From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java

@Override
public synchronized Profile getCurrentProfile() {
    if (checkLogin()) {
        try {/*from  w  w  w  . j a v a2 s .c o m*/
            startHttpClient();

            // 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");

            if (mUseRemoteService) {
                request.cookie(new HttpCookie("ZBW_SESSID", mZWayRemoteSessionId));
            }

            ContentResponse response = request.send();

            // Check HTTP status code
            int statusCode = response.getStatus();
            if (statusCode != HttpStatus.OK_200) {
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getCurrentProfile();
                    }
                } else {
                    processResponseStatus(statusCode);
                }
            } else {
                String responseBody = response.getContentAsString();
                try {
                    Gson gson = new Gson();
                    // Response -> String -> Json -> extract data field
                    JsonObject profileAsJson = gson.fromJson(responseBody, JsonObject.class).get("data")
                            .getAsJsonObject(); // extract data field

                    return new ProfileListDeserializer().deserializeProfile(profileAsJson);
                } catch (JsonParseException e) {
                    logger.warn("Unexpected response format: {}", e.getMessage());
                    mCaller.responseFormatError("Unexpected response format: " + e.getMessage(), true);
                }
            }
        } catch (Exception e) {
            if (e.getCause() instanceof HttpResponseException) {
                int statusCode = ((HttpResponseException) e.getCause()).getResponse().getStatus();
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getCurrentProfile();
                    }
                }
            } else {
                handleException(e, "get current profile");
            }
        } finally {
            stopHttpClient();
        }
    } // no else ... checkLogin() method will invoke the appropriate callback method

    return null;
}

From source file:org.openhab.binding.amazonechocontrol.internal.Connection.java

private @Nullable Date tryRestoreSessionData(@Nullable String data, @Nullable String overloadedDomain) {
    // verify store data
    if (StringUtils.isEmpty(data)) {
        return null;
    }/*  ww  w  .j  av a 2s. c om*/
    Scanner scanner = new Scanner(data);
    String version = scanner.nextLine();
    // check if serialize version
    if (!version.equals("5") && !version.equals("6")) {
        scanner.close();
        return null;
    }
    int intVersion = Integer.parseInt(version);

    frc = scanner.nextLine();
    serial = scanner.nextLine();
    deviceId = scanner.nextLine();

    // Recreate session and cookies
    refreshToken = scanner.nextLine();
    String domain = scanner.nextLine();
    if (overloadedDomain != null) {
        domain = overloadedDomain;
    }
    setAmazonSite(domain);

    deviceName = scanner.nextLine();

    if (intVersion > 5) {
        String accountCustomerId = scanner.nextLine();
        if (!StringUtils.equals(accountCustomerId, "null")) {
            this.accountCustomerId = accountCustomerId;
        }
    }

    Date loginTime = new Date(Long.parseLong(scanner.nextLine()));
    CookieStore cookieStore = cookieManager.getCookieStore();
    cookieStore.removeAll();

    Integer numberOfCookies = Integer.parseInt(scanner.nextLine());
    for (Integer i = 0; i < numberOfCookies; i++) {
        String name = readValue(scanner);
        String value = readValue(scanner);

        HttpCookie clientCookie = new HttpCookie(name, value);
        clientCookie.setComment(readValue(scanner));
        clientCookie.setCommentURL(readValue(scanner));
        clientCookie.setDomain(readValue(scanner));
        clientCookie.setMaxAge(Long.parseLong(readValue(scanner)));
        clientCookie.setPath(readValue(scanner));
        clientCookie.setPortlist(readValue(scanner));
        clientCookie.setVersion(Integer.parseInt(readValue(scanner)));
        clientCookie.setSecure(Boolean.parseBoolean(readValue(scanner)));
        clientCookie.setDiscard(Boolean.parseBoolean(readValue(scanner)));

        cookieStore.add(null, clientCookie);
    }
    scanner.close();
    try {
        checkRenewSession();

        if (StringUtils.isEmpty(this.accountCustomerId)) {
            List<Device> devices = this.getDeviceList();
            for (Device device : devices) {
                if (StringUtils.equals(device.serialNumber, this.serial)) {
                    this.accountCustomerId = device.deviceOwnerCustomerId;
                    break;
                }
            }
            if (StringUtils.isEmpty(this.accountCustomerId)) {
                for (Device device : devices) {
                    if (StringUtils.equals(device.accountName, "This Device")) {
                        this.accountCustomerId = device.deviceOwnerCustomerId;
                        String serial = device.serialNumber;
                        if (serial != null) {
                            this.serial = serial;
                        }
                        break;
                    }
                }
            }
        }
    } catch (URISyntaxException | IOException | ConnectionException e) {
        logger.debug("Getting account customer Id failed {}", e);
    }
    return loginTime;
}

From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java

@Override
public synchronized SystemInfo getSystemInfo() {
    if (checkLogin()) {
        try {/*w  ww  .  j ava 2  s. c o m*/
            startHttpClient();

            Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_SYSTEM_INFO)
                    .method(HttpMethod.GET).header(HttpHeader.ACCEPT, "application/json")
                    .header(HttpHeader.CONTENT_TYPE, "application/json")
                    .cookie(new HttpCookie("ZWAYSession", mZWaySessionId));

            if (mUseRemoteService) {
                request.cookie(new HttpCookie("ZBW_SESSID", mZWayRemoteSessionId));
            }

            ContentResponse response = request.send();

            // Check HTTP status code
            int statusCode = response.getStatus();
            if (statusCode != HttpStatus.OK_200) {
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getSystemInfo();
                    }
                } else {
                    processResponseStatus(statusCode);
                }
            } else {
                String responseBody = response.getContentAsString();
                try {
                    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").create();
                    // Response -> String -> Json -> extract data field
                    JsonObject systemInfoAsJson = gson.fromJson(responseBody, JsonObject.class).get("data")
                            .getAsJsonObject(); // extract data field

                    return gson.fromJson(systemInfoAsJson, SystemInfo.class);
                } catch (JsonParseException e) {
                    logger.warn("Unexpected response format: {}", e.getMessage());
                    mCaller.responseFormatError("Unexpected response format: " + e.getMessage(), true);
                }
            }
        } catch (Exception e) {
            if (e.getCause() instanceof HttpResponseException) {
                int statusCode = ((HttpResponseException) e.getCause()).getResponse().getStatus();
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        return getSystemInfo();
                    }
                }
            } else {
                handleException(e, "get system info");
            }
        } finally {
            stopHttpClient();
        }
    } // no else ... checkLogin() method will invoke the appropriate callback method

    return null;
}

From source file:de.fh_zwickau.informatik.sensor.ZWayApiHttp.java

@Override
public void getSystemInfo(final IZWayCallback<SystemInfo> callback) {
    if (checkLogin()) {
        try {//from   w  w w . j a v  a  2 s.c om
            startHttpClient();

            Request request = mHttpClient.newRequest(getZAutomationTopLevelUrl() + "/" + PATH_SYSTEM_INFO)
                    .method(HttpMethod.GET).header(HttpHeader.ACCEPT, "application/json")
                    .header(HttpHeader.CONTENT_TYPE, "application/json")
                    .cookie(new HttpCookie("ZWAYSession", mZWaySessionId))
                    .onRequestFailure(new ZWayFailureListener());

            if (mUseRemoteService) {
                request.cookie(new HttpCookie("ZBW_SESSID", mZWayRemoteSessionId));
            }

            request.send(new BufferingResponseListener() {
                @Override
                public void onComplete(Result result) {
                    int statusCode = result.getResponse().getStatus();
                    if (statusCode != HttpStatus.OK_200) {
                        if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                            if (getLogin() == null) {
                                mCaller.authenticationError();
                            } else {
                                getSystemInfo(callback);
                            }
                        } else {
                            processResponseStatus(statusCode);
                        }
                    } else {
                        String responseBody = getContentAsString();
                        try {
                            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
                                    .create();
                            // Response -> String -> Json -> extract data field
                            JsonObject systemInfoAsJson = gson.fromJson(responseBody, JsonObject.class)
                                    .get("data").getAsJsonObject(); // extract data field

                            callback.onSuccess(gson.fromJson(systemInfoAsJson, SystemInfo.class));
                        } catch (JsonParseException e) {
                            logger.warn("Unexpected response format: {}", e.getMessage());
                            mCaller.responseFormatError("Unexpected response format: " + e.getMessage(), true);
                        }
                    }
                }
            });
        } catch (Exception e) {
            if (e.getCause() instanceof HttpResponseException) {
                int statusCode = ((HttpResponseException) e.getCause()).getResponse().getStatus();
                // Authentication error - retry login and operation
                if (statusCode == HttpStatus.UNAUTHORIZED_401) {
                    if (getLogin() == null) {
                        mCaller.authenticationError();
                    } else {
                        getSystemInfo(callback);
                    }
                }
            } else {
                handleException(e, "get system info");
            }
        } finally {
            // do not stop http client for asynchronous call
        }
    } // no else ... checkLogin() method will invoke the appropriate callback method
}