Example usage for java.net CookieHandler getDefault

List of usage examples for java.net CookieHandler getDefault

Introduction

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

Prototype

public static synchronized CookieHandler getDefault() 

Source Link

Document

Gets the system-wide cookie handler.

Usage

From source file:net.sf.jabref.logic.net.URLDownload.java

private static void setCookieHandler() {
    try {/*from   w w w  .  j  av  a 2  s  . c  om*/
        // This should set up JabRef to receive cookies properly
        if (CookieHandler.getDefault() == null) {
            CookieHandler.setDefault(new CookieHandlerImpl());
        }
    } catch (SecurityException ignored) {
        // Setting or getting the system default cookie handler is forbidden
        // In this case cookie handling is not possible.
    }
}

From source file:org.exoplatform.utils.image.CookieAwarePicassoDownloader.java

/**
 * Creates a new CookieManager if none already exists and sets it as the
 * default CookieHandler/* w ww .  jav a2 s . c  om*/
 * 
 * @return the CookieManager newly created, or the existing one if it's
 *         already the default CookieHandler
 */
private CookieManager initCookieManager() {
    CookieHandler handler = CookieHandler.getDefault();
    CookieManager manager;
    if (handler == null || !(handler instanceof CookieManager)) {
        manager = new CookieManager();
        CookieHandler.setDefault(manager);
        // Sync cookies from ExoConnectionUtils only
        // when the Cookies Manager is created
        syncCookies(manager);
    } else {
        manager = (CookieManager) handler;
    }
    return manager;
}

From source file:at.florian_lentsch.expirysync.net.JsonCaller.java

public JsonCaller(String hostStr) throws URISyntaxException {
    setHost(hostStr);/*from  w w w. j av a  2 s.  c o  m*/
    this.cookieManager = (CookieManager) CookieHandler.getDefault();

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

From source file:com.wikaba.ogapp.AgentService.java

@Override
public void onDestroy() {
    super.onDestroy();

    CustomCookieManager cookieman = (CustomCookieManager) CookieHandler.getDefault();
    CookieStore cookiestore = cookieman.getCookieStore();
    List<HttpCookie> cookies = cookiestore.getCookies();
    dbman.saveCookies(cookies);/* w  w  w.j a  va  2s  . co  m*/

    if (dbman != null) {
        dbman.close();
        dbman = null;
    }
}

From source file:jdbc.ClientFormLogin.java

public void setCookie(URL url, String value) throws IOException, URISyntaxException {
    CookieHandler handler = CookieHandler.getDefault();
    if (handler != null) {
        Map<String, List<String>> headers = new HashMap<String, List<String>>();
        List<String> values = new Vector<String>();
        values.add(value);//  www. j a  v a  2 s .  c  o m
        headers.put("Cookie", values);
        handler.put(url.toURI(), headers);
        System.out.println();
    }
}

From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java

public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData)
        throws Throwable {
    HttpURLConnection connection = null;
    InputStream is = null;//from   w w  w  .j a v a 2 s.co m
    int statusCode;

    if (DUMP_PAYLOAD) {
        log.debug("Send request to {}", remoteServiceURL);
        log.debug("Request payload: {}", requestData);
    }

    // Send request
    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    try {
        CookieHandler.setDefault(cookieManager);

        URL url = new URL(remoteServiceURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName);
        connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL);
        connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8");
        connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length);

        CookieStore store = cookieManager.getCookieStore();
        String cookiesStr = "";

        for (HttpCookie cookie : store.getCookies()) {
            if (!"".equals(cookiesStr))
                cookiesStr += "; ";
            cookiesStr += cookie.getName() + "=" + cookie.getValue();
        }

        connection.setRequestProperty("Cookie", cookiesStr);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(requestData);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationException("IOException while sending RPC request", e);
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
    }

    // Receive and process response
    try {

        is = connection.getInputStream();
        statusCode = connection.getResponseCode();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        String encodedResponse = baos.toString("UTF8");
        if (DUMP_PAYLOAD) {
            log.debug("Response code: {}", statusCode);
            log.debug("Response payload: {}", encodedResponse);
        }

        // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse);
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new StatusCodeException(statusCode, encodedResponse);
        } else if (encodedResponse == null) {
            // This can happen if the XHR is interrupted by the server dying
            throw new InvocationException("No response payload");
        } else if (isReturnValue(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            return responseReader.read(createStreamReader(encodedResponse));
        } else if (isThrownException(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject();
            throw throwable;
        } else {
            throw new InvocationException("Unknown response " + encodedResponse);
        }
    } catch (IOException e) {

        log.error("error response: {}", IOUtils.toString(connection.getErrorStream()));
        throw new InvocationException("IOException while receiving RPC response", e);

    } catch (SerializationException e) {
        throw new InvocationException("Error while deserialization response", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (connection != null) {
            // connection.disconnect();
        }
    }
}

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  va 2 s  .  com*/
 * @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;/*ww w  . ja v  a2s  . com*/
    mediaDataSourceFactory = buildDataSourceFactory(true);
    mainHandler = new Handler();
    window = new Timeline.Window();
    if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
        CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
    }
}

From source file:com.studyjams.mdvideo.PlayerModule.ExoPlayerV2.PlayerActivityV2.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    shouldAutoPlay = true;// ww w .j  a  va  2 s  .co  m
    mediaDataSourceFactory = buildDataSourceFactory(true);
    mainHandler = new Handler();
    window = new Timeline.Window();
    if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
        CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
    }

    setContentView(R.layout.player_activity_v2);
    //        View rootView = findViewById(root);

    simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player_view);
    //        simpleExoPlayerView.setControllerVisibilityListener(this);
    simpleExoPlayerView.requestFocus();

    /**?ExoPlayermediaController**/
    simpleExoPlayerView.setUseController(false);

    controller = (MediaControlView) findViewById(R.id.player_control);
    controller.setVisibilityListener(new MediaControlView.VisibilityListener() {
        @Override
        public void onVisibilityChange(int visibility) {

        }
    });
    EventBus.getDefault().register(this);
}

From source file:com.appunite.appunitevideoplayer.PlayerActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.player_activity);
    root = (ViewGroup) findViewById(R.id.root);
    root.setOnTouchListener(new OnTouchListener() {
        @Override/*from ww w.ja v a  2s .  co m*/
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                toggleControlsVisibility();
            } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.performClick();
            }
            return true;
        }
    });
    root.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE
                    || keyCode == KeyEvent.KEYCODE_MENU) {
                return false;
            }
            return mediaController.dispatchKeyEvent(event);
        }
    });

    shutterView = findViewById(R.id.shutter);

    videoFrame = (AspectRatioFrameLayout) findViewById(R.id.video_frame);
    surfaceView = (SurfaceView) findViewById(R.id.surface_view);
    surfaceView.getHolder().addCallback(this);

    subtitleLayout = (SubtitleLayout) findViewById(R.id.subtitles);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
    toolbar.setTitle(getIntent().getStringExtra(TITLE_TEXT_EXTRA));
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });

    mediaController = new MediaController(this);
    mediaController.setAnchorView(root);
    controllerView = (ViewGroup) findViewById(R.id.controller_view);
    controllerView.addView(mediaController);
    CookieHandler currentHandler = CookieHandler.getDefault();
    if (currentHandler != defaultCookieManager) {
        CookieHandler.setDefault(defaultCookieManager);
    }

    audioCapabilitiesReceiver = new AudioCapabilitiesReceiver(this, this);
    audioCapabilitiesReceiver.register();

    progressBar = (ProgressBar) findViewById(R.id.progress_bar);

    playButton = (ImageView) findViewById(R.id.play_button_icon);
    final int playButtonIconDrawableId = getIntent().getIntExtra(PLAY_BUTTON_EXTRA, 0);
    if (playButtonIconDrawableId != 0) {
        playButton.setImageDrawable(ContextCompat.getDrawable(this, playButtonIconDrawableId));
        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                preparePlayer(true);
            }
        });
    }
}