// TEIID-3914 - test the olingo-patch work public void testCompositeKeyTimestamp() throws Exception { String vdb = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<vdb name=\"northwind\" version=\"1\">\n" + " <model name=\"m\">\n" + " <source name=\"x1\" translator-name=\"loopback\" />\n" + " <metadata type=\"DDL\"><![CDATA[\n" + " CREATE FOREIGN TABLE x (a string, b timestamp, c integer, primary key (a, b)) options (updatable true);\n" + " ]]> </metadata>\n" + " </model>\n" + "</vdb>"; admin.deploy( "loopy-vdb.xml", new ReaderInputStream(new StringReader(vdb), Charset.forName("UTF-8"))); assertTrue(AdminUtil.waitForVDBLoad(admin, "Loopy", 1, 3)); WebClient client = WebClient.create("http://localhost:8080/odata4/m/x(a='a',b=2011-09-11T00:00:00Z)"); client.header( "Authorization", "Basic " + Base64.encodeBytes(("user:user").getBytes())); // $NON-NLS-1$ //$NON-NLS-2$ Response response = client.invoke("GET", null); assertEquals(200, response.getStatus()); client = WebClient.create("http://localhost:8080/odata4/m/x"); client.header( "Authorization", "Basic " + Base64.encodeBytes(("user:user").getBytes())); // $NON-NLS-1$ //$NON-NLS-2$ response = client.post("{\"a\":\"b\", \"b\":\"2000-02-02T22:22:22Z\"}"); assertEquals(204, response.getStatus()); admin.undeploy("loopy-vdb.xml"); }
@Test public void testOdata() throws Exception { String vdb = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<vdb name=\"Loopy\" version=\"1\">\n" + " <model name=\"MarketData\">\n" + " <source name=\"text-connector2\" translator-name=\"loopback\" />\n" + " <metadata type=\"DDL\"><![CDATA[\n" + " CREATE FOREIGN TABLE G1 (e1 string, e2 integer PRIMARY KEY);\n" + " CREATE FOREIGN TABLE G2 (e1 string, e2 integer PRIMARY KEY) OPTIONS (UPDATABLE 'true');\n" + " ]]> </metadata>\n" + " </model>\n" + "</vdb>"; admin.deploy( "loopy-vdb.xml", new ReaderInputStream(new StringReader(vdb), Charset.forName("UTF-8"))); assertTrue(AdminUtil.waitForVDBLoad(admin, "Loopy", 1, 3)); WebClient client = WebClient.create("http://*****:*****@mm://localhost:31000;user=user;password=user", null); PreparedStatement ps = conn.prepareCall( "select t.* from xmltable('/*:Edmx/*:DataServices/*:Schema[@Alias=\"MarketData\"]' passing xmlparse(document cast(? as clob))) as t"); ps.setAsciiStream(1, (InputStream) response.getEntity()); ResultSet rs = ps.executeQuery(); rs.next(); assertEquals( ObjectConverterUtil.convertFileToString( UnitTestUtil.getTestDataFile("loopy-metadata4-results.txt")), rs.getString(1)); conn.close(); // try an invalid url client = WebClient.create("http://localhost:8080/odata/x/y$metadata"); client.header( "Authorization", "Basic " + Base64.encodeBytes(("user:user").getBytes())); // $NON-NLS-1$ //$NON-NLS-2$ response = client.invoke("GET", null); assertEquals(500, response.getStatus()); admin.undeploy("loopy-vdb.xml"); }
public HttpDispatch( String endpoint, String configFile, @SuppressWarnings("unused") String configName) { this.endpoint = endpoint; if (configFile == null) { this.client = WebClient.create(this.endpoint); } else { this.client = WebClient.create(this.endpoint, configFile); } }
public boolean removeUserCredentialsForPaaS(String userInstanceUriId, String paaSInstanceUriId) throws SOAException { String rsUri = getBASE_URI() + "removeUserCredentialsForPaaS"; WebClient client = WebClient.create(rsUri); client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN); registerJsonProvider(); List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("userInstanceUriId", MediaType.TEXT_PLAIN, userInstanceUriId)); atts.add(new Attachment("paaSInstanceUriId", MediaType.TEXT_PLAIN, paaSInstanceUriId)); Response response = client.post(new MultipartBody(atts)); if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.ACCEPTED) { try { String responseString = IOUtils.readStringFromStream((InputStream) response.getEntity()); logger.debug("Response Status ACCEPTED - " + responseString); } catch (IOException ex) { logger.error("Error reading the REST response: " + ex.getMessage()); } return true; } return false; }
public String storeTurtleUserProfile(String userProfile, String username, String password) { String rsUri = getBASE_URI() + "createNewUserAccount"; WebClient client = WebClient.create(rsUri); client.type("multipart/mixed").accept(MediaType.TEXT_PLAIN); registerJsonProvider(); List<Attachment> atts = new LinkedList<Attachment>(); atts.add(new Attachment("userProfile", MediaType.TEXT_PLAIN, userProfile)); atts.add(new Attachment("username", MediaType.TEXT_PLAIN, username)); atts.add(new Attachment("password", MediaType.TEXT_PLAIN, password)); Response response = client.post(new MultipartBody(atts)); String userInstanceUriId = null; if (Response.Status.fromStatusCode(response.getStatus()) == Response.Status.CREATED) { try { userInstanceUriId = IOUtils.readStringFromStream((InputStream) response.getEntity()); logger.debug("Response Status CREATED - userInstanceUriId: " + userInstanceUriId); } catch (IOException ex) { logger.error("Error reading the REST response: " + ex.getMessage()); } } return userInstanceUriId; }
public NLTKNERecogniser() { try { String restHostUrlStr = ""; try { restHostUrlStr = readRestUrl(); } catch (IOException e) { e.printStackTrace(); } if (restHostUrlStr == null || restHostUrlStr.equals("")) { this.restHostUrlStr = NLTK_REST_HOST; } else { this.restHostUrlStr = restHostUrlStr; } Response response = WebClient.create(restHostUrlStr).accept(MediaType.TEXT_HTML).get(); int responseCode = response.getStatus(); if (responseCode == 200) { available = true; } else { LOG.info("NLTKRest Server is not running"); } } catch (Exception e) { LOG.debug(e.getMessage(), e); } }
private boolean initializeWebService() { WebClient client = WebClient.create("http://localhost:8080"); String init = client.path("/feelinganalyzer/analyzer/init").accept("text/plain").get(String.class); return init.compareToIgnoreCase("Dictionary loaded") == 0; }
@Test public void rest() { String response = WebClient.create("http://localhost:4204/openejb-cxf-rs") .path("/match/openejb/test/normal") .get(String.class); assertEquals("openejb", response); }
@Test public void testPing() throws Exception { WebClient client = WebClient.create(endpointUrl + "/hello/echo/SierraTangoNevada"); Response r = client.accept("text/plain").get(); assertEquals(Response.Status.OK.getStatusCode(), r.getStatus()); String value = IOUtils.toString((InputStream) r.getEntity()); assertEquals("SierraTangoNevada", value); }
private void testDELETEMethodWithJAXRSClientApi( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebClient client = WebClient.create(host); String orderId = request.getParameter("OrderId"); String orderURLPath = serviceEndPoint + "/orders/" + orderId; Response response1 = client.path(orderURLPath).delete(); printOutput(response, response1); }
@Test public void isCdi() { assertEquals( "Oh Yeah!", WebClient.create("http://localhost:" + port + "/foo") .accept("provider/type") .path("res") .get(String.class)); }
/** Creates a JAXRS web client for the given JAXRS client */ @Override protected <T> T createWebClient(Class<T> clientType) { List<Object> providers = WebClients.createProviders(); providers.add(new Authenticator()); WebClient webClient = WebClient.create(address, providers); disableSslChecks(webClient); // configureUserAndPassword(webClient, username, password); return JAXRSClientFactory.fromClient(webClient, clientType); }
private WebClient createWebClient(final String url) { return WebClient.create( "http://localhost:" + getPort() + url, Arrays.<Object>asList(new JacksonJsonProvider()), Arrays.<Feature>asList(new LoggingFeature()), null) .accept(MediaType.APPLICATION_JSON) .accept("application/yaml"); }
protected WebClient createWebClient(final String url, final String mediaType) { final List<?> providers = Arrays.asList(new JacksonJsonProvider()); final WebClient wc = WebClient.create("http://localhost:" + getPort() + url, providers).accept(mediaType); WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L); return wc; }
@Test public void isCdi() { assertEquals(2, MyCdiRESTApplication.injection.size()); for (final Boolean b : MyCdiRESTApplication.injection) { assertTrue(b); } assertEquals( "Hi from REST World!", WebClient.create("http://localhost:" + port + "/foo/").path("/first/hi").get(String.class)); }
public void testPie1() { try { String url = baseURL + "/rest/Pie/search;id=*/utensilCollection"; WebClient client = WebClient.create(url); client.type("application/xml").accept("application/xml"); Response response = client.get(); if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } File myFile = new File("Pie_Search" + "XML.xml"); System.out.println("writing data to file " + myFile.getAbsolutePath()); FileWriter myWriter = new FileWriter(myFile); BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { myWriter.write(output); System.out.println(output); } myWriter.flush(); myWriter.close(); } catch (Exception e) { e.printStackTrace(); ResponseBuilder builder = Response.status(Status.INTERNAL_SERVER_ERROR); builder.type("application/xml"); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<response>"); buffer.append("<type>ERROR</type>"); buffer.append("<code>INTERNAL_ERROR_4</code>"); buffer.append("<message>Failed to Query due to: " + e.getMessage() + "</message>"); buffer.append("</response>"); builder.entity(buffer.toString()); throw new WebApplicationException(builder.build()); } }
public void handleFileUpload(FileUploadEvent fue) { String docId = UUID.randomUUID().toString(); getDocIds().add(docId); try { IclubDocumentModel model = new IclubDocumentModel(); model.setIclubPerson(getSessionUserId()); model.setDCrtdDt(new Date(System.currentTimeMillis())); model.setDId(docId); model.setDName(fue.getFile().getFileName()); model.setDContent(fue.getFile().getContentType()); model.setDSize(fue.getFile().getSize()); WebClient client = IclubWebHelper.createCustomClient(D_BASE_URL + "add"); ResponseModel response = client.accept(MediaType.APPLICATION_JSON).post(model, ResponseModel.class); client.close(); if (response.getStatusCode() == 0) { ContentDisposition cd = new ContentDisposition( "attachment;filename=" + fue.getFile().getFileName() + ";filetype=" + fue.getFile().getContentType()); List<Attachment> attachments = new ArrayList<Attachment>(); Attachment attachment = new Attachment(docId, fue.getFile().getInputstream(), cd); attachments.add(attachment); WebClient uploadClient = WebClient.create(D_BASE_URL + "upload"); Response res = uploadClient.type("multipart/form-data").post(new MultipartBody(attachments)); uploadClient.close(); if (res.getStatus() == 200) { IclubWebHelper.addMessage( getLabelBundle().getString("doucmentuploadedsuccessfully"), FacesMessage.SEVERITY_INFO); } else { IclubWebHelper.addMessage( getLabelBundle().getString("doucmentuploadingfailed") + " :: " + (res.getHeaderString("status") != null ? res.getHeaderString("status") : res.getStatusInfo()), FacesMessage.SEVERITY_ERROR); } } } catch (Exception e) { LOGGER.error(e, e); IclubWebHelper.addMessage( getLabelBundle().getString("doucmentuploadingerror") + " :: " + e.getMessage(), FacesMessage.SEVERITY_ERROR); } }
private void testGETMethodWithJAXRSClientApi( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebClient client = WebClient.create(host); String orderId = request.getParameter("OrderId"); // Sent HTTP GET request to query customer info System.out.println("Sent HTTP GET request to query order info of " + orderId); String orderURLPath = serviceEndPoint + "/orders/" + orderId; Response response1 = client.path(orderURLPath).accept(MediaType.APPLICATION_JSON).get(); printOutput(response, response1); }
private Float getValue(String text) { Float result = 5f; WebClient client = WebClient.create("http://localhost:8080"); result = Float.valueOf( client .path("/feelinganalyzer/analyzer/tweet") .query("text", text) .accept("text/plain") .get(String.class)); return result; }
@Test @Ignore public void shit() throws Exception { WebClient client = WebClient.create("http://localhost:8080/forsendelse/service/rest/forsendelsesservice/send"); client.type("multipart/form-data"); List<Attachment> attacments = new ArrayList<Attachment>(); attacments.add( createDocumentAttachment(new File("src/test/resources/Undervisningsfritak.pdf"))); attacments.add(createForsendelsesAttachment(createForsendelse(1))); Response rs = client.post(new MultipartBody(attacments)); System.out.println(rs.getStatus()); }
public void handleMessage(Message message) throws Fault { SecurityContext context = message.get(SecurityContext.class); if (context == null) { return; } Principal principal = context.getUserPrincipal(); UsernameToken usernameToken = (UsernameToken) message.get(SecurityToken.class); if (principal == null || usernameToken == null || !principal.getName().equals(usernameToken.getName())) { return; } // Read the user from Syncope and get the roles WebClient client = WebClient.create(address, Collections.singletonList(new JacksonJsonProvider())); String authorizationHeader = "Basic " + Base64Utility.encode( (usernameToken.getName() + ":" + usernameToken.getPassword()).getBytes()); client.header("Authorization", authorizationHeader); client = client.path("users/self"); UserTO user = null; try { user = client.get(UserTO.class); if (user == null) { Exception exception = new Exception("Authentication failed"); throw new Fault(exception); } } catch (RuntimeException ex) { if (log.isDebugEnabled()) { log.debug(ex.getMessage(), ex); } throw new Fault(ex); } // Now get the roles List<MembershipTO> membershipList = user.getMemberships(); Subject subject = new Subject(); subject.getPrincipals().add(principal); for (MembershipTO membership : membershipList) { String roleName = membership.getRoleName(); subject.getPrincipals().add(new SimpleGroup(roleName, usernameToken.getName())); } subject.setReadOnly(); message.put(SecurityContext.class, new DefaultSecurityContext(principal, subject)); }
@Test public void testJsonRoundtrip() throws Exception { List<Object> providers = new ArrayList<Object>(); providers.add(new org.codehaus.jackson.jaxrs.JacksonJsonProvider()); JsonBean inputBean = new JsonBean(); inputBean.setVal1("Maple"); WebClient client = WebClient.create(endpointUrl + "/hello/jsonBean", providers); Response r = client.accept("application/json").type("application/json").post(inputBean); assertEquals(Response.Status.OK.getStatusCode(), r.getStatus()); MappingJsonFactory factory = new MappingJsonFactory(); JsonParser parser = factory.createJsonParser((InputStream) r.getEntity()); JsonBean output = parser.readValueAs(JsonBean.class); assertEquals("Maple", output.getVal2()); }
// Optional step - may be needed to ensure that by the time individual // tests start running the endpoint has been fully initialized private static void waitForWADL() throws InterruptedException { LOGGER.info("Waiting for wadl"); WebClient client = WebClient.create(WADL_ADDRESS); // wait for 20 secs or so for (int i = 0; i < 20; i++) { Thread.currentThread().sleep(200); Response response = client.get(); if (response.getStatus() == 200) { break; } } // no WADL is available yet - throw an exception or give tests a chance // to run anyway }
@Test @Ignore public void statuslist() throws Exception { WebClient wc = WebClient.create( "http://localhost:8080/forsendelse/service/rest/forsendelsesservice/statuslist?ids=000000001689.pdf,000000001690.pdf"); wc.type("text/xml"); XMLSource source = wc.get(XMLSource.class); source.setBuffering(true); ForsendelseStatusRest b1 = source.getNode("/books/book[position() = 1]", ForsendelseStatusRest.class); assertNotNull(b1); ForsendelseStatusRest b2 = source.getNode("/books/book[position() = 2]", ForsendelseStatusRest.class); assertNotNull(b2); }
private void testPOSTMethodWithJAXRSClientApi( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { WebClient client = WebClient.create(host); String orderURLPath = serviceEndPoint + "/orders"; // Sent HTTP POST request to add customer order System.out.println("\n"); System.out.println("Sent HTTP POST request to add an order"); String postData = "<Order>\n" + " <drinkName>Mocha Flavored Coffee</drinkName>\n" + " <additions>Caramel</additions>\n" + "</Order>\n"; Entity<String> entity = Entity.entity(postData, MediaType.TEXT_XML_TYPE); Response response1 = client.path(orderURLPath).post(entity); printOutput(response, response1); }
public void testDelete() throws Exception { try { Pie searchObject = new Pie(); Collection results = getApplicationService() .search( "gov.nih.nci.cacoresdk.domain.other.differentpackage.associations.Pie", searchObject); String id = ""; if (results != null && results.size() > 0) { Pie obj = (Pie) ((List) results).get(0); Integer idVal = obj.getId(); id = new Integer(idVal).toString(); } else return; if (id.equals("")) return; String url = baseURL + "/rest/Pie/" + id; WebClient client = WebClient.create(url); Response response = client.delete(); if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } } catch (Exception e) { e.printStackTrace(); throw e; } }
public void testSearch() throws Exception { try { String url = baseURL + "/rest/Pupil/search;id=*"; WebClient client = WebClient.create(url); client.type("application/xml").accept("application/xml"); Response response = client.get(); if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) { InputStream is = (InputStream) response.getEntity(); org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false); org.jdom.Document jDoc = builder.build(is); assertEquals(jDoc.getRootElement().getName(), "response"); } else if (response.getStatus() != 200) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } File myFile = new File("Pupil_Search" + "XML.xml"); System.out.println("writing data to file " + myFile.getAbsolutePath()); FileWriter myWriter = new FileWriter(myFile); BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { myWriter.write(output); System.out.println(output); } myWriter.flush(); myWriter.close(); } catch (Exception e) { e.printStackTrace(); } }
@SuppressWarnings("unchecked") public void downloadDocument(String selDocId) { try { WebClient client = WebClient.create(D_BASE_URL + "download/" + selDocId); client.type("multipart/form-data").accept(MediaType.MULTIPART_FORM_DATA); List<Attachment> attachments = (List<Attachment>) client.getCollection(Attachment.class); file = new DefaultStreamedContent( attachments.get(0).getDataHandler().getInputStream(), attachments.get(0).getContentDisposition().getParameter("filetype"), attachments.get(0).getContentDisposition().getParameter("filename")); client.close(); } catch (Exception e) { LOGGER.error(e, e); IclubWebHelper.addMessage( getLabelBundle().getString("doucmentuploadingerror") + " :: " + e.getMessage(), FacesMessage.SEVERITY_ERROR); } }
/** * recognises names of entities in the text * * @param text text which possibly contains names * @return map of entity type -> set of names */ public Map<String, Set<String>> recognise(String text) { Map<String, Set<String>> entities = new HashMap<>(); try { String url = restHostUrlStr + "/nltk"; Response response = WebClient.create(url).accept(MediaType.TEXT_HTML).post(text); int responseCode = response.getStatus(); if (responseCode == 200) { String result = response.readEntity(String.class); JSONParser parser = new JSONParser(); JSONObject j = (JSONObject) parser.parse(result); Set s = entities.put("NAMES", new HashSet((Collection) j.get("names"))); } } catch (Exception e) { LOG.debug(e.getMessage(), e); } ENTITY_TYPES.clear(); ENTITY_TYPES.addAll(entities.keySet()); return entities; }
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest request, * javax.servlet.http.HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String hostIp = request.getParameter("Host"); String port = request.getParameter("Port"); if (hostIp != null && port != null) { host = "http://" + hostIp + ":" + port + "/"; } WebClient client = WebClient.create(host); String method = request.getParameter("HTTPMethod"); if ("GET".equals(method)) { testGETMethodWithJAXRSClientApi(request, response); } else if ("POST".equals(method)) { testPOSTMethodWithJAXRSClientApi(request, response); } else if ("PUT".equals(method)) { testPUTMethodWithJAXRSClientApi(request, response); } else if ("DELETE".equals(method)) { testDELETEMethodWithJAXRSClientApi(request, response); } }