Example usage for java.net CookiePolicy ACCEPT_ALL

List of usage examples for java.net CookiePolicy ACCEPT_ALL

Introduction

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

Prototype

CookiePolicy ACCEPT_ALL

To view the source code for java.net CookiePolicy ACCEPT_ALL.

Click Source Link

Document

One pre-defined policy which accepts all cookies.

Usage

From source file:jmc.util.UtlFbComents.java

public static String getJSONComentarios(String url, Long numComents) throws JMCException {
    String linea = "";
    String buf = "";

    try {//from   w ww .  j  av a  2s.  co m
        Properties props = ConfigPropiedades.getProperties("props_config.properties");
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        URL ur = new URL(
                "http://graph.facebook.com/comments?id=" + url + "&limit=" + numComents + "&filter=stream");
        HttpURLConnection cn = (HttpURLConnection) ur.openConnection();

        cn.setRequestProperty("user-agent", props.getProperty("navegador"));
        cn.setInstanceFollowRedirects(false);
        cn.setUseCaches(false);
        cn.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(cn.getInputStream()));

        while ((linea = br.readLine()) != null) {
            buf.concat(linea);
        }
        cn.disconnect();

    } catch (IOException e) {
        throw new JMCException(e);
    }
    return buf;
}

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

private static boolean isURLAlive(String url) throws IOException {
    try {//from w  w w.ja va 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));

        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.muse.launcher.Splash.java

private static boolean isURLAlive(String url) throws IOException {
    try {//from   w  w w.j av  a2s  .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  va 2  s. c  om*/
        // 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;
}

From source file:org.perfcake.message.sender.HttpClientSender.java

@Override
public void preSend(final Message message, final Properties messageAttributes) throws Exception {
    super.preSend(message, messageAttributes);

    if (storeCookies && localCookieManager.get() == null) {
        localCookieManager.set(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    }//from   w w w .j  ava 2  s .  c om

    currentMethod = getDynamicMethod(messageAttributes);

    payloadLength = 0;
    if (message == null) {
        payload = null;
    } else if (message.getPayload() != null) {
        payload = message.getPayload().toString();
        payloadLength = payload.length();
    }

    final URI uri = url.toURI();
    switch (currentMethod) {
    case GET:
        currentRequest = new HttpGet(uri);
        break;
    case POST:
        currentRequest = new HttpPost(uri);
        break;
    case PUT:
        currentRequest = new HttpPut(uri);
        break;
    case PATCH:
        currentRequest = new HttpPatch(uri);
        break;
    case DELETE:
        currentRequest = new HttpDelete(uri);
        break;
    case HEAD:
        currentRequest = new HttpHead(uri);
        break;
    case TRACE:
        currentRequest = new HttpTrace(uri);
        break;
    case OPTIONS:
        currentRequest = new HttpOptions(uri);
    }

    StringEntity msg = null;
    if (payload != null && (currentRequest instanceof HttpEntityEnclosingRequestBase)) {
        ((HttpEntityEnclosingRequestBase) currentRequest).setEntity(
                new StringEntity(payload, ContentType.create("text/plain", Utils.getDefaultEncoding())));
    }

    if (storeCookies) {
        popCookies();
    }

    if (log.isDebugEnabled()) {
        log.debug("Setting HTTP headers: ");
    }

    // set message properties as HTTP headers
    if (message != null) {
        for (final Entry<Object, Object> property : message.getProperties().entrySet()) {
            final String pKey = property.getKey().toString();
            final String pValue = property.getValue().toString();
            currentRequest.setHeader(pKey, pValue);
            if (log.isDebugEnabled()) {
                log.debug(pKey + ": " + pValue);
            }
        }
    }

    // set message headers as HTTP headers
    if (message != null) {
        if (message.getHeaders().size() > 0) {
            for (final Entry<Object, Object> property : message.getHeaders().entrySet()) {
                final String pKey = property.getKey().toString();
                final String pValue = property.getValue().toString();
                currentRequest.setHeader(pKey, pValue);
                if (log.isDebugEnabled()) {
                    log.debug(pKey + ": " + pValue);
                }
            }
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("End of HTTP headers.");
    }
}

From source file:com.microfocus.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {/*  w  ww  .ja  va2s.  co  m*/
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat(
                "/com.microfocus.application.automation.tools.srf.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String credentialsId = document.getElementsByTagName("credentialsId").item(0).getTextContent();
        UsernamePasswordCredentials credentials = CredentialsProvider.findCredentialById(credentialsId,
                StandardUsernamePasswordCredentials.class, build, URIRequirementBuilder.create().build());

        String app = credentials.getUsername();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = credentials.getPassword().getPlainText();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();

        // Normalize SRF server URL string if needed
        if (server.substring(server.length() - 1).equals("/")) {
            server = server.substring(0, server.length() - 1);
        }

        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0) != null
                    ? document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim()
                    : null;
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0) != null
                    ? document.getElementsByTagName("srfTunnelPath").item(0).getTextContent()
                    : null;
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

From source file:com.hpe.application.automation.tools.srf.run.RunFromSrfBuilder.java

public static JSONObject getSrfConnectionData(AbstractBuild<?, ?> build, PrintStream logger) {
    try {/*from  www  . ja  va  2 s . c o m*/
        CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        String path = build.getProject().getParent().getRootDir().toString();
        path = path.concat("/com.hpe.application.automation.tools.settings.SrfServerSettingsBuilder.xml");
        File file = new File(path);
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        // This also shows how you can consult the global configuration of the builder
        JSONObject connectionData = new JSONObject();

        String app = document.getElementsByTagName("srfAppName").item(0).getTextContent();
        String tenant = app.substring(1, app.indexOf('_'));
        String secret = document.getElementsByTagName("srfSecretName").item(0).getTextContent();
        String server = document.getElementsByTagName("srfServerName").item(0).getTextContent();
        boolean https = true;
        if (!server.startsWith("https://")) {
            if (!server.startsWith("http://")) {
                String tmp = server;
                server = "https://";
                server = server.concat(tmp);
            } else
                https = false;
        }
        URL urlTmp = new URL(server);
        if (urlTmp.getPort() == -1) {
            if (https)
                server = server.concat(":443");
            else
                server = server.concat(":80");
        }
        String srfProxy = "";
        String srfTunnel = "";
        try {
            srfProxy = document.getElementsByTagName("srfProxyName").item(0).getTextContent().trim();
            srfTunnel = document.getElementsByTagName("srfTunnelPath").item(0).getTextContent();
        } catch (Exception e) {
            throw e;
        }
        connectionData.put("app", app);
        connectionData.put("tunnel", srfTunnel);
        connectionData.put("secret", secret);
        connectionData.put("server", server);
        connectionData.put("https", (https) ? "True" : "False");
        connectionData.put("proxy", srfProxy);
        connectionData.put("tenant", tenant);
        return connectionData;
    } catch (ParserConfigurationException e) {
        logger.print(e.getMessage());
        logger.print("\n\r");
    } catch (SAXException | IOException e) {
        logger.print(e.getMessage());
    }
    return null;
}

From source file:io.jari.geenstijl.API.API.java

/**
 * ensureCookies sets up cookiemanager and makes sure cookies are set up
 *///  w  w w  .  j  av  a2 s.c o  m
static void ensureCookies() {
    if (CookieHandler.getDefault() == null) {
        cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);
    }
}

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

private static boolean isURLAlive(String url) throws IOException {
    try {/*from   www . j a v  a2s  .  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);
        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;
}

From source file:fr.cls.atoll.motu.api.rest.MotuRequest.java

/**
 * Executes the request and returns the result as a stream. The stream contains: - the extracted netcdf
 * file if mode is 'console' - the url the extracted netcdf file if mode is 'url' url - the url of the XML
 * status file if mode is 'status' (this file contains the status of the request : INPROGRESS or
 * ERROR+error message or DONE).//from   w  w  w .  j  a v  a  2s.  c o  m
 * 
 * This function must be used
 * 
 * @return the result of the request as a stream
 * 
 * @throws MotuRequestException the motu request exception
 */
public InputStream executeV2() throws MotuRequestException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("executeV2() - entering");
    }
    // First set the default cookie manager.
    // Must be set before the first http request.
    // This is essential for cookie session managment with CAS authentication
    cookieStore.removeAll();
    CookieManager cm = new CookieManager(cookieStore, CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cm);

    URL url = null;

    // Get the authentication mode parameter
    String authModeString = (String) motuRequestParameters
            .getParameter(MotuRequestParametersConstant.PARAM_AUTHENTICATION_MODE);
    AuthenticationMode authMode = null;
    if (!AssertionUtils.isNullOrEmpty(authModeString)) {
        authMode = AuthenticationMode.fromValue((String) motuRequestParameters
                .getParameter(MotuRequestParametersConstant.PARAM_AUTHENTICATION_MODE));
    }
    // Authentication mode is not an extraction criteria, remove it now
    motuRequestParameters.removeParameter(MotuRequestParametersConstant.PARAM_AUTHENTICATION_MODE);

    // Get login / password parameters,
    String login = (String) motuRequestParameters.getParameter(MotuRequestParametersConstant.PARAM_LOGIN);
    String password = (String) motuRequestParameters.getParameter(MotuRequestParametersConstant.PARAM_PWD);
    // Login/password are not extraction criteria, remove them now
    motuRequestParameters.removeParameter(MotuRequestParametersConstant.PARAM_LOGIN);
    motuRequestParameters.removeParameter(MotuRequestParametersConstant.PARAM_PWD);

    // String requestParams = null;

    String targetUrl = getRequestUrl();

    // Check is authentication mode is set or not
    // if not set, guess the authentication mode

    boolean guessAuthentication = (authMode == null) && (!AssertionUtils.isNullOrEmpty(login));

    if (guessAuthentication) {
        UserBase user = new UserBase();

        if (!AssertionUtils.isNullOrEmpty(login)) {
            user.setLogin(login);
            if (AssertionUtils.isNullOrEmpty(password)) {
                password = "";
            }
            user.setPwd(password);
        }

        try {
            RestUtil.checkAuthenticationMode(servletUrl, user);
            authMode = user.getAuthenticationMode();
        } catch (MotuCasException e) {
            String msg = String.format("Unable to check authentication mode from url '%s'. Reason is:\n %s",
                    servletUrl, e.notifyException());
            throw new MotuRequestException(msg, e);
        } catch (IOException e) {
            String msg = String.format("Unable to check authentication mode from url '%s'. Reason is:\n %s",
                    servletUrl, e.getMessage());
            throw new MotuRequestException(msg, e);
        }
    }

    try {
        if (authMode == AuthenticationMode.CAS) {
            // Add CAS ticket to the query parameters
            // If url is CASified then a CAS ticket is added to the returned url.
            // If url is not CASified then the original url is returned.
            // If login or password is null or empty, then the original url is returned.
            targetUrl = AssertionUtils.addCASTicket(targetUrl, login, password, null);
        }

        url = new URL(targetUrl);
    } catch (MalformedURLException e) {
        LOG.error("executeV2()", e);

        throw new MotuRequestException("Invalid url", e);
    } catch (MotuCasBadRequestException e) {
        LOG.error("executeV2()", e);

        throw new MotuRequestException("Invalid url", e);
    } catch (IOException e) {
        LOG.error("executeV2()", e);

        throw new MotuRequestException("Invalid url", e);
    }

    LOG.info("URL=" + targetUrl);

    HttpURLConnection urlConnection = null;

    try {
        urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setConnectTimeout(connectTimeout);
        if ((authMode == AuthenticationMode.BASIC) && (!AssertionUtils.isNullOrEmpty(login))
                && (!AssertionUtils.isNullOrEmpty(password))) {
            // Set basic authentication
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(login);
            stringBuffer.append(":");
            stringBuffer.append(password);
            byte[] encoding = new org.apache.commons.codec.binary.Base64()
                    .encode(stringBuffer.toString().getBytes());
            urlConnection.setRequestProperty("Authorization", "Basic " + new String(encoding));
        }

    } catch (IOException ex) {
        LOG.error("executeV2()", ex);

        throw new MotuRequestException("Request connection failed", ex);
    }

    try {
        InputStream returnInputStream = urlConnection.getInputStream();

        if (LOG.isDebugEnabled()) {
            LOG.debug("executeV2() - exiting");
        }
        return returnInputStream;

    } catch (IOException ex) {
        LOG.error("executeV2()", ex);

        MotuRequestException motuRequestException;
        try {
            motuRequestException = new MotuRequestException("Request failed - errorCode: "
                    + urlConnection.getResponseCode() + ", errorMsg: " + urlConnection.getResponseMessage(),
                    ex);
        } catch (IOException e) {
            LOG.error("executeV2()", e);

            motuRequestException = new MotuRequestException("Request connection failed", ex);
        }
        throw motuRequestException;
    }

}