org.restlet.resource.ClientResource Java Examples

The following examples show how to use org.restlet.resource.ClientResource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MigrateUIDOperation.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.subTask(Messages.migratingUID);
    PageDesignerURLFactory urlBuilder = pageDesignerURLBuilder == null
            ? new PageDesignerURLFactory(getPreferenceStore()) : pageDesignerURLBuilder;
    URI uri = null;
    try {
        uri = urlBuilder.migrate().toURI();
    } catch (MalformedURLException | URISyntaxException e1) {
        throw new InvocationTargetException(new MigrationException(e1));
    }
    Context currentContext = Context.getCurrent();
    try {
        ClientResource clientResource = new ClientResource(uri);
        clientResource.setRetryOnError(true);
        clientResource.setRetryDelay(500);
        clientResource.setRetryAttempts(10);
        clientResource.post(new EmptyRepresentation());
    } catch (ResourceException e) {
        throw new InvocationTargetException(new MigrationException(e),
                "Failed to post on " + uri);
    }finally {
        Context.setCurrent(currentContext);
    }
}
 
Example #2
Source File: IndexingUIDOperation.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    monitor.subTask(Messages.indexingUIDPages);
    PageDesignerURLFactory urlBuilder = pageDesignerURLBuilder == null
            ? new PageDesignerURLFactory(getPreferenceStore()) : pageDesignerURLBuilder;
    URI uri = null;
    try {
        uri = urlBuilder.indexation().toURI();
    } catch (MalformedURLException | URISyntaxException e1) {
        throw new InvocationTargetException(new MigrationException(e1));
    }
    Context currentContext = Context.getCurrent();
    try {
        ClientResource clientResource = new ClientResource(uri);
        clientResource.setRetryOnError(true);
        clientResource.setRetryDelay(500);
        clientResource.setRetryAttempts(10);
        clientResource.post(new EmptyRepresentation());
    } catch (ResourceException e) {
        throw new InvocationTargetException(new MigrationException(e),
                "Failed to post on " + uri);
    }finally {
        Context.setCurrent(currentContext);
    }
}
 
Example #3
Source File: RemoteCarService.java    From microservices-comparison with Apache License 2.0 6 votes vote down vote up
@Override
public List<Car> list() {
    Client client = new Client(new Context(), Protocol.HTTPS);
    Series<Parameter> parameters = client.getContext().getParameters();
    parameters.add("truststorePath", System.getProperty("javax.net.ssl.trustStore"));

    ClientResource clientResource = new ClientResource("https://localhost:8043/api/cars/cars");
    clientResource.setNext(client);
    ChallengeResponse challenge = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
    challenge.setRawValue(Request.getCurrent().getAttributes().getOrDefault("token", "").toString());
    clientResource.setChallengeResponse(challenge);
    CarServiceInterface carServiceInterface = clientResource.wrap(CarServiceInterface.class);
    Car[] allCars = carServiceInterface.getAllCars();
    try {
        client.stop();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return asList(allCars);
}
 
Example #4
Source File: XEBatchSolverSaver.java    From unitime with Apache License 2.0 6 votes vote down vote up
protected XEInterface.RegisterResponse postChanges(ClientResource resource, XEInterface.RegisterRequest req) throws IOException {
	if (req.isEmpty()) req.empty();
	try {
        resource.post(new GsonRepresentation<XEInterface.RegisterRequest>(req));
	} catch (ResourceException e) {
		handleError(resource, e);
	}

	XEInterface.RegisterResponse response = new GsonRepresentation<XEInterface.RegisterResponse>(resource.getResponseEntity(), XEInterface.RegisterResponse.class).getObject();

	if (response == null)
        throw new SectioningException("Failed to enroll student.");
	else if (!response.validStudent) {
		String reason = null;
		if (response.failureReasons != null)
			for (String m: response.failureReasons) {
				if (reason == null) reason = m;
				else reason += "\n" + m;
			}
		if (reason != null) throw new SectioningException(reason);
		throw new SectioningException("Failed to enroll student.");
	}
	
    return response;
}
 
Example #5
Source File: XEBatchSolverSaver.java    From unitime with Apache License 2.0 6 votes vote down vote up
protected void handleError(ClientResource resource, Exception exception) {
	try {
		XEInterface.ErrorResponse response = new GsonRepresentation<XEInterface.ErrorResponse>(resource.getResponseEntity(), XEInterface.ErrorResponse.class).getObject();
		XEInterface.Error error = response.getError();
		if (error != null && error.message != null) {
			throw new SectioningException(error.message);
		} else if (error != null && error.description != null) {
			throw new SectioningException(error.description);
		} else if (error != null && error.errorMessage != null) {
			throw new SectioningException(error.errorMessage);
		} else {
			throw exception;
		}
	} catch (SectioningException e) {
		throw e;
	} catch (Throwable t) {
		throw new SectioningException(exception.getMessage(), exception);
	}
}
 
Example #6
Source File: NeighbourhoodManagerConnector.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Perform handshake and expects NM to validate identity.
 * 
 * @param JSON containing array records with all the messages 
 * @return Server acknowledgment
 */
public synchronized void handshake(){
	try {
		String endpointUrl = SERVER_PROTOCOL + neighbourhoodManagerServer + ":" + port + API_PATH + HANDSHAKE;
		ClientResource clientResource = createRequest(endpointUrl);
		Representation responseRepresentation = clientResource.get(MediaType.APPLICATION_JSON);
		JSONObject jsonDocument = new JSONObject(responseRepresentation.getText());
		logger.info(jsonDocument.getString("message"));
	} catch(IOException i) {
		i.printStackTrace();
	} catch(Exception e) {
		e.printStackTrace();
		logger.warning("There might be a problem authenticating your signature, please check that you uploaded the right public key to the server.");
	}
	
}
 
Example #7
Source File: TestGetAllUsers.java    From FoxBPM with Apache License 2.0 6 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) {
	ClientResource client = new ClientResource("http://localhost:8889/foxbpm-webapps-base/service/identity/allUsers");
	client.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "111", "111");
	Representation result = client.get();
	try {
		BufferedReader br = new BufferedReader(result.getReader());
		String line = null;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
Example #8
Source File: NeighbourhoodManagerConnector.java    From vicinity-gateway-api with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Retrieves the thing descriptions of list IoT objects from the Neighborhood Manager. 
 * 
 * @param Representation of the incoming JSON. List of OIDs
 * @return Thing descriptions of objects specified in payload.
 */
public synchronized Representation getThingDescriptions(Representation json){
	
	String endpointUrl = SERVER_PROTOCOL + neighbourhoodManagerServer + ":" + port + API_PATH + TD_SERVICE;
	
	ClientResource clientResource = createRequest(endpointUrl);
	
	Representation responseRepresentation = clientResource.post(json, MediaType.APPLICATION_JSON);
	
	return responseRepresentation;
	
	/*
	String ret;
	
	try {
		ret = representation.getText();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		ret = null;
	}

	return ret;
	*/
}
 
Example #9
Source File: PostBDMEventHandler.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
private void execute(final Event event) {
    final String fileContent = (String) event.getProperty(FILE_CONTENT);
    Map<String, String> content = new HashMap<>();
    content.put("bdmXml", fileContent);
    try {
        new ClientResource(String.format("http://%s:%s/bdm",
                InetAddress.getByName(null).getHostAddress(),
                InstanceScope.INSTANCE.getNode(BonitaStudioPreferencesPlugin.PLUGIN_ID)
                        .get(BonitaPreferenceConstants.DATA_REPOSITORY_PORT, "-1")))
                                .post(new JacksonRepresentation<Object>(content));
        BonitaStudioLog.info("BDM has been publish into Data Repository service", UIDesignerPlugin.PLUGIN_ID);
    } catch (ResourceException | UnknownHostException e) {
        BonitaStudioLog.error("An error occured while publishing the BDM into Data Repository service", e);
    }
    
}
 
Example #10
Source File: TestBizDataObjectResouce.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	ClientResource client = new ClientResource("http://localhost:8889/foxbpm-webapps-base/service/bizDataObjects/dataBaseMode/foxbpmDataSource");
	client.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "111", "111");
	Representation result = client.get();
	try {
		BufferedReader br = new BufferedReader(result.getReader());
		String line = null;
		while ((line = br.readLine()) != null) {
			System.out.println(line);
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	
}
 
Example #11
Source File: TestDeploy.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
	ClientResource client = new ClientResource("http://127.0.0.1:8082/model/deployments");
	client.setChallengeResponse(ChallengeScheme.HTTP_BASIC,"111", "111");
	
	InputStream input = TestDeploy.class.getClassLoader().getResourceAsStream("FirstFoxbpm.zip");
	Representation deployInput = new InputRepresentation(input);
	Representation result = client.post(deployInput);
	try {
		result.write(System.out);
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example #12
Source File: RestRequestByRestlet.java    From activiti-in-action-codes with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    ClientResource resource = new ClientResource(REST_URI);

    // 设置Base Auth认证
    resource.setChallengeResponse(ChallengeScheme.HTTP_BASIC, "kermit", "kermit");

    Representation representation = resource.get();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(representation.getStream());
    Iterator<String> fieldNames = jsonNode.fieldNames();
    while (fieldNames.hasNext()) {
        String fieldName = fieldNames.next();
        System.out.println(fieldName + " : " + jsonNode.get(fieldName));
    }
}
 
Example #13
Source File: XEBatchSolverSaver.java    From unitime with Apache License 2.0 5 votes vote down vote up
protected XEInterface.RegisterResponse getHoldSchedule(Student student, ClientResource resource) throws IOException {
	if (iHoldPassword != null && !iHoldPassword.isEmpty())
		iProgress.debug("[" + student.getExternalId() + "] " + "Using hold password...");
	if (iRegistrationDate != null && !iRegistrationDate.isEmpty())
		iProgress.debug("[" + student.getExternalId() + "] " + "Using registration date...");
	
	XEInterface.RegisterRequest req = new XEInterface.RegisterRequest(resource.getQueryValue("term"), resource.getQueryValue("bannerId"), null, true);
	req.empty();
	if (iHoldPassword != null && !iHoldPassword.isEmpty())
        req.holdPassword = iHoldPassword;
	if (iRegistrationDate != null && !iRegistrationDate.isEmpty())
        req.registrationDate = iRegistrationDate;
	try {
		resource.post(new GsonRepresentation<XEInterface.RegisterRequest>(req));
	} catch (ResourceException e) {
		handleError(resource, e);
	}

	XEInterface.RegisterResponse response = new GsonRepresentation<XEInterface.RegisterResponse>(resource.getResponseEntity(), XEInterface.RegisterResponse.class).getObject();
	if (response == null)
		throw new SectioningException("Failed to check student registration status.");
	else if (!response.validStudent) {
		String reason = null;
		if (response.failureReasons != null)
			for (String m: response.failureReasons) {
				if (reason == null) reason = m;
				else reason += "\n" + m;
			}
		if (reason != null) throw new SectioningException(reason);
		throw new SectioningException("Failed to check student registration status.");
	}
    return response;
}
 
Example #14
Source File: XEBatchSolverSaver.java    From unitime with Apache License 2.0 5 votes vote down vote up
protected XEInterface.RegisterResponse getSchedule(Student student, ClientResource resource) throws IOException {
	try {
		resource.get(MediaType.APPLICATION_JSON);
	} catch (ResourceException e) {
		handleError(resource, e);
	}
	
	List<XEInterface.RegisterResponse> current = new GsonRepresentation<List<XEInterface.RegisterResponse>>(resource.getResponseEntity(), XEInterface.RegisterResponse.TYPE_LIST).getObject();
	XEInterface.RegisterResponse original = null;
    if (current != null && !current.isEmpty())
    	original = current.get(0);
    
    if (original == null || !original.validStudent) {
    	String reason = null;
    	if (original != null && original.failureReasons != null) {
    		for (String m: original.failureReasons) {
    			if ("Holds prevent registration.".equals(m) && iHoldPassword != null && !iHoldPassword.isEmpty())
    				return getHoldSchedule(student, resource);
    			if ("Invalid or undefined Enrollment Status or date range invalid.".equals(m) && iRegistrationDate != null && !iRegistrationDate.isEmpty())
    				return getHoldSchedule(student, resource);
    			if (m != null) reason = m;
	    	}	
    	}
    	if (reason != null) throw new SectioningException(reason);
    	throw new SectioningException("Failed to check student registration status.");
    }
    
    return original;
}
 
Example #15
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getServiceReference(java.lang.String)
 */
public ServiceReferenceDTO getServiceReference(final String servicePath)
		throws Exception {
	final Representation repr = new ClientResource(Method.GET,
			baseUri.resolve(servicePath)).get(SERVICE);

	return DTOReflector.getDTO(ServiceReferenceDTO.class,
			repr);
}
 
Example #16
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getServiceRepresentations(java.lang.String
 *      )
 */
public Collection<ServiceReferenceDTO> getServiceReferences(
		final String filter) throws Exception {
	final ClientResource res = new ClientResource(Method.GET,
			baseUri.resolve("framework/services/representations"));
	if (filter != null) {
		res.getQuery().add("filter", filter);
	}
	final Representation repr = res.get(SERVICES_REPRESENTATIONS);

	return DTOReflector.getDTOs(ServiceReferenceDTO.class, repr);
}
 
Example #17
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getServices(java.lang.String)
 */
public Collection<String> getServicePaths(final String filter) throws Exception {
	final ClientResource res = new ClientResource(Method.GET,
			baseUri.resolve("framework/services"));

	if (filter != null) {
		res.getQuery().add("filter", filter);
	}

	final Representation repr = res.get(SERVICES);

	return DTOReflector.getStrings(repr);
}
 
Example #18
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#uninstallBundle(java.lang.String)
 */
public BundleDTO uninstallBundle(final String bundlePath) throws Exception {
	final BundleDTO bundle = getBundle(bundlePath);
	
	final ClientResource res = new ClientResource(Method.DELETE,
			baseUri.resolve(bundlePath));
	
	res.delete();
	return bundle;
}
 
Example #19
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#updateBundle(long,
 *      java.io.InputStream)
 */
public BundleDTO updateBundle(final long id, final InputStream in)
		throws Exception {
	new ClientResource(Method.PUT, baseUri.resolve("framework/bundle/"
			+ id)).put(in);
	return getBundle(id);
}
 
Example #20
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getBundleStartLevel(java.lang.String)
 */
public BundleStartLevelDTO getBundleStartLevel(final String bundlePath)
		throws Exception {
	final Representation repr = new ClientResource(Method.GET,
			baseUri.resolve(bundlePath + "/startlevel"))
			.get(BUNDLE_STARTLEVEL);

	return DTOReflector.getDTO(BundleStartLevelDTO.class, repr);
}
 
Example #21
Source File: DeleteUIDArtifactOperation.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
    try {
        new ClientResource(fileStore.toURI()).delete();
    } catch (ResourceException | MalformedURLException | URISyntaxException e) {
        throw new InvocationTargetException(e);
    }
}
 
Example #22
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getBundles()
 */
public Collection<String> getBundlePaths() throws Exception {
	final ClientResource res = new ClientResource(Method.GET,
			baseUri.resolve("framework/bundles"));
	final Representation repr = res.get(BUNDLES);

	return DTOReflector.getStrings(repr);
}
 
Example #23
Source File: UIDesignerWorkspaceIntegrationIT.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void import_a_custom_page_trigger_a_refresh_on_the_workspace() throws Exception {
    waitForServer();

    new ClientResource(String.format("http://localhost:%s/bonita/import/page", uidPort()))
            .post(formDataSetWithCustomPageZipFile());

    final WebPageRepositoryStore repositoryStore = RepositoryManager.getInstance()
            .getRepositoryStore(WebPageRepositoryStore.class);
    assertThat(repositoryStore.getChild("f3ae2099-6298-4b91-add3-bddb3af60b45", true).getResource()
            .getFile("f3ae2099-6298-4b91-add3-bddb3af60b45.json").exists())
                    .overridingErrorMessage(
                            "Workspace should be in sync with imported page file")
                    .isTrue();
}
 
Example #24
Source File: WebPageFileStore.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
public Collection<String> getPageResources() {
    try {
        ClientResource clientResource = new ClientResource(
                PageDesignerURLFactory.INSTANCE.resources(getId()).toURI());
        clientResource.getLogger().setLevel(Level.OFF);
        final Representation representation = clientResource.get();
        return representation != null ? parseExtensionResources( representation.getText() ) : Collections.emptyList();
    } catch (URISyntaxException | IOException e) {
        BonitaStudioLog.error(e);
        return null;
    }
}
 
Example #25
Source File: UIDesignerServerManager.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void connectToURL(final URL url) throws URISyntaxException {
    ClientResource cr = new ClientResource(url.toURI());
    cr.setRetryOnError(true);
    cr.setRetryDelay(500);
    cr.setRetryAttempts(120);
    cr.get();
}
 
Example #26
Source File: DeleteBDMEventHandler.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
private void execute(final Event event) {
    try {
        new ClientResource(String.format("http://%s:%s/bdm",
                InetAddress.getByName(null).getHostAddress(),
                InstanceScope.INSTANCE.getNode(BonitaStudioPreferencesPlugin.PLUGIN_ID)
                        .get(BonitaPreferenceConstants.DATA_REPOSITORY_PORT, "-1")))
                                .delete();
        BonitaStudioLog.info("BDM has been deleted from the Data Repository service", UIDesignerPlugin.PLUGIN_ID);
    } catch (ResourceException | UnknownHostException e) {
        BonitaStudioLog.error("An error occured while deleting the BDM from the Data Repository service", e);
    }
    
}
 
Example #27
Source File: NeighbourhoodManagerConnector.java    From vicinity-gateway-api with GNU General Public License v3.0 5 votes vote down vote up
private ClientResource createRequest(String endpointUrl) {
	ClientResource clientResource = new ClientResource(endpointUrl);
	// Add auth token if security enabled
	if(securityEnabled) {
		String token = secureComms.getToken();
		ChallengeResponse cr = new ChallengeResponse(ChallengeScheme.HTTP_OAUTH_BEARER);
		cr.setRawValue(token);
		clientResource.setChallengeResponse(cr);
	}
	return clientResource;
}
 
Example #28
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#getFrameworkStartLevel()
 */
public FrameworkStartLevelDTO getFrameworkStartLevel() throws Exception {
	final Representation repr = new ClientResource(Method.GET,
			baseUri.resolve("framework/startlevel"))
			.get(FRAMEWORK_STARTLEVEL);

	return DTOReflector.getDTO(FrameworkStartLevelDTO.class, repr);
}
 
Example #29
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#setFrameworkStartLevel(org.osgi.dto.framework
 *      .startlevel.FrameworkStartLevelDTO)
 */
public void setFrameworkStartLevel(final FrameworkStartLevelDTO startLevel)
		throws Exception {
	new ClientResource(Method.PUT, baseUri.resolve("framework/startlevel")).put(
			DTOReflector.getJson(FrameworkStartLevelDTO.class, startLevel),
			FRAMEWORK_STARTLEVEL);
}
 
Example #30
Source File: RestClientImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.rest.client.RestClient#installBundle(java.net.URL)
 */
public BundleDTO installBundle(final String url) throws Exception {
	final ClientResource res = new ClientResource(Method.POST,
			baseUri.resolve("framework/bundles"));
	final Representation repr = res.post(url, MediaType.TEXT_PLAIN);

	return getBundle(repr.getText());
}