List of usage examples for java.net CookieManager CookieManager
public CookieManager(CookieStore store, CookiePolicy cookiePolicy)
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 a v a 2 s .c o m*/ 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 {/*from w w w . ja v a2 s . 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 {/* w ww .ja v a 2s . 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 *///from ww w . j a va 2s .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 w w w .j a v a2s . co 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)./* w w w . ja v a2s. co 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; } }
From source file:io.kodokojo.brick.gitlab.GitlabConfigurer.java
public static OkHttpClient provideDefaultOkHttpClient() { OkHttpClient httpClient = new OkHttpClient(); final TrustManager[] certs = new TrustManager[] { new X509TrustManager() { @Override//from ww w. ja va 2 s . c o m public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } } }; SSLContext ctx = null; try { ctx = SSLContext.getInstance("TLS"); ctx.init(null, certs, new SecureRandom()); } catch (final java.security.GeneralSecurityException ex) { // } httpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); httpClient.setSslSocketFactory(ctx.getSocketFactory()); CookieManager cookieManager = new CookieManager(new GitlabCookieStore(), CookiePolicy.ACCEPT_ALL); httpClient.setCookieHandler(cookieManager); httpClient.setReadTimeout(2, TimeUnit.MINUTES); httpClient.setConnectTimeout(1, TimeUnit.MINUTES); httpClient.setWriteTimeout(1, TimeUnit.MINUTES); return httpClient; }
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 ww w. j ava2 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:org.apache.manifoldcf.crawler.connectors.webcrawler.WebcrawlerConnector.java
/** Install the connector. * This method is called to initialize persistent storage for the connector, such as database tables etc. * It is called when the connector is registered. *@param threadContext is the current thread context. *///from w w w .j a v a2 s .c o m @Override public void install(IThreadContext threadContext) throws ManifoldCFException { // Install IDBInterface mainDatabase = DBInterfaceFactory.make(threadContext, ManifoldCF.getMasterDatabaseName(), ManifoldCF.getMasterDatabaseUsername(), ManifoldCF.getMasterDatabasePassword()); RobotsManager rm = new RobotsManager(threadContext, mainDatabase); DNSManager dns = new DNSManager(threadContext, mainDatabase); CookieManager cm = new CookieManager(threadContext, mainDatabase); mainDatabase.beginTransaction(); try { rm.install(); dns.install(); cm.install(); } catch (ManifoldCFException e) { mainDatabase.signalRollback(); throw e; } catch (Error e) { mainDatabase.signalRollback(); throw e; } finally { mainDatabase.endTransaction(); } }
From source file:org.apache.manifoldcf.crawler.connectors.webcrawler.WebcrawlerConnector.java
/** Uninstall the connector. * This method is called to remove persistent storage for the connector, such as database tables etc. * It is called when the connector is deregistered. *@param threadContext is the current thread context. *//*from w w w . ja va 2 s . co m*/ @Override public void deinstall(IThreadContext threadContext) throws ManifoldCFException { // Uninstall IDBInterface mainDatabase = DBInterfaceFactory.make(threadContext, ManifoldCF.getMasterDatabaseName(), ManifoldCF.getMasterDatabaseUsername(), ManifoldCF.getMasterDatabasePassword()); RobotsManager rm = new RobotsManager(threadContext, mainDatabase); DNSManager dns = new DNSManager(threadContext, mainDatabase); CookieManager cm = new CookieManager(threadContext, mainDatabase); mainDatabase.beginTransaction(); try { cm.deinstall(); rm.deinstall(); dns.deinstall(); } catch (ManifoldCFException e) { mainDatabase.signalRollback(); throw e; } catch (Error e) { mainDatabase.signalRollback(); throw e; } finally { mainDatabase.endTransaction(); } }