List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider
public synchronized final CredentialsProvider getCredentialsProvider()
From source file:com.marklogic.client.functionaltest.ConnectedRESTQA.java
public static void createRESTUserWithPermissions(String usrName, String pass, ObjectNode perm, ObjectNode colections, String... roleNames) { try {//from www .ja v a 2 s. co m DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); HttpGet getrequest = new HttpGet("http://localhost:8002" + "/manage/v2/users/" + usrName); HttpResponse resp = client.execute(getrequest); if (resp.getStatusLine().getStatusCode() == 200) { System.out.println("User already exist"); } else { System.out.println("User dont exist"); client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); ObjectMapper mapper = new ObjectMapper(); ObjectNode mainNode = mapper.createObjectNode(); // ObjectNode childNode = mapper.createObjectNode(); ArrayNode childArray = mapper.createArrayNode(); mainNode.put("user-name", usrName); mainNode.put("description", "user discription"); mainNode.put("password", pass); for (String rolename : roleNames) childArray.add(rolename); mainNode.withArray("role").addAll(childArray); mainNode.setAll(perm); mainNode.setAll(colections); //System.out.println(type + mainNode.path("range-element-indexes").path("range-element-index").toString()); System.out.println(mainNode.toString()); HttpPost post = new HttpPost("http://localhost:8002" + "/manage/v2/users?format=json"); post.addHeader("Content-type", "application/json"); post.setEntity(new StringEntity(mainNode.toString())); HttpResponse response = client.execute(post); HttpEntity respEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 400) { System.out.println("Bad User creation request"); } else if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); System.out.println(content); } else { System.out.println("No Proper Response"); } } } catch (Exception e) { // writing error to Log e.printStackTrace(); } }
From source file:com.marklogic.client.functionaltest.ConnectedRESTQA.java
public static void setDatabaseProperties(String dbName, String propName, ObjectNode objNode) throws IOException { InputStream jsonstream = null; try {/*from w w w . j a va 2s .c o m*/ DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); HttpGet getrequest = new HttpGet( "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json"); HttpResponse response1 = client.execute(getrequest); jsonstream = response1.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); JsonNode jnode = mapper.readTree(jsonstream); if (!jnode.isNull()) { if (!jnode.has(propName)) { ((ObjectNode) jnode).putArray(propName).addAll(objNode.withArray(propName)); // System.out.println("when Node is null"+propName + objNode.toString()); } else { if (!jnode.path(propName).isArray()) { System.out.println("property is not array"); ((ObjectNode) jnode).putAll(objNode); } else { JsonNode member = jnode.withArray(propName); if (objNode.path(propName).isArray()) { ((ArrayNode) member).addAll(objNode.withArray(propName)); // System.out.println("when Node is not null"+ propName + objNode.withArray(propName).toString()); } } } HttpPut put = new HttpPut( "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(jnode.toString())); HttpResponse response2 = client.execute(put); HttpEntity respEntity = response2.getEntity(); if (respEntity != null) { String content = EntityUtils.toString(respEntity); System.out.println(content); } } else { System.out.println("REST call for database properties returned NULL \n" + jnode.toString() + "\n" + response1.getStatusLine().getStatusCode()); } } catch (Exception e) { // writing error to Log e.printStackTrace(); } finally { if (jsonstream == null) { } else { jsonstream.close(); } } }
From source file:com.marklogic.client.functionaltest.ConnectedRESTQA.java
public static void setDatabaseFieldProperties(String dbName, String field_name, String propName, ObjectNode objNode) throws IOException { InputStream jsonstream = null; try {//w w w .j a v a 2 s . c o m DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); HttpGet getrequest = new HttpGet( "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json"); HttpResponse response1 = client.execute(getrequest); jsonstream = response1.getEntity().getContent(); ObjectMapper mapper = new ObjectMapper(); JsonNode jnode = mapper.readTree(jsonstream); if (!jnode.isNull() && jnode.has("field")) { JsonNode fieldNode = jnode.withArray("field"); Iterator<JsonNode> fnode = fieldNode.elements(); while (fnode.hasNext()) { JsonNode fnchild = fnode.next(); if ((fnchild.path("field-name").asText()).equals(field_name)) { // System.out.println("Hurray" +fnchild.has(propName)); if (!fnchild.has(propName)) { ((ObjectNode) fnchild).putArray(propName).addAll(objNode.withArray(propName)); // System.out.println("Adding child array include node" + jnode.toString()); } else { JsonNode member = fnchild.withArray(propName); ((ArrayNode) member).addAll(objNode.withArray(propName)); } } } HttpPut put = new HttpPut( "http://localhost:8002" + "/manage/v2/databases/" + dbName + "/properties?format=json"); put.addHeader("Content-type", "application/json"); put.setEntity(new StringEntity(jnode.toString())); HttpResponse response2 = client.execute(put); HttpEntity respEntity = response2.getEntity(); if (respEntity != null) { String content = EntityUtils.toString(respEntity); System.out.println(content); } } else { System.out.println("REST call for database properties returned NULL \n" + jnode.toString() + "\n" + response1.getStatusLine().getStatusCode()); } } catch (Exception e) { // writing error to Log e.printStackTrace(); } finally { if (jsonstream == null) { } else { jsonstream.close(); } } }
From source file:org.talend.mdm.repository.ui.wizards.imports.ImportServerObjectWizard.java
private WSWorkflowE handleWorkflowObject(TreeObject treeObj) throws IOException, ClientProtocolException, UnsupportedEncodingException { // WSWorkflowProcessDefinitionUUID wsKey = (WSWorkflowProcessDefinitionUUID) treeObj.getWsKey(); String workflowURL = treeObj.getEndpointIpAddress() + TreeObject.BARFILE_URI + treeObj.getDisplayName(); // correct the URL to Bonita 5.8 version Pattern PATTERN_53 = Pattern.compile("(.+?)_(\\d+\\.\\d+)"); Matcher matcher = PATTERN_53.matcher(workflowURL); if (matcher.matches()) { workflowURL = matcher.group(1) + "--" + matcher.group(2); }//from w ww. java2 s . co m DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getCredentialsProvider().setCredentials( new AuthScope(treeObj.getEndpointHost(), Integer.valueOf(treeObj.getEndpointPort())), new UsernamePasswordCredentials(treeObj.getUsername(), treeObj.getPassword())); HttpGet httpget = new HttpGet(workflowURL); // System.out.println("executing request" + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String encodedID = URLEncoder.encode(treeObj.getDisplayName(), UTF8); File tempFolder = IOUtil.getWorkspaceTempFolder(); String filename = tempFolder.getAbsolutePath() + File.separator + encodedID + ".bar";//$NON-NLS-1$ InputStream is = entity.getContent(); OutputStream os = null; File barFile = new File(filename); try { os = new FileOutputStream(barFile); int copy = IOUtils.copy(is, os); } catch (Exception e) { log.error(e.getMessage(), e); return null; } finally { if (is != null) { try { is.close(); } catch (Exception e) { } } if (os != null) { try { os.close(); } catch (Exception e) { } } } if (barFile.exists()) { try { byte[] procBytes = extractBar(barFile); if (procBytes != null) { WSWorkflowE workflow = MdmserverobjectFactory.eINSTANCE.createWSWorkflowE(); // workflow.setName(wsKey.getProcessName()); workflow.setName(treeObj.getName()); workflow.setFileContent(procBytes); return workflow; } } finally { IOUtil.cleanFolder(tempFolder); } } } return null; }
From source file:com.marklogic.client.functionaltest.ConnectedRESTQA.java
public static void createUserRolesWithPrevilages(String roleName, String... privNames) { try {//from w ww .java2 s . c o m DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); HttpGet getrequest = new HttpGet("http://localhost:8002/manage/v2/roles/" + roleName); HttpResponse resp = client.execute(getrequest); if (resp.getStatusLine().getStatusCode() == 200) { System.out.println("Role already exist"); } else { System.out.println("Role dont exist, will create now"); String[] roleNames = { "rest-reader", "rest-writer" }; client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); ObjectMapper mapper = new ObjectMapper(); ObjectNode mainNode = mapper.createObjectNode(); ArrayNode roleArray = mapper.createArrayNode(); ArrayNode privArray = mapper.createArrayNode(); ArrayNode permArray = mapper.createArrayNode(); mainNode.put("role-name", roleName); mainNode.put("description", "role discription"); for (String rolename : roleNames) roleArray.add(rolename); mainNode.withArray("role").addAll(roleArray); for (String privName : privNames) { ObjectNode privNode = mapper.createObjectNode(); privNode.put("privilege-name", privName); privNode.put("action", "http://marklogic.com/xdmp/privileges/" + privName.replace(":", "-")); privNode.put("kind", "execute"); privArray.add(privNode); } mainNode.withArray("privilege").addAll(privArray); permArray.add(getPermissionNode(roleNames[0], Capability.READ).get("permission").get(0)); permArray.add(getPermissionNode(roleNames[1], Capability.READ).get("permission").get(0)); permArray.add(getPermissionNode(roleNames[1], Capability.EXECUTE).get("permission").get(0)); permArray.add(getPermissionNode(roleNames[1], Capability.UPDATE).get("permission").get(0)); mainNode.withArray("permission").addAll(permArray); System.out.println(mainNode.toString()); HttpPost post = new HttpPost("http://localhost:8002" + "/manage/v2/roles?format=json"); post.addHeader("Content-type", "application/json"); post.setEntity(new StringEntity(mainNode.toString())); HttpResponse response = client.execute(post); HttpEntity respEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 400) { System.out.println("creation of role got a problem"); } else if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); System.out.println(content); } else { System.out.println("No Proper Response"); } } } catch (Exception e) { // writing error to Log e.printStackTrace(); } }
From source file:com.marklogic.client.functionaltest.ConnectedRESTQA.java
public static void addElementRangeIndexTemporalAxis(String dbName, String axisName, String namespaceStart, String localnameStart, String namespaceEnd, String localnameEnd) throws Exception { /**//from ww w. java2s . com { "axis-name": "eri-json-system", "axis-start": { "element-reference": { "namespace-uri": "", "localname": "eri-system-start", "scalar-type": "dateTime" } }, "axis-end": { "element-reference": { "namespace-uri": "", "localname": "eri-system-end", "scalar-type": "dateTime" } } } */ ObjectMapper mapper = new ObjectMapper(); ObjectNode rootNode = mapper.createObjectNode(); rootNode.put("axis-name", axisName); // Set axis start ObjectNode axisStart = mapper.createObjectNode(); ObjectNode elementReferenceStart = mapper.createObjectNode(); elementReferenceStart.put("namespace-uri", namespaceStart); elementReferenceStart.put("localname", localnameStart); elementReferenceStart.put("scalar-type", "dateTime"); axisStart.set("element-reference", elementReferenceStart); rootNode.set("axis-start", axisStart); // Set axis end ObjectNode axisEnd = mapper.createObjectNode(); ObjectNode elementReferenceEnd = mapper.createObjectNode(); elementReferenceEnd.put("namespace-uri", namespaceStart); elementReferenceEnd.put("localname", localnameEnd); elementReferenceEnd.put("scalar-type", "dateTime"); axisEnd.set("element-reference", elementReferenceEnd); rootNode.set("axis-end", axisEnd); System.out.println(rootNode.toString()); DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002), new UsernamePasswordCredentials("admin", "admin")); HttpPost post = new HttpPost( "http://localhost:8002/manage/v2/databases/" + dbName + "/temporal/axes?format=json"); post.addHeader("Content-type", "application/json"); post.addHeader("accept", "application/json"); post.setEntity(new StringEntity(rootNode.toString())); HttpResponse response = client.execute(post); HttpEntity respEntity = response.getEntity(); if (response.getStatusLine().getStatusCode() == 400) { HttpEntity entity = response.getEntity(); String responseString = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseString); } else if (respEntity != null) { // EntityUtils to get the response content String content = EntityUtils.toString(respEntity); System.out.println(content); System.out.println("Temporal axis: " + axisName + " created"); System.out.println("=============================================================="); } else { System.out.println("No Proper Response"); } }
From source file:org.oscarehr.fax.admin.ManageFaxes.java
public ActionForward CancelFax(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {/*w w w . ja v a2 s.c o m*/ String jobId = request.getParameter("jobId"); if (!securityInfoManager.hasPrivilege(LoggedInInfo.getLoggedInInfoFromSession(request), "_admin", "w", null)) { throw new SecurityException("missing required security object (_admin)"); } FaxJobDao faxJobDao = SpringUtils.getBean(FaxJobDao.class); FaxConfigDao faxConfigDao = SpringUtils.getBean(FaxConfigDao.class); FaxJob faxJob = faxJobDao.find(Integer.parseInt(jobId)); FaxConfig faxConfig = faxConfigDao.getConfigByNumber(faxJob.getFax_line()); DefaultHttpClient client = new DefaultHttpClient(); String result = "{success:false}"; log.info("TRYING TO CANCEL FAXJOB " + faxJob.getJobId()); if (faxConfig.isActive()) { if (faxJob.getStatus().equals(FaxJob.STATUS.SENT)) { faxJob.setStatus(FaxJob.STATUS.CANCELLED); faxJobDao.merge(faxJob); result = "{success:true}"; } if (faxJob.getJobId() != null) { if (faxJob.getStatus().equals(FaxJob.STATUS.WAITING)) { client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(faxConfig.getSiteUser(), faxConfig.getPasswd())); HttpPut mPut = new HttpPut(faxConfig.getUrl() + "/fax/" + faxJob.getJobId()); mPut.setHeader("accept", "application/json"); mPut.setHeader("user", faxConfig.getFaxUser()); mPut.setHeader("passwd", faxConfig.getFaxPasswd()); try { HttpResponse httpResponse = client.execute(mPut); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); result = EntityUtils.toString(httpEntity); faxJob.setStatus(FaxJob.STATUS.CANCELLED); faxJobDao.merge(faxJob); } } catch (ClientProtocolException e) { log.error("PROBLEM COMM WITH WEB SERVICE"); } catch (IOException e) { log.error("PROBLEM COMM WITH WEB SERVICE"); } } } } try { JSONObject json = JSONObject.fromObject(result); json.write(response.getWriter()); } catch (IOException e) { log.error(e.getMessage(), e); } return null; }
From source file:de.unioninvestment.eai.portal.portlet.crud.domain.model.authentication.Realm.java
/** * Applies credentials to target {@link HttpClient} with Basic * Authentication (PLEASE ONLY USE THIS TOGETHER WITH SSL). * //from w w w. ja v a2 s.c o m * @param httpClient */ public void applyBasicAuthentication(DefaultHttpClient httpClient) { String username = null; String password = null; Cryptor cryptor = null; PortletPreferences preferences = VaadinPortletService.getCurrentPortletRequest().getPreferences(); CredentialsConfig credentials = config.getCredentials(); String usernameKey = credentials.getUsername().getPreferenceKey(); if (usernameKey != null) { username = preferences.getValue(usernameKey, null); } String passwordKey = credentials.getPassword().getPreferenceKey(); if (passwordKey != null) { password = preferences.getValue(passwordKey, null); } String encryptionAlgorithm = credentials.getPassword().getEncryptionAlgorithm(); if (encryptionAlgorithm != null) { cryptor = cryptorFactory.getCryptor(encryptionAlgorithm); } String plaintextPassword = cryptor == null ? password : cryptor.decrypt(password); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, plaintextPassword)); }
From source file:password.pwm.http.client.PwmHttpClient.java
public static HttpClient getHttpClient(final Configuration configuration, final PwmHttpClientConfiguration pwmHttpClientConfiguration) throws PwmUnrecoverableException { final DefaultHttpClient httpClient; try {/* w w w . j a va 2 s.c o m*/ if (Boolean.parseBoolean(configuration.readAppProperty(AppProperty.SECURITY_HTTP_PROMISCUOUS_ENABLE))) { httpClient = new DefaultHttpClient(makeConnectionManager(new X509Utils.PromiscuousTrustManager())); } else if (pwmHttpClientConfiguration != null && pwmHttpClientConfiguration.getCertificates() != null) { final TrustManager trustManager = new X509Utils.CertMatchingTrustManager(configuration, pwmHttpClientConfiguration.getCertificates()); httpClient = new DefaultHttpClient(makeConnectionManager(trustManager)); } else { httpClient = new DefaultHttpClient(); } } catch (Exception e) { throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_UNKNOWN, "unexpected error creating promiscuous https client: " + e.getMessage())); } final String strValue = configuration.readSettingAsString(PwmSetting.HTTP_PROXY_URL); if (strValue != null && strValue.length() > 0) { final URI proxyURI = URI.create(strValue); final String host = proxyURI.getHost(); final int port = proxyURI.getPort(); final HttpHost proxy = new HttpHost(host, port); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); final String username = proxyURI.getUserInfo(); if (username != null && username.length() > 0) { final String password = (username.contains(":")) ? username.split(":")[1] : ""; final UsernamePasswordCredentials passwordCredentials = new UsernamePasswordCredentials(username, password); httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), passwordCredentials); } } final String userAgent = PwmConstants.PWM_APP_NAME + " " + PwmConstants.SERVLET_VERSION; httpClient.getParams().setParameter(HttpProtocolParams.USER_AGENT, userAgent); return httpClient; }
From source file:org.miloss.fgsms.bueller.Bueller.java
/** * attempts an http get request with authentication * * @param pooled/*from www . j a va 2 s .c om*/ * @param endpoint * @param policyURL * @return */ protected String sendGetRequestAuth(boolean pooled, String endpoint, String policyURL, int depth) {//, AuthMode mode) { if (depth > 10) { //abort, possible redirect loop return "Aborting due to redirect loop"; } String[] info = DBSettingsLoader.GetCredentials(pooled, policyURL); if (info == null) { info = DBSettingsLoader.GetDefaultBuellerCredentials(pooled); if (info == null) { return "Unauthorized, no credentials are available"; } } if (endpoint.startsWith("http://")) { // Send a GET request to the servlet DefaultHttpClient c = new DefaultHttpClient(); try { c.getCredentialsProvider().setCredentials(AuthScope.ANY, transformCredentials(info)); if (!c.getCredentialsProvider().getCredentials(AuthScope.ANY).getClass().getCanonicalName().equalsIgnoreCase(NTCredentials.class.getCanonicalName())) { log.log(Level.WARN, "Usage of non-NTLM authentication over a non SSL channel."); } HttpGet m = new HttpGet(endpoint); HttpResponse res = c.execute(m); int status = res.getStatusLine().getStatusCode(); try { InputStream content = res.getEntity().getContent(); byte[] buffer = new byte[1024]; while (content.read(buffer) >= 0) { } } catch (Exception f) { } c.getConnectionManager().shutdown(); if (status < 300 || status == HttpStatus.SC_NOT_MODIFIED) { return "OK"; } else if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_TEMPORARILY) { String newUrl = res.getHeaders("Location")[0].getValue(); return sendGetRequestAuth(pooled, newUrl, policyURL, depth + 1); } return String.valueOf(status); } catch (Exception ex) { c.getConnectionManager().shutdown(); log.log(Level.INFO, "code " + ex.getLocalizedMessage()); return "offline: " + ex.getMessage(); } } else if (endpoint.startsWith("https://")) { //first try with the username/password over ssl if (sf == null && sfpki == null) { return "Unauthorized, no trust store available for SSL communication"; } DefaultHttpClient c = new DefaultHttpClient(); try { URL url = new URL(endpoint); String scheme = "https"; int port = url.getPort(); if (port == -1 && endpoint.toLowerCase().startsWith("https:")) { port = 443; } Scheme sch = null; if (sfpki == null) { sch = new Scheme("https", port, sf); } else { sch = new Scheme("https", port, sfpki); } c.getConnectionManager().getSchemeRegistry().register(sch); c.getCredentialsProvider().setCredentials(AuthScope.ANY, transformCredentials(info)); HttpGet m = new HttpGet(endpoint); HttpResponse res = c.execute(m); int status = res.getStatusLine().getStatusCode(); try { InputStream content = res.getEntity().getContent(); byte[] buffer = new byte[1024]; while (content.read(buffer) >= 0) { } } catch (Exception f) { } c.getConnectionManager().shutdown(); if (status < 300 || status == HttpStatus.SC_NOT_MODIFIED) { return "OK"; } else if (status == HttpStatus.SC_MOVED_PERMANENTLY || status == HttpStatus.SC_TEMPORARY_REDIRECT || status == HttpStatus.SC_MOVED_TEMPORARILY) { String newUrl = res.getHeaders("Location")[0].getValue(); return sendGetRequestAuth(pooled, newUrl, policyURL, depth + 1); } return String.valueOf(status); } catch (Exception ex) { c.getConnectionManager().shutdown(); log.log(Level.INFO, "code " + ex.getLocalizedMessage()); return "offline: " + ex.getMessage(); } } else { return "undeterminable"; } }