Java Code Examples for javax.ws.rs.core.MediaType

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project bpm-console, under directory /server/war/src/main/java/org/jboss/bpm/console/server/.

Source file: FormProcessingFacade.java

  23 
vote

private FieldMapping createFieldMapping(MultipartFormDataInput payload){
  FieldMapping mapping=new FieldMapping();
  Map<String,InputPart> formData=payload.getFormData();
  Iterator<String> partNames=formData.keySet().iterator();
  while (partNames.hasNext()) {
    final String partName=partNames.next();
    final InputPart part=formData.get(partName);
    final MediaType mediaType=part.getMediaType();
    if (MediaType.TEXT_PLAIN_TYPE.equals(mediaType)) {
      if (mapping.isReserved(partName))       mapping.directives.put(partName,part.getBodyAsString());
 else       mapping.processVars.put(partName,part.getBodyAsString());
    }
 else {
      final byte[] data=part.getBodyAsString().getBytes();
      DataHandler dh=new DataHandler(new DataSource(){
        public InputStream getInputStream() throws IOException {
          return new ByteArrayInputStream(data);
        }
        public OutputStream getOutputStream() throws IOException {
          throw new RuntimeException("This is a readonly DataHandler");
        }
        public String getContentType(){
          return mediaType.getType();
        }
        public String getName(){
          return partName;
        }
      }
);
      mapping.processVars.put(partName,dh);
    }
  }
  return mapping;
}
 

Example 2

From project candlepin, under directory /src/main/java/org/candlepin/exceptions/mappers/.

Source file: CandlepinExceptionMapper.java

  19 
vote

public MediaType determineBestMediaType(){
  HttpServletRequest request=injector.getInstance(HttpServletRequest.class);
  String header=request.getHeader(HttpHeaderNames.ACCEPT);
  MediaType mediaType=null;
  if (header != null) {
    List<MediaType> headerMediaTypes=parseHeader(header);
    mediaType=headerMediaTypes.size() == 0 ? MediaType.TEXT_PLAIN_TYPE : getBestMatch(DESIRED_RESPONSE_TYPES,headerMediaTypes);
  }
  if (mediaType == null || (mediaType.getType().equals("*") && mediaType.getSubtype().equals("*"))) {
    mediaType=MediaType.APPLICATION_JSON_TYPE;
  }
  return mediaType;
}
 

Example 3

From project candlepin, under directory /src/main/java/org/candlepin/exceptions/mappers/.

Source file: RuntimeExceptionMapper.java

  17 
vote

@Override public Response toResponse(RuntimeException exception){
  MediaType responseMediaType=determineBestMediaType();
  ResponseBuilder bldr=null;
  Throwable cause=exception.getCause() == null ? exception : exception.getCause();
  if (cause instanceof CandlepinException) {
    bldr=getBuilder((CandlepinException)cause,responseMediaType);
  }
 else   if (exception instanceof CandlepinException) {
    bldr=getBuilder((CandlepinException)exception,responseMediaType);
  }
 else {
    bldr=getDefaultBuilder(cause,null,responseMediaType);
  }
  return bldr.build();
}
 

Example 4

From project action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.

Source file: HdfsBrowser.java

  15 
vote

@GET @Produces(MediaType.APPLICATION_JSON) @Path("/json") @Timed public StreamingOutput listingToJson(@QueryParam("path") final String path,@QueryParam("recursive") final boolean recursive,@QueryParam("pretty") final boolean pretty,@QueryParam("raw") final boolean raw) throws IOException {
  final HdfsListing hdfsListing=hdfsReader.getListing(path,raw,recursive);
  return new StreamingOutput(){
    @Override public void write(    OutputStream output) throws IOException, WebApplicationException {
      hdfsListing.toJson(output,pretty);
    }
  }
;
}
 

Example 5

From project action-core, under directory /src/main/java/com/ning/metrics/action/endpoint/.

Source file: HdfsBrowser.java

  15 
vote

@GET @Produces(MediaType.TEXT_PLAIN) @Path("/binary") @Timed public StreamingOutput download(@QueryParam("path") final String path) throws IOException {
  if (hdfsReader.isDir(path)) {
    throw new WebApplicationException(Response.Status.BAD_REQUEST);
  }
  return hdfsReader.getFile(path);
}
 

Example 6

From project airlift, under directory /discovery/src/main/java/io/airlift/discovery/client/.

Source file: HttpDiscoveryAnnouncementClient.java

  15 
vote

@Override public CheckedFuture<Duration,DiscoveryException> announce(Set<ServiceAnnouncement> services){
  Preconditions.checkNotNull(services,"services is null");
  URI uri=discoveryServiceURI.get();
  if (uri == null) {
    return Futures.immediateFailedCheckedFuture(new DiscoveryException("No discovery servers are available"));
  }
  Announcement announcement=new Announcement(nodeInfo.getEnvironment(),nodeInfo.getNodeId(),nodeInfo.getPool(),nodeInfo.getLocation(),services);
  Request request=preparePut().setUri(URI.create(uri + "/v1/announcement/" + nodeInfo.getNodeId())).setHeader("User-Agent",nodeInfo.getNodeId()).setHeader("Content-Type",MediaType.APPLICATION_JSON).setBodyGenerator(jsonBodyGenerator(announcementCodec,announcement)).build();
  return httpClient.execute(request,new DiscoveryResponseHandler<Duration>("Announcement"){
    @Override public Duration handle(    Request request,    Response response) throws DiscoveryException {
      int statusCode=response.getStatusCode();
      if (!isSuccess(statusCode)) {
        throw new DiscoveryException(String.format("Announcement failed with status code %s: %s",statusCode,getBodyForError(response)));
      }
      Duration maxAge=extractMaxAge(response);
      return maxAge;
    }
  }
);
}
 

Example 7

From project airlift, under directory /event/src/main/java/io/airlift/event/client/.

Source file: HttpEventClient.java

  15 
vote

@Override public <T>CheckedFuture<Void,RuntimeException> post(EventGenerator<T> eventGenerator){
  Preconditions.checkNotNull(eventGenerator,"eventGenerator is null");
  List<URI> uris=serviceSelector.selectHttpService();
  if (uris.isEmpty()) {
    return Futures.<Void,RuntimeException>immediateFailedCheckedFuture(new ServiceUnavailableException(serviceSelector.getType(),serviceSelector.getPool()));
  }
  Request request=preparePost().setUri(resolveUri(uris.get(0))).setHeader("User-Agent",nodeInfo.getNodeId()).setHeader("Content-Type",MediaType.APPLICATION_JSON).setBodyGenerator(new JsonEntityWriter<T>(eventWriter,eventGenerator)).build();
  return httpClient.execute(request,new EventResponseHandler(serviceSelector.getType(),serviceSelector.getPool()));
}
 

Example 8

From project ANNIS, under directory /annis-interfaces/src/main/java/annis/provider/.

Source file: SaltProjectProvider.java

  15 
vote

@Override public void writeTo(SaltProject project,Class<?> type,Type genericType,Annotation[] annotations,MediaType mediaType,MultivaluedMap<String,Object> httpHeaders,OutputStream entityStream) throws IOException, WebApplicationException {
  Resource resource=new XMIResourceImpl();
  resource.getContents().add(project);
  for (  SCorpusGraph corpusGraph : project.getSCorpusGraphs()) {
    for (    SDocument doc : corpusGraph.getSDocuments()) {
      if (doc.getSDocumentGraph() != null) {
        resource.getContents().add(doc.getSDocumentGraph());
      }
    }
  }
  try {
    resource.save(entityStream,null);
  }
 catch (  Exception ex) {
    log.error("exception when serializing SaltProject",ex);
  }
}
 

Example 9

From project ANNIS, under directory /annis-interfaces/src/main/java/annis/provider/.

Source file: SaltProjectProvider.java

  15 
vote

@Override public SaltProject readFrom(Class<SaltProject> type,Type genericType,Annotation[] annotations,MediaType mediaType,MultivaluedMap<String,String> httpHeaders,InputStream entityStream) throws IOException, WebApplicationException {
  ResourceSet resourceSet=new ResourceSetImpl();
  resourceSet.getPackageRegistry().put(SaltCommonPackage.eINSTANCE.getNsURI(),SaltCommonPackage.eINSTANCE);
  XMIResourceImpl resource=new XMIResourceImpl();
  resourceSet.getResources().add(resource);
  if (xmlParserPool.get() == null) {
    xmlParserPool.set(new XMLParserPoolImpl());
  }
  Map<Object,Object> options=resource.getDefaultLoadOptions();
  options.put(XMLResource.OPTION_USE_PARSER_POOL,xmlParserPool.get());
  options.put(XMLResource.OPTION_DEFER_IDREF_RESOLUTION,Boolean.TRUE);
  resource.load(entityStream,null);
  SaltProject project=SaltCommonFactory.eINSTANCE.createSaltProject();
  for (  EObject o : resource.getContents()) {
    if (o instanceof SaltProject) {
      project=(SaltProject)o;
      break;
    }
  }
  return project;
}
 

Example 10

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/impl/.

Source file: ServiceDescriptorResource.java

  15 
vote

@GET @Produces(MediaType.TEXT_HTML) public StreamingOutput getServiceDescriptors(){
  return new StreamingOutput(){
    @Override public void write(    OutputStream output) throws IOException, WebApplicationException {
      final PrintWriter pw=new PrintWriter(output,true);
      StringTemplate st=StringTemplates.getTemplate("htmlOpen");
      st.setAttribute("header","Event Aggregator v2");
      st.setAttribute("msg","");
      pw.println(st);
      pw.println("<h3> Aggregator Nodes </h3>");
      for (      ServiceDescriptor sd : chooser.getAllServiceDescriptors()) {
        String host=sd.getProperties().get("host");
        String port=sd.getProperties().get("jetty.port");
        pw.printf("<li> [<a href=\"http://%s:%s/\"> %s:%s </a>]  ",host,port,host,port);
        pw.printf(" [<a href=\"http://%s:%s/xn/rest/1.0/event/aggregator\"> Aggregators </a>]",host,port);
        pw.printf(" [<a href=\"http://%s:%s/xn/rest/1.0/event/dictionary\"> Event Dictionary </a>]",host,port);
        pw.printf(" [<a href=\"http://%s:%s/xn/rest/1.0/event/stream\"> Streaming End Point </a>]",host,port);
        pw.printf("%s \n",selfUUID.equals(sd.getUuid()) ? " &lt;== hey that's this Node" : "");
      }
      pw.println(StringTemplates.getTemplate("htmlClose"));
      pw.flush();
      pw.close();
    }
  }
;
}
 

Example 11

From project Arecibo, under directory /aggregator/src/main/java/com/ning/arecibo/aggregator/rest/.

Source file: AggregatorRenderer.java

  15 
vote

@Override public void writeTo(AggregatorImpl impl,Class<?> type,Type genericType,Annotation[] annotations,MediaType mediaType,MultivaluedMap<String,Object> httpHeaders,OutputStream entityStream) throws IOException, WebApplicationException {
  PrintWriter pw=new PrintWriter(entityStream);
  StringTemplate st=StringTemplates.getTemplate("htmlOpen");
  st.setAttribute("header","Aggregator Details");
  st.setAttribute("msg","");
  pw.println(st.toString());
  pw.println(StringTemplates.getTemplate("tableOpen"));
  StringTemplate th=StringTemplates.getTemplate("tableHeader");
  th.setAttribute("headers",Arrays.asList("Aggregator","InputEvent","OutputEvent","Esper Statement"));
  pw.println(th);
  impl.renderHtml(pw,0);
  pw.println(StringTemplates.getTemplate("tableClose"));
  pw.println(StringTemplates.getTemplate("htmlClose"));
}
 

Example 12

From project arquillian-container-glassfish, under directory /glassfish-common/src/main/java/org/jboss/arquillian/container/glassfish/clientutils/.

Source file: GlassFishClientUtil.java

  15 
vote

/** 
 * Basic REST call preparation, with the additional resource url appended
 * @param additionalResourceUrl url portion past the base to use
 * @return the resource builder to execute
 */
private WebResource.Builder prepareClient(String additionalResourceUrl){
  final Client client=Client.create();
  if (configuration.isAuthorisation()) {
    client.addFilter(new HTTPBasicAuthFilter(configuration.getAdminUser(),configuration.getAdminPassword()));
  }
  client.addFilter(new CsrfProtectionFilter());
  return client.resource(this.adminBaseUrl + additionalResourceUrl).accept(MediaType.APPLICATION_XML_TYPE);
}
 

Example 13

From project arquillian-container-glassfish, under directory /glassfish-common/src/main/java/org/jboss/arquillian/container/glassfish/.

Source file: CommonGlassFishManager.java

  15 
vote

public void undeploy(Archive<?> archive) throws DeploymentException {
  if (archive == null) {
    throw new IllegalArgumentException("archive must not be null");
  }
 else {
    deploymentName=createDeploymentName(archive.getName());
    try {
      final FormDataMultiPart form=new FormDataMultiPart();
      form.field("target",this.configuration.getTarget(),MediaType.TEXT_PLAIN_TYPE);
      form.field("operation",DELETE_OPERATION,MediaType.TEXT_PLAIN_TYPE);
      glassFishClient.doUndeploy(this.deploymentName,form);
    }
 catch (    GlassFishClientException e) {
      throw new DeploymentException("Could not undeploy " + archive.getName(),e);
    }
  }
}
 

Example 14

From project arquillian-showcase, under directory /extensions/resteasy/src/test/java/org/jboss/arquillian/extension/rest/.

Source file: RestClientTestCase.java

  15 
vote

@Test @GET @Path("rest/customer") @Consumes(MediaType.APPLICATION_XML) public void shouldBeAbleToListAllCustomers(ClientResponse<List<Customer>> response){
  Assert.assertEquals(Status.OK.getStatusCode(),response.getStatus());
  List<Customer> customers=response.getEntity(new GenericType<List<Customer>>(){
  }
);
  Assert.assertEquals(2,customers.size());
}
 

Example 15

From project arquillian-showcase, under directory /jaxrs/src/test/java/com/acme/jaxrs/.

Source file: CustomerResourceClientTest.java

  15 
vote

@Test public void testGetCustomerByIdUsingClientRequest() throws Exception {
  ClientRequest request=new ClientRequest(deploymentUrl.toString() + RESOURCE_PREFIX + "/customer/1");
  request.header("Accept",MediaType.APPLICATION_XML);
  ClientResponse<String> responseObj=request.get(String.class);
  Assert.assertEquals(200,responseObj.getStatus());
  System.out.println("GET /customer/1 HTTP/1.1\n\n" + responseObj.getEntity());
  String response=responseObj.getEntity().replaceAll("<\\?xml.*\\?>","").trim();
  Assert.assertEquals("<customer><id>1</id><name>Acme Corporation</name></customer>",response);
}
 

Example 16

From project arquillian_deprecated, under directory /containers/glassfish-remote-3.1/src/main/java/org/jboss/arquillian/container/glassfish/remote_3_1/.

Source file: GlassFishRestDeployableContainer.java

  15 
vote

public ProtocolMetaData deploy(Archive<?> archive) throws DeploymentException {
  if (archive == null) {
    throw new IllegalArgumentException("archive must not be null");
  }
  final String archiveName=archive.getName();
  try {
    final File archiveFile=new File(new File(System.getProperty("java.io.tmpdir")),archiveName);
    archive.as(ZipExporter.class).exportZip(archiveFile,true);
    final FormDataMultiPart form=new FormDataMultiPart();
    form.getBodyParts().add(new FileDataBodyPart("id",archiveFile));
    form.field("contextroot",archiveName.substring(0,archiveName.lastIndexOf(".")),MediaType.TEXT_PLAIN_TYPE);
    deploymentName=archiveName.substring(0,archiveName.lastIndexOf("."));
    form.field("name",deploymentName,MediaType.TEXT_PLAIN_TYPE);
    final String xmlResponse=prepareClient(APPLICATION).type(MediaType.MULTIPART_FORM_DATA_TYPE).post(String.class,form);
    try {
      if (!isCallSuccessful(xmlResponse)) {
        throw new DeploymentException(getMessage(xmlResponse));
      }
    }
 catch (    XPathExpressionException e) {
      throw new DeploymentException("Error finding exit code or message",e);
    }
    final String subComponentsResponse=prepareClient(LIST_SUB_COMPONENTS + this.deploymentName).get(String.class);
    return this.parseForProtocolMetaData(subComponentsResponse);
  }
 catch (  XPathExpressionException e) {
    throw new DeploymentException("Error in creating / deploying archive",e);
  }
}
 

Example 17

From project ATHENA, under directory /components/reports/src/main/java/org/fracturedatlas/athena/reports/serialization/.

Source file: AthenaReportSerializer.java

  15 
vote

@Override public AthenaReport readFrom(java.lang.Class<AthenaReport> type,java.lang.reflect.Type genericType,java.lang.annotation.Annotation[] annotations,MediaType mediaType,MultivaluedMap<java.lang.String,java.lang.String> httpHeaders,java.io.InputStream entityStream){
  Gson gson=JsonUtil.getGson();
  try {
    AthenaReport tran=gson.fromJson(new InputStreamReader(entityStream),AthenaReport.class);
    return tran;
  }
 catch (  JsonParseException e) {
    e.printStackTrace();
    throw e;
  }
}
 

Example 18

From project ATHENA, under directory /core/web-resources/src/main/java/org/fracturedatlas/athena/web/serialization/.

Source file: JsonPropFieldArraySerializer.java

  15 
vote

@Override public void writeTo(PropField[] fields,Class<?> type,Type type1,Annotation[] annotations,MediaType mediaType,MultivaluedMap<String,Object> httpHeaders,OutputStream out) throws IOException, WebApplicationException {
  Gson gson=JsonUtil.getGson();
  ArrayList<PField> outFields=new ArrayList<PField>();
  for (  PropField field : fields) {
    outFields.add(field.toClientField());
  }
  out.write(JsonUtil.getGson().toJson(outFields).getBytes());
}
 

Example 19

From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/rest/service/.

Source file: ScriptRunner.java

  15 
vote

@POST @Path("/sessions/{" + SESSION_ID + "}") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_ATOM_XML}) @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_ATOM_XML}) public Response cli_eval(@PathParam(SESSION_ID) final String sessionId,EvalScript evalScript){
  if (!isAdministrator()) {
    return responseForbidden();
  }
  ScriptSessionManager.ScriptSession scriptSession;
  try {
    scriptSession=checkNotNull(sessionManager.getSession(SessionId.valueOf(sessionId)),"Session instance");
  }
 catch (  IllegalArgumentException e) {
    return responseInternalError(Arrays.asList((e.getMessage())));
  }
  ConsoleOutputBean consoleOutputBean=new ConsoleOutputBean();
  try {
    return responseEvalOk(eval(scriptSession.getScriptEngine(),evalScript.getScript(),evalScript.getBindings(),consoleOutputBean));
  }
 catch (  ScriptException e) {
    return responseScriptError(e,consoleOutputBean.getOutAsString(),consoleOutputBean.getErrAsString());
  }
}
 

Example 20

From project atlassian-rest-cli, under directory /rest-cli-runner/src/main/java/com/galeoconsulting/leonardinius/rest/service/.

Source file: ScriptRunner.java

  15 
vote

@DELETE @Path("/sessions/{" + SESSION_ID + "}") @Consumes({MediaType.APPLICATION_JSON,MediaType.APPLICATION_ATOM_XML}) @Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_ATOM_XML}) public Response deleteSession(@PathParam(SESSION_ID) String sessionId){
  if (!isAdministrator()) {
    return responseForbidden();
  }
  if (sessionManager.removeSession(SessionId.valueOf(sessionId)) == null) {
    return Response.noContent().cacheControl(CacheControl.NO_CACHE).build();
  }
  return Response.ok().cacheControl(CacheControl.NO_CACHE).build();
}
 

Example 21

From project caseconductor-platform, under directory /utest-webservice/utest-webservice-impl/src/main/java/com/utest/webservice/impl/v2/.

Source file: ProductWebServiceImpl.java

  15 
vote

@PUT @Path("/{id}/undo_delete/") @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Override @Secured({Permission.PRODUCT_EDIT,Permission.DELETED_ENTITY_UNDO}) public Boolean undeleteProduct(@Context final UriInfo ui_,@PathParam("id") final Integer productId,@FormParam("originalVersionId") final Integer originalVersionId_) throws Exception {
  UtestSearch search=new UtestSearch();
  search.addFilterEqual("productId",productId);
  productService.undoAllDeletedEntities(ProductComponent.class,search);
  return productService.undoDeletedEntity(Product.class,productId);
}
 

Example 22

From project caseconductor-platform, under directory /utest-webservice/utest-webservice-impl/src/main/java/com/utest/webservice/impl/v2/.

Source file: StaticDataWebServiceImpl.java

  15 
vote

@Override @GET @Path("/errorkeys/") @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Consumes({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) public Set<String> getErrorKeys() throws Exception {
  Set<String> errorKeys=new HashSet<String>();
  for (  DomainException.DomainErrorMessage m : DomainException.DomainErrorMessage.values()) {
    errorKeys.add(m.getMessageKey());
  }
  return errorKeys;
}
 

Example 23

From project cdi-arq-workshop, under directory /arquillian-showcase/jaxrs/src/test/java/com/acme/jaxrs/.

Source file: CustomerResourceClientTest.java

  15 
vote

@Test public void testGetCustomerByIdUsingClientRequest() throws Exception {
  ClientRequest request=new ClientRequest(deploymentUrl.toString() + RESOURCE_PREFIX + "/customer/1");
  request.header("Accept",MediaType.APPLICATION_XML);
  ClientResponse<String> responseObj=request.get(String.class);
  Assert.assertEquals(200,responseObj.getStatus());
  System.out.println("GET /customer/1 HTTP/1.1\n\n" + responseObj.getEntity());
  String response=responseObj.getEntity().replaceAll("<\\?xml.*\\?>","").trim();
  Assert.assertEquals("<customer><id>1</id><name>Acme Corporation</name></customer>",response);
}
 

Example 24

From project cdi-arq-workshop, under directory /arquillian-showcase/jaxrs/src/test/java/com/acme/jaxrs/.

Source file: EnterpriseCustomerResourceClientTest.java

  15 
vote

@Test public void testGetCustomerByIdUsingClientRequest() throws Exception {
  ClientRequest request=new ClientRequest(deploymentUrl.toString() + RESOURCE_PREFIX + "/customer/1");
  request.header("Accept",MediaType.APPLICATION_XML);
  ClientResponse<String> responseObj=request.get(String.class);
  Assert.assertEquals(200,responseObj.getStatus());
  System.out.println("GET /customer/1 HTTP/1.1\n\n" + responseObj.getEntity());
  String response=responseObj.getEntity().replaceAll("<\\?xml.*\\?>","").trim();
  Assert.assertEquals("<customer><id>1</id><name>Acme Corporation</name></customer>",response);
}
 

Example 25

From project cloud-management, under directory /src/main/java/com/proofpoint/cloudmanagement/service/.

Source file: InstanceResource.java

  15 
vote

@GET @Produces(MediaType.APPLICATION_JSON) public Response getInstance(@PathParam("id") String instanceId,@Context UriInfo uriInfo){
  checkNotNull(instanceId);
  checkNotNull(uriInfo);
  for (  Map.Entry<String,InstanceConnector> instanceConnectorEntry : instanceConnectorMap.entrySet()) {
    Instance instance=instanceConnectorEntry.getValue().getInstance(instanceId);
    if (instance != null) {
      return Response.ok(InstanceRepresentation.fromInstance(instance.toBuilder().setProvider(instanceConnectorEntry.getKey()).setHostname(dnsManager.getFullyQualifiedDomainName(instance)).setTags(tagManager.getTags(instance)).build(),constructSelfUri(uriInfo,instanceId))).build();
    }
  }
  return Response.status(Status.NOT_FOUND).build();
}
 

Example 26

From project cloud-management, under directory /src/main/java/com/proofpoint/cloudmanagement/service/.

Source file: InstancesResource.java

  15 
vote

@GET @Produces(MediaType.APPLICATION_JSON) public Response getInstances(@Context UriInfo uriInfo){
  checkNotNull(uriInfo);
  ImmutableSet.Builder<InstanceRepresentation> representationBuilder=new ImmutableSet.Builder<InstanceRepresentation>();
  for (  Map.Entry<String,InstanceConnector> instanceConnectorEntry : instanceConnectorMap.entrySet()) {
    for (    Instance instance : instanceConnectorEntry.getValue().getAllInstances()) {
      representationBuilder.add(InstanceRepresentation.fromInstance(instance.toBuilder().setProvider(instanceConnectorEntry.getKey()).setHostname(dnsManager.getFullyQualifiedDomainName(instance)).setTags(tagManager.getTags(instance)).build(),InstanceResource.constructSelfUri(uriInfo,instance.getId())));
    }
  }
  return Response.ok(representationBuilder.build()).build();
}
 

Example 27

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/openstack/.

Source file: OpenstackCloudDriver.java

  15 
vote

private Node getNode(final String nodeId,final String token) throws OpenstackException {
  final Node node=new Node();
  String response="";
  try {
    response=service.path(this.pathPrefix + "servers/" + nodeId).header("X-Auth-Token",token).accept(MediaType.APPLICATION_XML).get(String.class);
    final DocumentBuilder documentBuilder=createDocumentBuilder();
    final Document xmlDoc=documentBuilder.parse(new InputSource(new StringReader(response)));
    node.setId(xpath.evaluate("/server/@id",xmlDoc));
    node.setStatus(xpath.evaluate("/server/@status",xmlDoc));
    node.setName(xpath.evaluate("/server/@name",xmlDoc));
    final NodeList addresses=(NodeList)xpath.evaluate("/server/addresses/network/ip/@addr",xmlDoc,XPathConstants.NODESET);
    if (node.getStatus().equalsIgnoreCase(MACHINE_STATUS_ACTIVE)) {
      if (addresses.getLength() != 2) {
        throw new IllegalStateException("Expected 2 addresses, private and public, got " + addresses.getLength() + " addresses");
      }
      node.setPrivateIp(addresses.item(0).getTextContent());
      node.setPublicIp(addresses.item(1).getTextContent());
    }
  }
 catch (  final XPathExpressionException e) {
    throw new OpenstackException("Failed to parse XML Response from server. Response was: " + response + ", Error was: "+ e.getMessage(),e);
  }
catch (  final SAXException e) {
    throw new OpenstackException("Failed to parse XML Response from server. Response was: " + response + ", Error was: "+ e.getMessage(),e);
  }
catch (  final IOException e) {
    throw new OpenstackException("Failed to send request to server. Response was: " + response + ", Error was: "+ e.getMessage(),e);
  }
catch (  UniformInterfaceException e) {
    throw new OpenstackException("Failed on get for server with node id " + nodeId + ". Response was: "+ response+ ", Error was: "+ e.getMessage(),e);
  }
  return node;
}
 

Example 28

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/openstack/.

Source file: OpenstackCloudDriver.java

  15 
vote

private List<String> listServerIds(final String token) throws OpenstackException {
  String response=null;
  try {
    response=service.path(this.pathPrefix + "servers").header("X-Auth-Token",token).accept(MediaType.APPLICATION_XML).get(String.class);
    final DocumentBuilder documentBuilder=createDocumentBuilder();
    final Document xmlDoc=documentBuilder.parse(new InputSource(new StringReader(response)));
    final NodeList idNodes=(NodeList)xpath.evaluate("/servers/server/@id",xmlDoc,XPathConstants.NODESET);
    final int howmany=idNodes.getLength();
    final List<String> ids=new ArrayList<String>(howmany);
    for (int i=0; i < howmany; i++) {
      ids.add(idNodes.item(i).getTextContent());
    }
    return ids;
  }
 catch (  final UniformInterfaceException e) {
    final String responseEntity=e.getResponse().getEntity(String.class);
    throw new OpenstackException(e + " Response entity: " + responseEntity,e);
  }
catch (  final SAXException e) {
    throw new OpenstackException("Failed to parse XML Response from server. Response was: " + response + ", Error was: "+ e.getMessage(),e);
  }
catch (  final XPathException e) {
    throw new OpenstackException("Failed to parse XML Response from server. Response was: " + response + ", Error was: "+ e.getMessage(),e);
  }
catch (  final IOException e) {
    throw new OpenstackException("Failed to send request to server. Response was: " + response + ", Error was: "+ e.getMessage(),e);
  }
}