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:edgeserver.Publicador.java

private void publicaDado(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);

    sensor.updateDado();/*from   ww  w . j  a v a  2 s . c om*/

    List<NameValuePair> GatewayParams = new ArrayList<>();
    GatewayParams
            .add(new BasicNameValuePair("publicacao_servidorborda", Integer.toString(this.ServidorBordaID)));
    GatewayParams.add(new BasicNameValuePair("publicacao_sensor", Integer.toString(sensor.getId())));
    GatewayParams.add(new BasicNameValuePair("publicacao_datacoleta",
            new Timestamp(this.datapublicacao.getTime()).toString()));
    GatewayParams.add(new BasicNameValuePair("publicacao_datapublicacao",
            new Timestamp(this.datapublicacao.getTime()).toString()));
    GatewayParams.add(new BasicNameValuePair("publicacao_valorcoletado", Float.toString(sensor.getDado())));

    String result = http.GetPageContent(this.urlInsertDado, GatewayParams);
}

From source file:hanulhan.cas.client.CasRestActions.java

public String doLogoutCasUser() {

    jsonStatus = new JsonStatus();
    CookieHandler.setDefault(new CookieManager());
    StringBuilder myResult;//from w  ww  .  jav a 2  s.  co m
    return SUCCESS;
}

From source file:hudson.plugins.sitemonitor.SiteMonitorRecorder.java

/**
 * Performs the web site monitoring by checking the response code of the site's URL.
 * /*from ww w  . ja v  a2 s.c  o  m*/
 * @param build
 *            the build
 * @param launcher
 *            the launcher
 * @param listener
 *            the listener
 * @return true if all sites give success response codes, false otherwise
 * @throws InterruptedException
 *             when there's an interruption
 * @throws IOException
 *             when there's an IO error
 */
@Override
public final boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher,
        final BuildListener listener) throws InterruptedException, IOException {
    List<Result> results = new ArrayList<Result>();
    SiteMonitorDescriptor descriptor = (SiteMonitorDescriptor) getDescriptor();

    if (CookieHandler.getDefault() == null) {
        CookieHandler.setDefault(new CookieManager());
    }

    boolean hasFailure = false;
    for (Site site : mSites) {

        Integer responseCode = null;
        Status status;
        String note = "";
        HttpURLConnection connection = null;

        try {
            connection = getConnection(site.getUrl());

            if (site.getTimeout() != null) {
                connection.setConnectTimeout(site.getTimeout() * MILLISECS_IN_SECS);
            } else {
                connection.setConnectTimeout(descriptor.getTimeout() * MILLISECS_IN_SECS);
            }

            responseCode = connection.getResponseCode();

            List<Integer> successResponseCodes = descriptor.getSuccessResponseCodes();

            if (site.getSuccessResponseCodes() != null && site.getSuccessResponseCodes().size() > 0) {
                successResponseCodes = site.getSuccessResponseCodes();
            }

            if (successResponseCodes.contains(responseCode)) {
                status = Status.UP;
            } else {
                status = Status.ERROR;
            }
        } catch (SocketTimeoutException ste) {
            listener.getLogger().println(ste + " - " + ste.getMessage());
            status = Status.DOWN;
        } catch (Exception e) {
            note = e + " - " + e.getMessage();
            listener.getLogger().println(note);
            status = Status.EXCEPTION;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }

        note = "[" + status + "] " + note;
        listener.getLogger()
                .println(Messages.SiteMonitor_Console_URL() + site.getUrl() + ", "
                        + Messages.SiteMonitor_Console_ResponseCode() + responseCode + ", "
                        + Messages.SiteMonitor_Console_Status() + status);

        if (!hasFailure && status != Status.UP) {
            hasFailure = true;
        }

        Result result = new Result(site, responseCode, status, note);
        results.add(result);
    }

    build.addAction(new SiteMonitorRootAction(results));
    hudson.model.Result result;
    if (hasFailure) {
        result = hudson.model.Result.FAILURE;
    } else {
        result = hudson.model.Result.SUCCESS;
    }
    build.setResult(result);

    // the return value is not used when this class implements a Recorder,
    // it's left here just in case this class switches to a Builder.
    // http://n4.nabble.com/how-can-a-Recorder-mark-build-as-failure-td1746654.html
    return !hasFailure;
}

From source file:com.birdgang.sample.ui.fragment.ViewPagerHeaderVideoFragment.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    HeaderFragmentChangeNotifier.INSTANCE.addOnFragmentHeaderLifecycleListener(this);

    mHeaderItemEntry = getArguments().getParcelable(IntentParams.PARAMS_HEADER_ITEM);
    mHeaderVideoPosition = getArguments().getInt(IntentParams.PARAMS_EXTRA_INDEX);

    Log.i("birdgangviewpager",
            " ViewPagerHeaderVideoFragment > onCreate > headerItemEntry : " + mHeaderItemEntry.toString());

    shouldAutoPlay = true;//from  ww w  .ja v a  2  s . c o m
    mediaDataSourceFactory = buildDataSourceFactory(true);
    mainHandler = new Handler();
    window = new Timeline.Window();
    if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
        CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
    }
}

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

private String postToRestfulApi(String addr, String data, HttpServletRequest request,
          HttpServletResponse response) {
      if (localCookie)
          CookieHandler.setDefault(cm);
      String result = "";
      try {/*from ww w.ja  v  a  2 s  .  c  o  m*/
          URLConnection connection = new URL(API_ROOT + addr).openConnection();
          String cookieVal = getBrowserInfiniteCookie(request);
          if (cookieVal != null) {
              connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
              connection.setDoInput(true);
          }
          connection.setDoOutput(true);
          connection.setRequestProperty("Accept-Charset", "UTF-8");

          // Post JSON string to URL
          OutputStream os = connection.getOutputStream();
          byte[] b = data.getBytes("UTF-8");
          os.write(b);

          // Receive results back from API
          InputStream is = connection.getInputStream();
          result = IOUtils.toString(is, "UTF-8");

          String newCookie = getConnectionInfiniteCookie(connection);
          if (newCookie != null && response != null) {
              setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
          }
      } catch (Exception e) {
          //System.out.println("Exception: " + e.getMessage());
      }
      return result;
  }

From source file:at.becast.youploader.account.Account.java

public void loadCookie() throws IOException {
    CookieJar persistentCookieStore = new CookieJar();
    CookieManager cmrCookieMan = new CookieManager(persistentCookieStore, null);
    persistentCookieStore.setSerializeableCookies(this.getCookie());
    CookieHandler.setDefault(cmrCookieMan);
    LOG.info("Updating cookies");
    OAuth2 auth = new OAuth2(s.setting.get("client_id"), s.setting.get("clientSecret"), this.refreshToken);
    Map<String, String> headers = new HashMap<>();
    try {/*from  w ww.j a  va 2  s.  c  om*/
        headers.put("Authorization", auth.getHeader());
    } catch (NullPointerException e) {
    }
    SimpleHTTP Videoget = new SimpleHTTP();
    String resp = Videoget.get(
            "https://www.googleapis.com/youtube/v3/search?part=id&forMine=true&maxResults=1&type=video",
            headers);
    Pattern MY_PATTERN = Pattern.compile("\"videoId\": \"(.*?)\"");
    Matcher m = MY_PATTERN.matcher(resp);
    String vidID = null;
    while (m.find()) {
        vidID = m.group(1);
    }
    String url = String.format("https://www.youtube.com/edit?o=U&ns=1&video_id=%s", vidID);
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", Main.APP_NAME + " " + Main.VERSION);
    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    if (responseCode < 400) {
        this.setCookie(persistentCookieStore.getSerializeableCookies());
        LOG.info("Got cookie: {}", persistentCookieStore.getSerializeableCookies().toString());
    } else {
        LOG.info("Could not fetch Cookie {}", response.toString());
    }
}

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

private String postToRestfulApi(String addr, String data, HttpServletRequest request,
           HttpServletResponse response) {
       if (localCookie)
           CookieHandler.setDefault(cm);
       String result = "";
       try {/*from www .  j  a  va2 s .c  om*/
           URLConnection connection = new URL(API_ROOT + addr).openConnection();
           String cookieVal = getBrowserInfiniteCookie(request);
           if (cookieVal != null) {
               connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
               connection.setDoInput(true);
           }
           connection.setDoOutput(true);
           connection.setRequestProperty("Accept-Charset", "UTF-8");

           // Post JSON string to URL
           OutputStream os = connection.getOutputStream();
           byte[] b = data.getBytes("UTF-8");
           os.write(b);

           // Receive results back from API
           InputStream is = connection.getInputStream();
           result = IOUtils.toString(is, "UTF-8");

           String newCookie = getConnectionInfiniteCookie(connection);
           if (newCookie != null && response != null) {
               setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
           }
       } catch (Exception e) {
           //System.out.println("Exception: " + e.getMessage());
       }
       return result;
   }

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

public static String stringOfUrl(String addr, HttpServletRequest request, HttpServletResponse response) {
    if (localCookie)
        CookieHandler.setDefault(cm);
    try {/*from  www  .  j a  v  a 2 s .  c  o m*/
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        URL url = new URL(addr);
        URLConnection urlConnection = url.openConnection();

        String cookieVal = getBrowserInfiniteCookie(request);
        if (cookieVal != null) {
            urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal);
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Accept-Charset", "UTF-8");
        } else if (DEBUG_MODE)
            System.out.println("Infinit.e Cookie Value is Null");
        IOUtils.copy(urlConnection.getInputStream(), output);
        String newCookie = getConnectionInfiniteCookie(urlConnection);
        if (newCookie != null && response != null) {
            setBrowserInfiniteCookie(response, newCookie, request.getServerPort());
        }

        String toReturn = output.toString();
        output.close();
        return toReturn;
    } catch (IOException e) {
        return null;
    }
}

From source file:edu.stanford.muse.launcher.Splash.java

private static boolean isURLAlive(String url) throws IOException {
    try {//  w w w  .  j a v a2 s  .  c  o m
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false

        // since "index" may auto load default archive, attach it to session, and redirect to "info" page,
        // we need to maintain the session across the pages.
        // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

        out.println("Testing liveness at " + url);
        HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    return false;
}

From source file:edu.stanford.epadd.launcher.Splash.java

private static boolean isURLAlive(String url) throws IOException {
    try {/*from  ww w .  j a  v a 2  s  .  c  o m*/
        // attempt to fetch the page
        // throws a connect exception if the server is not even running
        // so catch it and return false

        // since "index" may auto load default archive, attach it to session, and redirect to "info" page,
        // we need to maintain the session across the pages.
        // see "Maintaining the session" at http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));

        out.println("Testing for already running ePADD by probing " + url);
        System.out.println("Testing for already running ePADD by probing " + url);
        HttpURLConnection u = (HttpURLConnection) new URL(url).openConnection();
        if (u.getResponseCode() == 200) {
            u.disconnect();
            out.println("ePADD is already running!");

            return true;
        }
        u.disconnect();
    } catch (ConnectException ce) {
    }
    out.println("Good, ePADD is not already running");
    return false;
}