protected void logReferenceInfo() { Reference reference = getReference(); getLiberecoResourceLogger() .debug( "Reference, path [" + reference.getPath() + "], identifier: " + reference.getIdentifier() + ", last segment: " + reference.getLastSegment() + ", path: " + reference.getPath() + ", relative part: " + reference.getRelativePart() + ", remaining part: " + reference.getRemainingPart() + ", fragment: " + reference.getFragment() + ", segments: " + reference.getSegments()); List<String> segments = reference.getSegments(); if (segments != null) { for (String segment : segments) { getLiberecoResourceLogger().debug("Segment: " + segment); } } }
public void testMatrix() { final Reference ref1 = new Reference("http://domain.tld/whatever/a=1;b=2;c=4?x=a&y=b"); final Reference ref2 = new Reference("http://domain.tld/whatever/a=1/foo;b=2;c=4;d?x=a&y=b"); final Reference ref3 = new Reference("http://domain.tld/whatever/a=1;b=2;c=4/foo?x=a&y=b"); assertTrue(ref1.hasMatrix()); assertTrue(ref2.hasMatrix()); assertFalse(ref3.hasMatrix()); assertEquals("b=2;c=4", ref1.getMatrix()); assertEquals("b=2;c=4;d", ref2.getMatrix()); final Form form1 = ref1.getMatrixAsForm(); assertEquals("2", form1.getFirstValue("b")); assertEquals("4", form1.getFirstValue("c")); final Form form2 = ref1.getMatrixAsForm(); assertEquals("2", form2.getFirstValue("b")); assertEquals("4", form2.getFirstValue("c")); assertNull(form2.getFirstValue("d")); final Form newForm = new Form(); newForm.add("a", "1"); newForm.add("b", "2"); newForm.add("c", "4"); assertEquals("a=1;b=2;c=4", newForm.getMatrixString()); }
/** * Handle HTTP GET method / Json * * @return a JSON list of contacts. */ @Get("json") public Representation toJSON() { // System.out.println("Request Original Ref " + getOriginalRef()); // System.out.println("Request Entity " + getRequest().getEntityAsText() // + // " entity mediaType " + getRequest().getEntity().getMediaType()); try { JSONArray jcontacts = new JSONArray(); Reference ref = getRequest().getResourceRef(); final String baseURL = ref.getHierarchicalPart(); Form formQuery = ref.getQueryAsForm(); Iterator<Contact> it = getSortedContacts(formQuery.getFirstValue(REQUEST_QUERY_SORT, LAST_NAME)).iterator(); while (it.hasNext()) { Contact contact = it.next(); JSONObject jcontact = new JSONObject(); jcontact.put(ID, String.format("%s", contact.getId())); jcontact.put(URL, String.format("%s/%s", baseURL, contact.getId())); jcontact.put(FIRST_NAME, contact.getFirstName()); jcontact.put(LAST_NAME, contact.getLastName()); jcontacts.put(jcontact); } JSONObject contacts = new JSONObject(); contacts.put(CONTACTS, jcontacts); return new JsonRepresentation(contacts); } catch (Exception e) { setStatus(Status.SERVER_ERROR_INTERNAL); return null; } }
@Before public void setUp() throws Exception { contactsRepository = ContactsRepository.getInstance(); contactsRepository.setDbService(dbService); attributes = new ConcurrentHashMap<String, Object>(); Subject subjectUnderTest = Mockito.mock(Subject.class); setSubject(subjectUnderTest); request = Mockito.mock(Request.class); Mockito.when(request.getClientInfo()).thenReturn(new ClientInfo()); Mockito.when(request.getAttributes()).thenReturn(attributes); Reference targetRef = Mockito.mock(Reference.class); Reference resourceRef = Mockito.mock(Reference.class); Mockito.when(request.getResourceRef()).thenReturn(resourceRef); Mockito.when(resourceRef.getTargetRef()).thenReturn(targetRef); response = new Response(request); ValidatorService validatorService = Mockito.mock(ValidatorService.class); Validator validator = Mockito.mock(Validator.class); Mockito.when(validatorService.getValidator()).thenReturn(validator); Mockito.when(clipboardApplication.getValidatorService()).thenReturn(validatorService); RouteBuilder routeBuilder = Mockito.mock(RouteBuilder.class); Mockito.when(clipboardApplication.getRouteBuilders(Mockito.any())) .thenReturn(Arrays.asList(routeBuilder)); }
/** * Creates a next Restlet is no one is set. By default, it creates a new {@link Client} based on * the protocol of the resource's URI reference. * * @return The created next Restlet or null. */ protected Uniform createNext() { Uniform result = null; // Prefer the outbound root result = getApplication().getOutboundRoot(); if ((result == null) && (getContext() != null)) { // Try using directly the client dispatcher result = getContext().getClientDispatcher(); } if (result == null) { // As a final option, try creating a client connector Protocol rProtocol = getProtocol(); Reference rReference = getReference(); Protocol protocol = (rProtocol != null) ? rProtocol : (rReference != null) ? rReference.getSchemeProtocol() : null; if (protocol != null) { result = new Client(protocol); } } return result; }
protected Reference getChildReference(Reference parentRef, String childId) { if (parentRef.getIdentifier().endsWith("/")) { return new Reference(parentRef.getIdentifier() + childId); } else { return new Reference(parentRef.getIdentifier() + "/" + childId); } }
/** Test scheme specific part getting/setting. */ public void testSchemeSpecificPart() throws Exception { final Reference ref = getDefaultReference(); String part = "//www.restlet.org"; assertEquals(part, ref.getSchemeSpecificPart()); part = "//www.restlet.net"; ref.setSchemeSpecificPart(part); assertEquals(part, ref.getSchemeSpecificPart()); }
/** Test references that are unequal. */ public void testUnEquals() throws Exception { final String uri1 = "http://www.restlet.org/"; final String uri2 = "http://www.restlet.net/"; final Reference ref1 = new Reference(uri1); final Reference ref2 = new Reference(uri2); assertFalse(ref1.equals(ref2)); assertFalse(ref1.equals(null)); }
/** Test hostname getting/setting. */ public void testHostName() throws Exception { final Reference ref = getReference(); String host = "www.restlet.org"; ref.setHostDomain(host); assertEquals(host, ref.getHostDomain()); host = "restlet.org"; ref.setHostDomain(host); assertEquals(host, ref.getHostDomain()); }
public void testValidity() { String uri = "http ://domain.tld/whatever/"; Reference ref = new Reference(uri); assertEquals("http+://domain.tld/whatever/", ref.toString()); uri = "file:///C|/wherever\\whatever.swf"; ref = new Reference(uri); assertEquals("file:///C%7C/wherever%5Cwhatever.swf", ref.toString()); }
public void testProtocolConstructors() { assertEquals("http://restlet.org", new Reference(Protocol.HTTP, "restlet.org").toString()); assertEquals( "https://restlet.org:8443", new Reference(Protocol.HTTPS, "restlet.org", 8443).toString()); final Reference ref = new Reference(Protocol.HTTP, "restlet.org"); ref.addQueryParameter("abc", "123"); assertEquals("http://restlet.org?abc=123", ref.toString()); }
/** Test port getting/setting. */ public void testPort() throws Exception { final Reference ref = getDefaultReference(); int port = 8080; ref.setHostPort(port); assertEquals(port, ref.getHostPort()); port = 9090; ref.setHostPort(port); assertEquals(port, ref.getHostPort()); }
/** * Assert if the FileOrdered have been copied It gets the list of files from the order, and gets * the file described in the list of files * * @param order the order to assert * @param nbFileCopied the expected number of files to be copied */ private void assertFileOrderedExists(Order order, int nbFileCopied) { assertNotNull(order); assertNotNull(order.getResourceCollection()); assertEquals(1, order.getResourceCollection().size()); Representation result = null; try { String res = order.getResourceCollection().get(0); ClientResource cr = new ClientResource(res); ChallengeResponse chal = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password); cr.setChallengeResponse(chal); result = cr.get(getMediaTest()); assertNotNull(result); assertTrue(cr.getStatus().isSuccess()); try { // get the list of files String text = result.getText(); String[] contents = text.split("\r\n"); assertNotNull(contents); assertEquals(nbFileCopied, contents.length); Reference content = new Reference(contents[0]); // asserts assertNotNull(content); assertNotSame("", content.toString()); // get the file corresponding to the first url, check that this file // exists cr = new ClientResource(content); chal = new ChallengeResponse(ChallengeScheme.HTTP_BASIC, userLogin, password); cr.setChallengeResponse(chal); result = cr.get(getMediaTest()); assertNotNull(result); assertTrue(cr.getStatus().isSuccess()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { RIAPUtils.exhaust(result); } } finally { RIAPUtils.exhaust(result); } }
/** * Returns the canonicalized resource name. * * @param resourceRef The resource reference. * @return The canonicalized resource name. */ private static String getCanonicalizedResourceName(Reference resourceRef) { Form form = resourceRef.getQueryAsForm(); Parameter param = form.getFirst("comp", true); if (param != null) { StringBuilder sb = new StringBuilder(resourceRef.getPath()); return sb.append("?").append("comp=").append(param.getValue()).toString(); } return resourceRef.getPath(); }
/** * Returns the reference of a mail according to its identifier. * * @param identifier The identifier of a mail. * @return The URI of the mail. * @throws ResourceException */ protected Reference getMailRef(String identifier) throws ResourceException { final Template mailTemplate = new Template(getMailUriTemplate()); Reference result = new Reference(mailTemplate.format(new MailResolver(identifier))); if (result.isRelative()) { result.setBaseRef(getMailboxUri()); result = result.getTargetRef(); } return result; }
/** * Returns the reference of the target according to the a list of properties. * * @param resolver The resolver. * @return The target reference. * @throws ResourceException */ protected Reference getTargetRef(Resolver<String> resolver) throws ResourceException { final Template targetTemplate = new Template(getTargetUri()); Reference result = new Reference(targetTemplate.format(resolver)); if (result.isRelative()) { result.setBaseRef(getMailboxUri()); result = result.getTargetRef(); } return result; }
private int getRemainingCount() { final Reference reference = new Reference("http://localhost/clue/game.json"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); final ClueServerStatus response = resource.get(ClueServerStatus.class); resource.release(); return response.getRemainingTriples().size(); }
private void resetGame() { final Reference reference = new Reference("http://localhost/clue/game"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); resource.delete(); resource.release(); assertEquals(324, getRemainingCount()); }
@Override public Representation handleGet(Request request, Response response, Session session) throws ResourceException { if (request.getResourceRef().getPath().endsWith("image.png")) { return new InputRepresentation( getClass().getResourceAsStream("sis-video.png"), MediaType.IMAGE_PNG); } String url = SIS.get().getSettings(getContext()).getProperty(SOURCE_KEY); if (url == null) throw new ResourceException(Status.SERVER_ERROR_SERVICE_UNAVAILABLE); final Request extReq = new Request(Method.GET, url); final Response extResp = getContext().getClientDispatcher().handle(extReq); if (!extResp.getStatus().isSuccess()) throw new ResourceException(Status.SERVER_ERROR_SERVICE_UNAVAILABLE); final Document respDoc = getEntityAsDocument(extResp.getEntity()); final List<VideoSource> list = new ArrayList<VideoSource>(); final NodeList nodes = respDoc.getDocumentElement().getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if ("entry".equals(node.getNodeName())) { VideoSource video = new VideoSource(); video.setImage("/sources/youtube/featured/image.png"); NodeCollection children = new NodeCollection(node.getChildNodes()); for (Node child : children) { if ("title".equals(child.getNodeName())) video.setTitle(child.getTextContent()); else if ("content".equals(child.getNodeName())) video.setCaption(child.getTextContent()); else if ("link".equals(child.getNodeName())) { if ("alternate".equals(BaseDocumentUtils.impl.getAttribute(child, "rel"))) { Reference videoRef = new Reference(BaseDocumentUtils.impl.getAttribute(child, "href")); String videoID = videoRef.getQueryAsForm().getFirstValue("v"); if (videoID == null) video.setUrl(BaseDocumentUtils.impl.getAttribute(child, "href")); else video.setUrl("http://www.youtube.com/embed/" + videoID); } } } list.add(video); } } final StringBuilder out = new StringBuilder(); out.append("<root>"); for (VideoSource source : list) out.append(source.toXML()); out.append("</root>"); return new StringRepresentation(out.toString(), MediaType.TEXT_XML); }
/** * Handle HTTP GET Metod / xml * * @return an XML list of contacts. */ @Get("xml") public Representation toXML() { // System.out.println("Request Original Ref " + getOriginalRef()); // System.out.println("Request Entity " + getRequest().getEntityAsText() // + // " entity mediaType " + getRequest().getEntity().getMediaType()); Reference ref = getRequest().getResourceRef(); final String baseURL = ref.getHierarchicalPart(); Form formQuery = ref.getQueryAsForm(); try { DomRepresentation representation = new DomRepresentation(MediaType.TEXT_XML); Document d = representation.getDocument(); Element elContacts = d.createElement(CONTACTS); d.appendChild(elContacts); Iterator<Contact> it = getSortedContacts(formQuery.getFirstValue(REQUEST_QUERY_SORT, LAST_NAME)).iterator(); while (it.hasNext()) { Contact contact = it.next(); Element el = d.createElement(CONTACT); Element id = d.createElement(ID); id.appendChild(d.createTextNode(String.format("%s", contact.getId()))); el.appendChild(id); Element firstname = d.createElement(FIRST_NAME); firstname.appendChild(d.createTextNode(contact.getFirstName())); el.appendChild(firstname); Element lastname = d.createElement(LAST_NAME); lastname.appendChild(d.createTextNode(contact.getLastName())); el.appendChild(lastname); Element url = d.createElement(URL); url.appendChild(d.createTextNode(String.format("%s/%s", baseURL, contact.getId()))); el.appendChild(url); elContacts.appendChild(el); } d.normalizeDocument(); return representation; } catch (Exception e) { setStatus(Status.SERVER_ERROR_INTERNAL); return null; } }
/** * Writes the current object as an XML element using the given SAX writer. * * @param writer The SAX writer. * @throws SAXException */ public void writeElement(XmlWriter writer) throws SAXException { AttributesImpl attributes = new AttributesImpl(); if ((getReference() != null) && !getReference().equals("")) { attributes.addAttribute("", "href", null, "xs:anyURI", "#" + getReference()); writer.emptyElement(APP_NAMESPACE, "representation", null, attributes); } else { if ((getIdentifier() != null) && !getIdentifier().equals("")) { attributes.addAttribute("", "id", null, "xs:ID", getIdentifier()); } if (getMediaType() != null) { attributes.addAttribute("", "mediaType", null, "xs:string", getMediaType().toString()); } if ((getProfiles() != null) && !getProfiles().isEmpty()) { StringBuilder builder = new StringBuilder(); for (Iterator<Reference> iterator = getProfiles().iterator(); iterator.hasNext(); ) { Reference reference = iterator.next(); builder.append(reference.toString()); if (iterator.hasNext()) { builder.append(" "); } } attributes.addAttribute("", "profile", null, "xs:string", builder.toString()); } if ((getXmlElement() != null) && !getXmlElement().equals("")) { attributes.addAttribute("", "element", null, "xs:QName", getXmlElement()); } if (getDocumentations().isEmpty() && getParameters().isEmpty()) { writer.emptyElement(APP_NAMESPACE, "representation", null, attributes); } else { writer.startElement(APP_NAMESPACE, "representation", null, attributes); for (DocumentationInfo documentationInfo : getDocumentations()) { documentationInfo.writeElement(writer); } for (ParameterInfo parameterInfo : getParameters()) { parameterInfo.writeElement(writer); } writer.endElement(APP_NAMESPACE, "representation"); } } }
@Test public void testServerGetStatus() throws Exception { final Reference reference = new Reference("http://localhost/clue/game.xml"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); final ClueServerStatus response = resource.get(ClueServerStatus.class); resource.release(); assertNotNull(response); }
@Test public void testGetProbabilities() throws ResourceException, IOException { final Reference reference = new Reference("http://localhost/clue/probability.json"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); System.out.println(resource.get().getText()); final ProbabilityReport report = resource.get(ProbabilityReport.class); System.out.println(report.getMostLikelyRoom().getCardProbability()); resource.release(); }
@Test public void testPutCard() throws Exception { final Reference reference = new Reference("http://localhost/clue/cards"); reference.setHostPort(port); final ClientResource client = new ClientResource(reference); client.setChallengeResponse(getChallengeResponse()); final Card card = WeaponEnum.LEADPIPE.getWeapon(); client.put(new JacksonRepresentation<Card>(card)); client.release(); assertEquals(270, getRemainingCount()); }
/** Test addition methods. */ public void testAdditions() throws Exception { final Reference ref = new Reference("http://www.restlet.org"); ref.addQueryParameter("abc", "123"); assertEquals("http://www.restlet.org?abc=123", ref.toString()); ref.addQueryParameter("def", null); assertEquals("http://www.restlet.org?abc=123&def", ref.toString()); ref.addSegment("root"); assertEquals("http://www.restlet.org/root?abc=123&def", ref.toString()); ref.addSegment("dir"); assertEquals("http://www.restlet.org/root/dir?abc=123&def", ref.toString()); }
@Test public void testRemainingTriples() { final Reference reference = new Reference("http://localhost/clue/triples/remaining.json"); reference.setHostPort(port); final ClientResource resource = new ClientResource(reference); resource.setProtocol(Protocol.HTTP); resource.setChallengeResponse(getChallengeResponse()); final TripleList response = resource.get(TripleList.class); resource.release(); assertNotNull(response); assertEquals(324, response.size()); }
public MailboxResource(Context context, Request request, Response response) { super(context, request, response); final String mailboxId = Reference.decode( (String) request.getAttributes().get("mailboxId"), CharacterSet.ISO_8859_1); this.mailbox = getObjectsFacade().getMailboxById(mailboxId); System.out.println(Reference.encode(mailboxId)); if (this.mailbox != null) { getVariants().add(new Variant(MediaType.TEXT_HTML)); } // Avoid anonymous to update this resource. setModifiable(true); }
@SuppressWarnings("deprecation") public File downloadSnapshotArtifact(String repository, Gav gav, File parentDir) throws IOException { // @see http://issues.sonatype.org/browse/NEXUS-599 // r=<repoId> -- mandatory // g=<groupId> -- mandatory // a=<artifactId> -- mandatory // v=<version> -- mandatory // c=<classifier> -- optional // p=<packaging> -- optional, jar is taken as default // http://localhost:8087/nexus/service/local/artifact/maven/redirect?r=tasks-snapshot-repo&g=nexus&a=artifact& // v=1.0-SNAPSHOT String serviceURI = "service/local/artifact/maven/redirect?r=" + repository + "&g=" + gav.getGroupId() + "&a=" + gav.getArtifactId() + "&v=" + gav.getVersion(); Response response = RequestFacade.doGetRequest(serviceURI); Status status = response.getStatus(); if (status.isError()) { throw new FileNotFoundException(status + ": (" + status.getCode() + ")"); } Assert.assertEquals( "Snapshot download should redirect to a new file\n " + response.getRequest().getResourceRef().toString() + " \n Error: " + status.getDescription(), 301, status.getCode()); Reference redirectRef = response.getRedirectRef(); Assert.assertNotNull( "Snapshot download should redirect to a new file " + response.getRequest().getResourceRef().toString(), redirectRef); serviceURI = redirectRef.toString(); File file = FileUtils.createTempFile(gav.getArtifactId(), '.' + gav.getExtension(), parentDir); RequestFacade.downloadFile(new URL(serviceURI), file.getAbsolutePath()); return file; }
/** * Returns the feed representation. * * @return The feed representation. * @throws Exception */ public Feed getFeed() throws Exception { final Reference feedRef = getHref(); if (feedRef.isRelative()) { feedRef.setBaseRef(getWorkspace().getService().getReference()); } final Request request = new Request(Method.GET, feedRef.getTargetRef()); final Response response = getWorkspace().getService().getClientDispatcher().handle(request); if (response.getStatus().equals(Status.SUCCESS_OK)) { return new Feed(response.getEntity()); } throw new Exception( "Couldn't get the feed representation. Status returned: " + response.getStatus()); }
@Test public void testPutTriple() throws Exception { final Client client = new Client(Protocol.HTTP); final Reference reference = new Reference("http://localhost/clue/triples"); reference.setHostPort(port); final Request request = new Request(Method.PUT, reference); request.setChallengeResponse(getChallengeResponse()); final Weapon weapon = WeaponEnum.CANDLESTICK.getWeapon(); final Suspect suspect = SuspectEnum.PEACOCK.getSuspect(); final Room room = RoomEnum.BILLIARDROOM.getRoom(); request.setEntity(new JacksonRepresentation<Triple>(new Triple(room, suspect, weapon))); System.out.println(request.getEntityAsText()); client.handle(request); assertEquals(323, getRemainingCount()); }