Example usage for java.net CookieHandler setDefault

List of usage examples for java.net CookieHandler setDefault

Introduction

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

Prototype

public static synchronized void setDefault(CookieHandler cHandler) 

Source Link

Document

Sets (or unsets) the system-wide cookie handler.

Usage

From source file:org.apache.jsp.fileUploader_jsp.java

private String UpdateToShare(byte[] bytes, String mimeType, String title, String description, String prevId,
        Set<String> communities, boolean isJson, String type, boolean newShare, HttpServletRequest request,
        HttpServletResponse response) {//from w  ww .  j  av a  2 s  . c  o m
    String charset = "UTF-8";
    String url = "";
    try {
        if (isJson) {
            //first check if bytes are actually json
            try {
                new JsonParser().parse(new String(bytes));
            } catch (Exception ex) {
                return "Failed, file was not valid JSON";
            }
            if (newShare)
                url = API_ROOT + "social/share/add/json/" + URLEncoder.encode(type, charset) + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
            else
                url = API_ROOT + "social/share/update/json/" + prevId + "/" + URLEncoder.encode(type, charset)
                        + "/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
        } else {
            if (newShare)
                url = API_ROOT + "social/share/add/binary/" + URLEncoder.encode(title, charset) + "/"
                        + URLEncoder.encode(description, charset) + "/";
            else
                url = API_ROOT + "social/share/update/binary/" + prevId + "/"
                        + URLEncoder.encode(title, charset) + "/" + URLEncoder.encode(description, charset)
                        + "/";
        }

        if (localCookie)
            CookieHandler.setDefault(cm);
        URLConnection connection = new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", charset);
        String cookieVal = getBrowserInfiniteCookie(request);
        if (cookieVal != null) {
            connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept-Charset", "UTF-8");
        }
        if (mimeType != null && mimeType.length() > 0)
            connection.setRequestProperty("Content-Type", mimeType + ";charset=" + charset);
        DataOutputStream output = new DataOutputStream(connection.getOutputStream());
        output.write(bytes);
        DataInputStream responseStream = new DataInputStream(connection.getInputStream());

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        while ((nRead = responseStream.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }

        String json = buffer.toString();
        String newCookie = getConnectionInfiniteCookie(connection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }
        buffer.flush();
        buffer.close();
        output.close();
        responseStream.close();

        if (isJson) {
            jsonResponse jr = new Gson().fromJson(json, jsonResponse.class);
            if (jr == null) {
                return "Failed: " + json;
            }
            if (jr.response.success == true) {
                if (jr.data != null && jr.data._id != null) {
                    addRemoveCommunities(jr.data._id, communities, request, response);
                    return jr.data._id; //When a new upload, mr.data contains the ShareID for the upload
                }
            }
            return "Upload Failed: " + jr.response.message;
        } else {
            modResponse mr = new Gson().fromJson(json, modResponse.class);
            if (mr == null) {
                return "Failed: " + json;
            }
            if (mr.response.success == true) {
                if (prevId != null && mr.data == null) {
                    addRemoveCommunities(prevId, communities, request, response);
                    return prevId;
                } else {
                    addRemoveCommunities(mr.data, communities, request, response);
                    return mr.data; //When a new upload, mr.data contains the ShareID for the upload
                }
            } else {
                return "Upload Failed: " + mr.response.message;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        return "Upload Failed: " + e.getMessage();
    }
}

From source file:edgeserver.Descoberta.java

private void publicaGateway(Gateway gateway) throws Exception {
    // make sure cookies is turn on
    CookieHandler.setDefault(new CookieManager());

    HTTPClient http = new HTTPClient();

    List<NameValuePair> postp = new ArrayList<>();
    postp.add(new BasicNameValuePair("login", "huberto"));
    postp.add(new BasicNameValuePair("password", "99766330"));

    http.sendPost(this.urlLogin, postp);

    List<NameValuePair> GatewayParams = new ArrayList<>();
    GatewayParams.add(new BasicNameValuePair("gateway_nome", gateway.getNome()));
    GatewayParams.add(new BasicNameValuePair("gateway_servidorborda", Integer.toString(this.ServidorBordaID)));
    GatewayParams.add(new BasicNameValuePair("gateway_uid", (String) gateway.getUid()));

    String result = http.GetPageContent(this.insertGatewayURI, GatewayParams);
    //System.out.println(result);

    String publicType = result.split(":")[0];
    String gatewayID = result.split(":")[1];

    gateway.setId(Integer.parseInt(gatewayID));

    if (null != publicType)
        switch (publicType) {
        case "insert":
            System.out.println("-> Gateway " + gateway.getNome() + "(" + gateway.getId()
                    + ") cadastrado no Servidor de Contexto com sucesso.");
            break;
        case "update":
            System.out.println("-> Gateway " + gateway.getNome() + "(" + gateway.getId()
                    + ") atualizado no Servidor de Contexto com sucesso.");
            toggleGateway(gateway, "activate");
            break;
        }//from   w  w w  . j ava 2 s .  co m
}

From source file:no.eris.applet.AppletViewer.java

private void overrideCookieHandler(CookieManager manager) {
    manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    final CookieHandler handler = CookieHandler.getDefault();

    LOGGER.debug("CookieStore: size {}", manager.getCookieStore().getCookies().size());
    if (cookies != null) {
        for (UriAndCookie uriAndCookie : cookies) {
            URI uri = uriAndCookie.getUri();
            HttpCookie cookie = uriAndCookie.getCookie();
            LOGGER.debug("Adding cookies: <{}> value={} secure={}",
                    new Object[] { uri, cookie, cookie.getSecure() });
            manager.getCookieStore().add(uri, cookie);
        }/*  w w w.  j a v  a2  s . c  o m*/
    }
    LOGGER.debug("CookieStore: size {}", manager.getCookieStore().getCookies().size());
    LOGGER.debug("Overriding cookie handler: {}", (handler == null ? null : handler.getClass().getName()));
    // FIXME because we depend on the system-wide cookie manager, we probably cannot run multiple applets at the time
    // we also maybe have some security issues lurking here...
    // I could maybe partition the callers based on the ThreadGroup ?? 
    // FIXME theres also some cleanup to do somewhere
    CookieHandler.setDefault(new LoggingCookieHandler(manager));
}

From source file:test.be.fedict.eid.applet.ControllerTest.java

@Test
public void controllerIdentification() throws Exception {
    // setup/*from   w  w  w  . j  a  v  a 2  s.co  m*/
    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    // make sure that the session cookies are passed during conversations
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    // operate
    controller.run();

    // verify
    LOG.debug("verify...");
    SessionHandler sessionHandler = this.servletTester.getContext().getSessionHandler();
    SessionManager sessionManager = sessionHandler.getSessionManager();
    LOG.debug("session manager type: " + sessionManager.getClass().getName());
    HashSessionManager hashSessionManager = (HashSessionManager) sessionManager;
    LOG.debug("# sessions: " + hashSessionManager.getSessions());
    assertEquals(1, hashSessionManager.getSessions());
    Map<String, HttpSession> sessionMap = hashSessionManager.getSessionMap();
    LOG.debug("session map: " + sessionMap);
    Entry<String, HttpSession> sessionEntry = sessionMap.entrySet().iterator().next();
    HttpSession httpSession = sessionEntry.getValue();
    assertNotNull(httpSession.getAttribute("eid"));
    Identity identity = (Identity) httpSession.getAttribute("eid.identity");
    assertNotNull(identity);
    assertNotNull(identity.name);
    LOG.debug("name: " + identity.name);
    LOG.debug("document type: " + identity.getDocumentType());
    LOG.debug("duplicate: " + identity.getDuplicate());
    assertNull(httpSession.getAttribute("eid.identifier"));
    assertNull(httpSession.getAttribute("eid.address"));
    assertNull(httpSession.getAttribute("eid.photo"));
}

From source file:edgeserver.Descoberta.java

private void publicaSensor(Gateway gateway, Sensor sensor) throws Exception {

    // make sure cookies is turn on
    CookieHandler.setDefault(new CookieManager());

    HTTPClient http = new HTTPClient();

    List<NameValuePair> postp = new ArrayList<>();
    postp.add(new BasicNameValuePair("login", "huberto"));
    postp.add(new BasicNameValuePair("password", "99766330"));

    http.sendPost(this.urlLogin, postp);

    List<NameValuePair> SensorParams = new ArrayList<>();
    SensorParams.add(new BasicNameValuePair("sensor_nome", sensor.getNome()));
    SensorParams.add(new BasicNameValuePair("sensor_desc", sensor.getDescricao()));
    SensorParams.add(new BasicNameValuePair("sensor_modelo", sensor.getModelo()));
    SensorParams.add(new BasicNameValuePair("sensor_precisao", sensor.getPrecisao()));
    SensorParams.add(new BasicNameValuePair("sensor_tipo", sensor.getTipo()));
    SensorParams.add(new BasicNameValuePair("sensor_servidorborda", Integer.toString(this.ServidorBordaID)));
    SensorParams.add(new BasicNameValuePair("sensor_gateway", Integer.toString(gateway.getId())));

    String result = http.GetPageContent(this.insertSensorURI, SensorParams);
    //System.out.println(result);
    String publicType = result.split(":")[0];
    String sensorID = result.split(":")[1];

    sensor.setId(Integer.parseInt(sensorID));

    if (null != publicType)
        switch (publicType) {
        case "insert":
            System.out.println("-> Sensor " + sensor.getNome() + "(" + sensor.getId()
                    + ") cadastrado no Servidor de Contexto com sucesso.");
            break;
        case "update":
            System.out.println("-> Sensor " + sensor.getNome() + "(" + sensor.getId()
                    + ") atualizado no Servidor de Contexto com sucesso.");
            break;
        }/*from  w  w  w .ja va2  s.c  o  m*/
}

From source file:org.opendatakit.aggregate.odktables.api.perf.AggregateSynchronizer.java

public AggregateSynchronizer(String ctxt, String appName, String odkApiVersion, String aggregateUri,
        String accessToken) throws InvalidAuthTokenException {
    this.context = ctxt;
    this.appName = appName;
    this.odkClientApiVersion = odkApiVersion;
    this.aggregateUri = aggregateUri;
    logger.debug("AggregateUri:" + aggregateUri);
    this.baseUri = normalizeUri(aggregateUri, "/");
    logger.error("baseUri:" + baseUri);

    // This is technically not correct, as we should really have a global
    // that we manage for this... If there are two or more service threads
    // running, we could forget other session cookies. But, by creating a 
    // new cookie manager here, we ensure that we don't have any stale 
    // session cookies at the start of each sync.

    cm = new CookieManager();
    CookieHandler.setDefault(cm);

    // now everything should work...
    ClientConfig cc;/*from w ww  .j av a 2  s.co  m*/

    cc = new ClientConfig();
    cc.setLoadWinkApplications(false);
    cc.applications(new ODKClientApplication());
    cc.handlers(new GzipHandler(), new ReAuthSecurityHandler(this));
    cc.connectTimeout(CONNECTION_TIMEOUT);
    cc.readTimeout(2 * CONNECTION_TIMEOUT);
    cc.followRedirects(true);

    this.rt = new RestClient(cc);

    cc = new ClientConfig();
    cc.setLoadWinkApplications(false);
    cc.applications(new ODKClientApplication());
    cc.connectTimeout(CONNECTION_TIMEOUT);
    cc.readTimeout(2 * CONNECTION_TIMEOUT);
    cc.followRedirects(true);

    this.tokenRt = new RestClient(cc);

    this.resources = new HashMap<String, TableResource>();

    checkAccessToken(accessToken);
    this.accessToken = accessToken;

}

From source file:org.opendatakit.sync.aggregate.AggregateSynchronizer.java

public AggregateSynchronizer(Context context, String appName, String odkApiVersion, String aggregateUri,
        String accessToken) throws InvalidAuthTokenException {
    this.context = context;
    this.appName = appName;
    this.log = WebLogger.getLogger(appName);
    this.odkClientApiVersion = odkApiVersion;
    this.aggregateUri = aggregateUri;
    log.e(LOGTAG, "AggregateUri:" + aggregateUri);
    this.baseUri = normalizeUri(aggregateUri, "/");
    log.e(LOGTAG, "baseUri:" + baseUri);

    // This is technically not correct, as we should really have a global
    // that we manage for this... If there are two or more service threads
    // running, we could forget other session cookies. But, by creating a
    // new cookie manager here, we ensure that we don't have any stale
    // session cookies at the start of each sync.

    cm = new CookieManager();
    CookieHandler.setDefault(cm);

    // now everything should work...
    ClientConfig cc;/*from   www  .  ja  v a 2 s  .co  m*/

    cc = new ClientConfig();
    cc.setLoadWinkApplications(false);
    cc.applications(new ODKClientApplication());
    cc.handlers(new GzipHandler(), new ReAuthSecurityHandler(this));
    cc.connectTimeout(WebUtils.CONNECTION_TIMEOUT);
    cc.readTimeout(2 * WebUtils.CONNECTION_TIMEOUT);
    cc.followRedirects(true);

    this.rt = new RestClient(cc);

    cc = new ClientConfig();
    cc.setLoadWinkApplications(false);
    cc.applications(new ODKClientApplication());
    cc.connectTimeout(WebUtils.CONNECTION_TIMEOUT);
    cc.readTimeout(2 * WebUtils.CONNECTION_TIMEOUT);
    cc.followRedirects(true);

    this.tokenRt = new RestClient(cc);

    this.resources = new HashMap<String, TableResource>();

    checkAccessToken(accessToken);
    this.accessToken = accessToken;

}

From source file:org.sakaiproject.commons.tool.entityprovider.CommonsEntityProvider.java

@EntityCustomAction(action = "getUrlMarkup", viewKey = EntityView.VIEW_LIST)
public ActionReturn getUrlMarkup(OutputStream outputStream, EntityView view, Map<String, Object> params) {

    String userId = getCheckedUser();

    String urlString = (String) params.get("url");

    if (StringUtils.isBlank(urlString)) {
        throw new EntityException("No url supplied", "", HttpServletResponse.SC_BAD_REQUEST);
    }//from  www  .j a v  a  2  s .co m

    try {
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL url = new URL(urlString);
        URLConnection c = url.openConnection();

        if (c instanceof HttpURLConnection) {
            HttpURLConnection conn = (HttpURLConnection) c;
            conn.setRequestProperty("User-Agent", USER_AGENT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            String contentEncoding = conn.getContentEncoding();
            String contentType = conn.getContentType();
            int responseCode = conn.getResponseCode();
            log.debug("Response code: {}", responseCode);

            int redirectCounter = 1;
            while ((responseCode == HttpURLConnection.HTTP_MOVED_PERM
                    || responseCode == HttpURLConnection.HTTP_MOVED_TEMP
                    || responseCode == HttpURLConnection.HTTP_SEE_OTHER) && redirectCounter < 20) {
                String newUri = conn.getHeaderField("Location");
                log.debug("{}. New URI: {}", responseCode, newUri);
                String cookies = conn.getHeaderField("Set-Cookie");
                url = new URL(newUri);
                c = url.openConnection();
                conn = (HttpURLConnection) c;
                conn.setInstanceFollowRedirects(false);
                conn.setRequestProperty("User-Agent", USER_AGENT);
                conn.setRequestProperty("Cookie", cookies);
                conn.connect();
                contentEncoding = conn.getContentEncoding();
                contentType = conn.getContentType();
                responseCode = conn.getResponseCode();
                log.debug("Redirect counter: {}", redirectCounter);
                log.debug("Response code: {}", responseCode);
                redirectCounter += 1;
            }

            if (contentType != null
                    && (contentType.startsWith("text/html") || contentType.startsWith("application/xhtml+xml")
                            || contentType.startsWith("application/xml"))) {
                String mimeType = contentType.split(";")[0].trim();
                log.debug("mimeType: {}", mimeType);
                log.debug("encoding: {}", contentEncoding);

                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));

                String line = null;
                while ((line = reader.readLine()) != null) {
                    writer.write(line);
                }

                return new ActionReturn(contentEncoding, mimeType, outputStream);
            } else {
                log.debug("Invalid content type {}. Throwing bad request ...", contentType);
                throw new EntityException("Url content type not supported", "",
                        HttpServletResponse.SC_BAD_REQUEST);
            }
        } else {
            throw new EntityException("Url content type not supported", "", HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (MalformedURLException mue) {
        throw new EntityException("Invalid url supplied", "", HttpServletResponse.SC_BAD_REQUEST);
    } catch (IOException ioe) {
        throw new EntityException("Failed to download url contents", "",
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:test.be.fedict.eid.applet.ControllerTest.java

@Test
public void controllerIdentificationWithAddressAndPhoto() throws Exception {
    // setup/*w  ww  .  jav a2 s  .  co  m*/
    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    // make sure that the session cookies are passed during conversations
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    this.servletHolder.setInitParameter("IncludeAddress", "true");
    this.servletHolder.setInitParameter("IncludePhoto", "true");

    // operate
    controller.run();

    // verify
    LOG.debug("verify...");
    SessionHandler sessionHandler = this.servletTester.getContext().getSessionHandler();
    SessionManager sessionManager = sessionHandler.getSessionManager();
    LOG.debug("session manager type: " + sessionManager.getClass().getName());
    HashSessionManager hashSessionManager = (HashSessionManager) sessionManager;
    LOG.debug("# sessions: " + hashSessionManager.getSessions());
    assertEquals(1, hashSessionManager.getSessions());
    Map<String, HttpSession> sessionMap = hashSessionManager.getSessionMap();
    LOG.debug("session map: " + sessionMap);
    Entry<String, HttpSession> sessionEntry = sessionMap.entrySet().iterator().next();
    HttpSession httpSession = sessionEntry.getValue();
    assertNotNull(httpSession.getAttribute("eid"));
    Identity identity = (Identity) httpSession.getAttribute("eid.identity");
    assertNotNull(identity);
    assertNotNull(identity.name);
    LOG.debug("name: " + identity.name);
    LOG.debug("nationality: " + identity.getNationality());
    LOG.debug("national number: " + identity.getNationalNumber());
    assertNull(httpSession.getAttribute("eid.identifier"));
    assertNotNull(httpSession.getAttribute("eid.address"));
    assertNotNull(httpSession.getAttribute("eid.photo"));
}

From source file:com.blackducksoftware.integration.hub.rest.RestConnection.java

public void handleRequest(final ClientResource resource) throws BDRestException {
    final boolean debugLogging = isDebugLogging();
    if (debugLogging) {
        logMessage(LogLevel.TRACE, "Resource : " + resource.toString());
        logRestletRequestOrResponse(resource.getRequest());
    }//from w  ww . j a v  a2s .c o  m

    final CookieHandler originalCookieHandler = CookieHandler.getDefault();
    try {
        if (originalCookieHandler != null) {
            if (debugLogging) {
                logMessage(LogLevel.TRACE, "Setting Cookie Handler to NULL");
            }
            CookieHandler.setDefault(null);
        }
        resource.handle();
    } catch (final ResourceException e) {
        throw new BDRestException("Problem connecting to the Hub server provided.", e, resource);
    } finally {
        if (originalCookieHandler != null) {
            if (debugLogging) {
                logMessage(LogLevel.TRACE,
                        "Setting Original Cookie Handler : " + originalCookieHandler.toString());
            }
            CookieHandler.setDefault(originalCookieHandler);
        }
    }

    if (debugLogging) {
        logRestletRequestOrResponse(resource.getResponse());
        logMessage(LogLevel.TRACE, "Status Code : " + resource.getResponse().getStatus().getCode());
    }
}