/** * Creates a web hook in Gogs with the passed json configuration string * * @param jsonCommand A json buffer with the creation command of the web hook * @param projectName the project (owned by the user) where the webHook should be created * @throws IOException something went wrong */ int createWebHook(String jsonCommand, String projectName) throws IOException { String gogsHooksConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName + "/hooks"; Executor executor = getExecutor(); String result = executor .execute(Request.Post(gogsHooksConfigUrl).bodyString(jsonCommand, ContentType.APPLICATION_JSON)) .returnContent().asString(); JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( result ); int id = jsonObject.getInt("id"); return id; }
/** * Removes a web hook from a GOGS project * * @param projectName Name of the Gogs project to remove the hook from * @param hookId The ID of the hook to remove * @throws IOException something went wrong */ void removeHook(String projectName, int hookId) throws IOException { String gogsHooksConfigUrl = getGogsServer_apiUrl() + "repos/" + this.gogsServer_user + "/" + projectName + "/hooks/" + hookId; Executor executor = getExecutor(); int result = executor .execute(Request.Delete(gogsHooksConfigUrl)) .returnResponse().getStatusLine().getStatusCode(); if (result != 204) { throw new IOException("Delete hook did not return the expected value (returned " + result + ")"); } }
/** * Creates an empty repository (under the configured user). * It is created as a public repository, un-initialized. * * @param projectName the project name (repository) to create * @throws IOException Something went wrong (example: the repo already exists) */ void createEmptyRepo(String projectName) throws IOException { Executor executor = getExecutor(); String gogsHooksConfigUrl = getGogsServer_apiUrl() + "user/repos"; int result = executor .execute(Request .Post(gogsHooksConfigUrl) .bodyForm(Form.form() .add("name", projectName) .add("description", "API generated repository") .add("private", "true") .add("auto_init", "false") .build() ) ) .returnResponse().getStatusLine().getStatusCode(); if (result != 201) { throw new IOException("Repository creation call did not return the expected value (returned " + result + ")"); } }
@Test @RunAsClient public void hello() throws IOException, GeneralSecurityException { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial((TrustStrategy) (chain, authType) -> true) .build(); try (CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .build()) { String response = Executor.newInstance(httpClient) .execute(Request.Get("https://localhost:8443/")) .returnContent().asString(); assertThat(response).contains("Hello on port 8443, secure: true"); } }
/** * Post the data to the DataSift Ingestion endpoint. * @param data the data to send * @return the http response * @throws URISyntaxException if the uri is invalid or the request fails * @throws IOException if the http post fails */ @SuppressWarnings("checkstyle:designforextension") public HttpResponse post(final String data) throws URISyntaxException, IOException { log.debug("post()"); URI uri = getUri(); String authToken = getAuthorizationToken(config); metrics.sendAttempt.mark(); log.trace("Posting to ingestion endpoint {}", data); log.debug("Posting to ingestion endpoint data length {} bytes", data.length()); Request request = Request.Post(uri) .useExpectContinue() .version(HttpVersion.HTTP_1_1) .addHeader("Auth", authToken) .bodyString(data, ContentType.create("application/json")); return Executor.newInstance(httpClient) .execute(request) .returnResponse(); }
private boolean renewSession(final Executor executor, final String url, final String serviceName) throws IOException { assert sessionKey.isPresent(); final String _sessionKey = sessionKey.get(); final String uri = String.format("%s/v1/session/renew/%s", url, _sessionKey); logger.debug("PUT {}", uri); final Response response = executor.execute(Request.Put(uri)); boolean renewedOk = response.returnResponse().getStatusLine().getStatusCode() == 200; logger.debug("Session {} renewed={}", _sessionKey, renewedOk); if (!renewedOk) { logger.debug("Attempting to re-establish session for serviceName={}", serviceName); destroySession(url, _sessionKey); sessionKey = Optional.empty(); sessionKey = initSessionKey(serviceName); renewedOk = sessionKey.isPresent(); } return renewedOk; }
@Test public void testProxyAuthWithSSL() throws Exception { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(new File(keyStoreFile), keystorePW.toCharArray(), new TrustSelfSignedStrategy()) .build(); try (CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext) .setSSLHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }).build()) { Executor ex = Executor.newInstance(httpclient); Response response = ex.execute(Request.Get("https://localhost:9200/blahobar.234324234/logs/1") .addHeader("Authorization", String.format("Bearer %s", token)) .addHeader("X-Proxy-Remote-User", proxyUser)); System.out.println(response.returnContent().asString()); } catch (Exception e) { System.out.println(e); fail("Test Failed"); } }
static <ResType extends Error, ReqType> ResType invoke(final ClientConfig config, final ReqType request, final Class<ResType> responseClass, final Options opts) throws IOException { Request httpRequest = createRequest(config, request, opts); Executor invoker = createExecutor(config); return invoker .execute(httpRequest) .handleResponse( new ResponseHandler<ResType>() { public ResType handleResponse(HttpResponse response) throws IOException { ResType res = Endpoint.handleResponse(response, responseClass); if (LOG.isDebugEnabled()) { LOG.debug("response: {}", res); } return res; } } ); }
@Scheduled(cron = "0 0 9,18 * * ?") public void run() { for (Account account : getAccounts()) { try { RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build(); CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build(); Executor executor = Executor.newInstance(client).use(new BasicCookieStore()); if(login(executor, account)) { checkIn(executor, account); } } catch (Exception e) { log.error("【V2EX】【" + account.getUsername() + "】签到异常", e); } } }
private boolean checkIn(Executor executor, Account account) throws ClientProtocolException, IOException, URISyntaxException, InterruptedException { String usrename = account.getUsername(); String rtn = executor.execute(appendTimeOuts(Request.Get(CHECK_IN_URL))).returnContent().asString(); if(StringUtils.contains(rtn, "fa-ok-sign")) { log.info("【V2EX】【{}】每日登录奖励已领取,当前账户余额:{}", usrename, getBalance(rtn)); return true; } Elements element = Jsoup.parse(rtn).getElementsByAttributeValueMatching("onclick", "/mission/daily/redeem"); String once = StringUtils.substringBetween(element.attr("onclick"), "'", "'"); if(StringUtils.isNotEmpty(once)) { String url = "http://www.v2ex.com" + once; String checkInRtn = executor.execute(appendTimeOuts(Request.Get(url)).userAgent(USER_AGENT).addHeader("Referer", CHECK_IN_URL)).returnContent().asString(); log.info("【V2EX】【{}】签到成功,当前账户余额:{}", usrename, getBalance(checkInRtn)); return true; } log.info("【V2EX】【{}】签到成功", usrename); return false; }
private boolean login(Executor executor, Account account) throws ClientProtocolException, IOException, URISyntaxException { String usrename = account.getUsername(); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("username", usrename)); formParams.add(new BasicNameValuePair("password", account.getPassword())); formParams.add(new BasicNameValuePair("rememberme", "on")); formParams.add(new BasicNameValuePair("captcha", "")); formParams.add(new BasicNameValuePair("redirect_url", "http://www.smzdm.com")); String loginJson = executor.execute(appendTimeOuts(Request.Post(LOGIN_URL)).bodyForm(formParams)).returnContent().asString(); JSONObject loginJsonParseObject = JSON.parseObject(loginJson); if(0 != loginJsonParseObject.getInteger("error_code")) { log.info("【SMZDM】【{}】登录失败:{}", usrename, loginJsonParseObject.getString("error_msg")); return false; } log.info("【SMZDM】【{}】登录成功", usrename); return true; }
private boolean checkIn(Executor executor, Account account) throws ClientProtocolException, IOException, URISyntaxException { String usrename = account.getUsername(); URI checkInURI = new URIBuilder(CHECK_IN_URL). addParameter("_", System.currentTimeMillis() + ""). build(); String signInJson = executor.execute(appendTimeOuts(Request.Get(checkInURI))).returnContent().asString(); JSONObject signInParseObject = JSON.parseObject(signInJson); if(0 != signInParseObject.getInteger("error_code")) { log.info("【SMZDM】【{}】签到失败:{}", usrename, signInParseObject.getString("error_msg")); return false; } log.info("【SMZDM】【{}】签到成功", usrename); return true; }
@Scheduled(cron = "0 0 5,18 * * ?") public void run() { for (Account account : getAccounts()) { try { CloseableHttpClient client = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build(); Executor executor = Executor.newInstance(client).use(new BasicCookieStore()); String token = login(executor, account); if(StringUtils.isNotEmpty(token)) { if(checkIn(executor, account, token)) { // lottery(executor, account, token); } } } catch (Exception e) { log.error("【SMZDM】【" + account.getUsername() + "】签到异常", e); } } }
private boolean login(Executor executor, Account account) throws ClientProtocolException, IOException { // 1st load first page, 313932302c31303830 = stringToHex("1920,1080") executor.execute(appendTimeOuts(Request.Get(URL))).discardContent(); executor.execute(appendTimeOuts(Request.Get(URL + "?security_verify_data=313932302c31303830"))).discardContent(); String usrename = account.getUsername(); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("account", usrename)); formParams.add(new BasicNameValuePair("password", account.getPassword())); formParams.add(new BasicNameValuePair("remember", "0")); formParams.add(new BasicNameValuePair("url_back", URL)); String loginJson = executor.execute(appendTimeOuts(Request.Post(LOGIN_URL)).bodyForm(formParams)).returnContent().asString(); JSONObject loginJsonParseObject = JSON.parseObject(loginJson); if(1 != loginJsonParseObject.getInteger("status")) { log.info("【ZIMUZU】【{}】登录失败:{}", usrename, loginJsonParseObject.getString("info")); return false; } log.info("【ZIMUZU】【{}】登录成功", usrename); return true; }
private boolean signIn(Executor executor, Account account) throws ClientProtocolException, IOException, InterruptedException { // String usrename = account.getUsername(); executor.execute(appendTimeOuts(Request.Get(URL))).discardContent(); executor.execute(appendTimeOuts(Request.Get("http://www.zimuzu.tv/public/hotkeyword"))).discardContent(); executor.execute(appendTimeOuts(Request.Get("http://www.zimuzu.tv/user/login/getCurUserTopInfo"))).discardContent(); // String rtn = executor.execute(appendTimeOuts(Request.Get(SIGN_IN_URL))).returnContent().asString(); // if (StringUtils.contains(rtn, "您今天已登录")) { // log.info("【ZIMUZU】【{}】签到成功", usrename); // return true; // } // // log.info("【ZIMUZU】【{}】签到失败", usrename); return false; }
@BeforeClass public static void setUpClass() throws Exception { conf = new Configuration(CONF_FILE_PATH); MongoDBClientSingleton.init(conf); mongoClient = MongoDBClientSingleton.getInstance().getClient(); BASE_URL = "http://" + conf.getHttpHost() + ":" + conf.getHttpPort(); createURIs(); final String host = MONGO_HOST; final int port = conf.getHttpPort(); adminExecutor = Executor.newInstance().authPreemptive(new HttpHost(host, port, HTTP)).auth(new HttpHost(host), "admin", "changeit"); user1Executor = Executor.newInstance().authPreemptive(new HttpHost(host, port, HTTP)).auth(new HttpHost(host), "user1", "changeit"); user2Executor = Executor.newInstance().authPreemptive(new HttpHost(host, port, HTTP)).auth(new HttpHost(host), "user2", "changeit"); unauthExecutor = Executor.newInstance(); }
public void reload(boolean initial) { if ( initial ) { Runnable onChange = new Runnable() { @Override public void run() { reload(false); } }; INDEX_URL.addCallback(onChange); INDEX_USER.addCallback(onChange); INDEX_PASS.addCallback(onChange); } log.info("Using docker index url [{}] and user [{}]", INDEX_URL.get(), INDEX_USER.get()); Executor executor = Executor.newInstance(); if ( ! StringUtils.isBlank(INDEX_USER.get()) ) { executor = executor.auth(INDEX_USER.get(), INDEX_PASS.get()); } this.executor = executor; }
public WatsonUserModeller() { try { String VCAP_SERVICES = System.getenv("VCAP_SERVICES"); JSONObject vcap; vcap = (JSONObject) JSONObject.parse(VCAP_SERVICES); watson = (JSONArray) vcap.get("personality_insights"); watsonInstance = (JSONObject) watson.get(0); watsonCredentials = (JSONObject) watsonInstance.get("credentials"); } catch (IOException e) { e.printStackTrace(); } this.username = (String) watsonCredentials.get("username"); this.password = (String) watsonCredentials.get("password"); this.base_url = (String) watsonCredentials.get("url"); this.profile_api = Config.WATSON_PROF_API; this.visual_api = Config.WATSON_VIZ_API; this.executor = Executor.newInstance().auth(username, password); if (this.executor == null) { System.err.println("Authentication failed in WatsonUserModeller."); } }
private Executor executor() { if (executor == null) { if (this.host.startsWith("https://")) { try { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, (chain, authType) -> true) .build(); builder.setSSLContext(sslContext); builder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE); } catch (Exception ex) { Throwables.propagate(ex); } } client = builder.build(); executor = Executor.newInstance(client); if (creds != null) { executor.auth(creds); } } return executor; }
private Executor createHttpExecutor() throws MailetException { try { URIBuilder uriBuilder = new URIBuilder(serviceUrl); HttpHost host = new HttpHost(uriBuilder.getHost(), uriBuilder.getPort(), uriBuilder.getScheme()); return Executor.newInstance() .authPreemptive(host) .auth(host, new UsernamePasswordCredentials(serviceUsername, servicePassword)); } catch (URISyntaxException e) { throw new MailetException("invalid 'serviceUrl'", e); } }
/** * Initializes an http communication session with the application. */ public ApplicationSession authenticate(Application application) { String uri = application.makeHostnameUri() + "/" + DbFreezeRest.POST_LOGIN; Executor httpExecutor = executorFactory.makeExecutor(); CookieStore cookieStore = new BasicCookieStore(); httpExecutor.cookieStore(cookieStore); NameValuePair[] authParams = new NameValuePair[] { new BasicNameValuePair(PARAMNAME_AUTHUSERNAME, applicationUsername), new BasicNameValuePair(PARAMNAME_AUTHPASSWORD, applicationPassword) }; httpHelper.postAuthForCookie(httpExecutor, uri, authParams); return new ApplicationSession(httpExecutor, cookieStore); }
/** * Posts the authentication parameters to the given uri and validates the response cookie. * Returns silently if successful, else throws. */ public void postAuthForCookie(Executor executor, String uri, NameValuePair[] authParams) { try { Request request = Request.Post(uri).bodyForm(authParams); HttpResponse httpResponse = executor.execute(request).returnResponse(); int statusCode = httpResponse.getStatusLine().getStatusCode(); Header cookieHeader = null; String body = null; if (200 <= statusCode && statusCode < 400) { cookieHeader = httpResponse.getFirstHeader(HEADERNAME_SET_COOKIE); if (cookieHeader != null && StringUtils.isNotBlank(cookieHeader.getValue())) { body = EntityUtils.toString(httpResponse.getEntity()); LoginResult result = gson.fromJson(body, LoginResult.class); if (result != null && result.isLoggedIn()) { return; //success } } } throw new RuntimeException("Failed to obtain response cookie from uri " + uri + ", statusCode: " + statusCode + ", cookieHeader: " + cookieToString(cookieHeader) + ", body: " + body); //Note: if cookieStore already has valid cookie then response won't return a new cookie } catch (IOException e) { throw new RuntimeException("POST uri: " + uri + ", authParams", e); } }
/** * PUTs a uri (no content body) in an existing session, returns the response body as a string. */ public String executePut(final Executor executor, final String uri) { try { return executor.execute(Request.Put(uri)).returnContent().toString(); } catch (IOException e) { throw new RuntimeException("PUT uri: " + uri, e); } }
/** * GETs a uri in an existing session, returns the response body as a string. */ public String executeGet(Executor executor, String uri) { try { return executor.execute(Request.Get(uri)).returnContent().toString(); } catch (IOException e) { throw new RuntimeException("GET uri: " + uri, e); } }
public static Executor createExecutor(CookieStore cookieStore) { @SuppressWarnings("deprecation") final Registry<CookieSpecProvider> cookieSpecRegistry = RegistryBuilder.<CookieSpecProvider>create().register(CookieSpecs.DEFAULT, new BrowserCompatSpecFactory()).build(); final CloseableHttpClient client = HttpClients.custom() .setDefaultCookieSpecRegistry(cookieSpecRegistry) .setDefaultCookieStore(cookieStore) .build(); return Executor.newInstance(client); }
public static Content loadManifest(String folder, String owner, String repo) throws IOException { String projecUrl = "https://api.github.com/repos/"+owner+"/"+repo; String title = null; log.debug("Tentative de connexion à l'url : "+projecUrl); String githubUser = System.getProperty("zw.github_user"); String githubToken = System.getProperty("zw.github_token"); Executor executor; if(githubUser != null && !"".equals(githubUser) && githubToken != null && !"".equals(githubToken)) { executor = Executor .newInstance() .auth(new HttpHost("api.github.com"), githubUser, githubToken); } else { executor = Executor.newInstance(); } String json = executor.execute(Request.Get(projecUrl)).returnContent().asString(); ObjectMapper mapper = new ObjectMapper(); Map map = mapper.readValue(json, Map.class); if(map.containsKey("description")) { title = (String) map.get("description"); } Content current = new Content("container", toSlug(title), title, Constant.DEFAULT_INTRODUCTION_FILENAME, Constant.DEFAULT_CONCLUSION_FILENAME, new ArrayList<>(), 2, "CC-BY", title, "TUTORIAL"); // read all directory current.getChildren ().addAll (loadDirectory (folder.length () + File.separator.length (), new File(folder))); current.setBasePath (folder); generateMetadataAttributes(current.getFilePath()); return current; }
/** * Gets a Executor object. The Executor object allows to cache the authentication data. * If it was not initialized, the method instantiates one. * * @return an initialized Executor object */ private Executor getExecutor() { if (this.executor == null) { HttpHost httpHost = new HttpHost(this.gogsServer_nodeName, this.gogsServer_port); this.executor = Executor.newInstance() .auth(httpHost, this.gogsServer_user, this.gogsServer_password) .authPreemptive(httpHost); } return this.executor; }
public static HttpResponse invokeRequest(Request request, String username, String password, boolean useSSL) throws ClientProtocolException, IOException, KeyManagementException, NoSuchAlgorithmException { Executor executor = getExecutor(useSSL); executor = executor.auth(username, password); HttpResponse httpResponse = invokeRequest(request, executor); return httpResponse; }
private static Executor getExecutor(boolean useSSL) throws KeyManagementException, NoSuchAlgorithmException { Executor executor = null; if (useSSL){ executor = Executor.newInstance(Utility.getTrustedHttpClient()); } else{ executor = Executor.newInstance(); } return executor; }
@Test public void testBasicAuth() throws JSONException, IOException, CredentialInvalidException { stubBasicAuth(); Executor exec = newExecutor(); LoginHandler handler = new LoginHandler(dataBasic, correct, null); handler.handleLogin(exec, null); // loading page should succeed int status = exec.execute(Request.Get(baseurl + "/index.html")).returnResponse().getStatusLine() .getStatusCode(); assertEquals(200, status); }
@Test public void testBasicAuthFail() throws JSONException, IOException, CredentialInvalidException { stubBasicAuth(); Executor exec = newExecutor(); LoginHandler handler = new LoginHandler(dataBasic, wrong, null); handler.handleLogin(exec, null); // loading page should succeed int status = exec.execute(Request.Get(baseurl + "/index.html")).returnResponse().getStatusLine() .getStatusCode(); assertEquals(401, status); }
@Test(expected = CredentialInvalidException.class) public void testBasicAuthFailUrl() throws JSONException, IOException, CredentialInvalidException { stubBasicAuth(); Executor exec = newExecutor(); LoginHandler handler = new LoginHandler(dataBasicUrl, wrong, null); handler.handleLogin(exec, null); }
@Test public void testPostAuth() throws JSONException, IOException, CredentialInvalidException { stubPostAuth(); Executor exec = newExecutor(); LoginHandler handler = new LoginHandler(dataPost, correct, null); handler.handleLogin(exec, null); // loading page should succeed String content = exec.execute(Request.Get(baseurl + "/index.html")).returnContent().asString(); assertEquals("content", content); }
@Test public void testPostAuthFail() throws JSONException, IOException, CredentialInvalidException { stubPostAuth(); Executor exec = newExecutor(); LoginHandler handler = new LoginHandler(dataPost, wrong, null); handler.handleLogin(exec, null); // loading page should fail String content = exec.execute(Request.Get(baseurl + "/index.html")).returnContent().asString(); assertEquals("please login", content); }
@Test(expected = CredentialInvalidException.class) public void testPostAuthFailCheckText() throws JSONException, IOException, CredentialInvalidException { stubPostAuth(); Executor exec = newExecutor(); LoginHandler handler = new LoginHandler(dataPostCheckText, wrong, null); handler.handleLogin(exec, null); // should throw CredentialInvalidException }
@Test(expected = CredentialInvalidException.class) public void testPostAuthFailCheckUrl() throws JSONException, IOException, CredentialInvalidException { stubPostAuth(); Executor exec = newExecutor(); LoginHandler handler = new LoginHandler(dataPostCheckUrl, wrong, null); handler.handleLogin(exec, null); // should throw CredentialInvalidException }
@Test public void testPostAuthFormData() throws JSONException, IOException, CredentialInvalidException { stubPostAuthFormData(); Executor exec = newExecutor(); LoginHandler handler = new LoginHandler(dataPostFormData, correct, null); handler.handleLogin(exec, null); // loading page should succeed String content = exec.execute(Request.Get(baseurl + "/index.html")).returnContent().asString(); assertEquals("content", content); }
public WebreportsAPI(HttpClient apacheHttpClient,URI uri, String username, String password) throws JAXBException, Exception { this.baseURI = uri; client = Executor.newInstance(apacheHttpClient); this.username = username; this.password = password; initializeJAXB(); }
public ConsulFacadeBean(final String consulUrl, final Optional<String> username, final Optional<String> password, final int ttlInSeconds, final int lockDelayInSeconds, final boolean allowIslandMode, final int createSessionTries, final int retryPeriod, final double backOffMultiplier) throws MalformedURLException { this(consulUrl, username, password, Executor.newInstance()); this.ttlInSeconds = ttlInSeconds; this.lockDelayInSeconds = lockDelayInSeconds; this.createSessionTries = createSessionTries; this.retryPeriod = retryPeriod; this.backOffMultiplier = backOffMultiplier; }