下面列出了org.osgi.framework.dto.ServiceReferenceDTO#org.restlet.resource.ClientResource 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
*/
}
/**
* 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.");
}
}
@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);
}
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;
}
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);
}
}
/**
* @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();
}
}
@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);
}
}
@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);
}
}
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);
}
}
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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
/**
* @see org.osgi.rest.client.RestClient#getBundleRepresentations()
*/
public Collection<BundleDTO> getBundles() throws Exception {
try {
final Representation repr = new ClientResource(Method.GET,
baseUri.resolve("framework/bundles/representations"))
.get(BUNDLES_REPRESENTATIONS);
return DTOReflector.getDTOs(BundleDTO.class, repr);
} catch (final ResourceException e) {
if (Status.CLIENT_ERROR_NOT_FOUND.equals(e.getStatus())) {
return null;
}
throw e;
}
}
/**
* @see org.osgi.rest.client.RestClient#getBundle(java.lang.String)
*/
public BundleDTO getBundle(final String bundlePath) throws Exception {
try {
final Representation repr = new ClientResource(Method.GET,
baseUri.resolve(bundlePath)).get(BUNDLE);
return DTOReflector.getDTO(BundleDTO.class, repr);
} catch (final ResourceException e) {
if (Status.CLIENT_ERROR_NOT_FOUND.equals(e.getStatus())) {
return null;
}
throw e;
}
}
/**
* @see org.osgi.rest.client.RestClient#getBundleState(java.lang.String)
*/
public int getBundleState(final String bundlePath) throws Exception {
final Representation repr = new ClientResource(Method.GET,
baseUri.resolve(bundlePath + "/state")).get(BUNDLE_STATE);
// FIXME: hardcoded to JSON
final JSONObject obj = new JsonRepresentation(repr).getJsonObject();
return obj.getInt("state");
}
/**
* @see org.osgi.rest.client.RestClient#startBundle(java.lang.String)
*/
public void startBundle(final String bundlePath, final int options)
throws Exception {
// FIXME: hardcoded to JSON
final JSONObject state = new JSONObject();
state.put("state", 32);
state.put("options", options);
new ClientResource(Method.PUT, baseUri.resolve(bundlePath + "/state"))
.put(state, BUNDLE_STATE);
}
/**
* @see org.osgi.rest.client.RestClient#stopBundle(java.lang.String)
*/
public void stopBundle(final String bundlePath, final int options)
throws Exception {
final JSONObject state = new JSONObject();
state.put("state", 4);
state.put("options", options);
new ClientResource(Method.PUT, baseUri.resolve(bundlePath + "/state"))
.put(state, BUNDLE_STATE);
}
/**
* @see org.osgi.rest.client.RestClient#getBundleHeaders(java.lang.String)
*/
public Map<String, String> getBundleHeaders(final String bundlePath)
throws Exception {
final Representation repr = new ClientResource(Method.GET,
baseUri.resolve(bundlePath + "/header"))
.get(BUNDLE_HEADER);
return DTOReflector.getMap(repr);
}
/**
* @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);
}
/**
* @see org.osgi.rest.client.RestClient#setBundleStartLevel(java.lang.String,
* org.osgi.dto.framework.startlevel.BundleStartLevelDTO)
*/
public void setBundleStartLevel(final String bundlePath,
final int startLevel) throws Exception {
BundleStartLevelDTO bsl = new BundleStartLevelDTO();
bsl.startLevel = startLevel;
new ClientResource(Method.PUT, baseUri.resolve(bundlePath
+ "/startlevel")).put(
DTOReflector.getJson(BundleStartLevelDTO.class, bsl),
BUNDLE_STARTLEVEL);
}
/**
* @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());
}
/**
* @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);
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
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;
}
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;
}
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();
}
}