Java Code Examples for javax.ws.rs.core.MediaType#equals()

The following examples show how to use javax.ws.rs.core.MediaType#equals() . 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: ApiBaseTestCase.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected String marshall(Object result, MediaType mediaType) throws Throwable {
	if (null != mediaType && mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
		JSONProvider jsonProvider = (JSONProvider) super.getApplicationContext().getBean("jsonProvider");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		jsonProvider.writeTo(result, result.getClass().getGenericSuperclass(), 
				result.getClass().getAnnotations(), mediaType, null, baos);
		return new String(baos.toByteArray(), "UTF-8");
	} else {
		JAXBContext context = JAXBContext.newInstance(result.getClass());
		Marshaller marshaller = context.createMarshaller();
		marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		marshaller.setProperty("com.sun.xml.bind.marshaller.CharacterEscapeHandler", new CDataCharacterEscapeHandler());
		StringWriter writer = new StringWriter();
		marshaller.marshal(result, writer);
		return writer.toString();
	}
}
 
Example 2
Source File: ImageWriter.java    From SciGraph with Apache License 2.0 6 votes vote down vote up
@Override
public void writeTo(Graph data, Class<?> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, Object> headers, OutputStream out) throws IOException {
  Integer width = Integer.parseInt(Optional.ofNullable(request.getParameter("width")).orElse(DEFAULT_WIDTH));
  Integer height = Integer.parseInt(Optional.ofNullable(request.getParameter("height")).orElse(DEFAULT_HEIGHT));
  String layoutName = Optional.ofNullable(request.getParameter("layout")).orElse(DEFAULT_LAYOUT);

  GraphJung<Graph> graph = new GraphJung<Graph>(data);
  AbstractLayout<Vertex, Edge> layout = getLayout(graph, layoutName);
  layout.setSize(new Dimension(width, height));

  BasicVisualizationServer<Vertex, Edge> viz = new BasicVisualizationServer<>(layout);
  viz.setPreferredSize(new Dimension(width, height));
  viz.getRenderContext().setEdgeLabelTransformer(edgeLabelTransformer);
  viz.getRenderContext().setVertexLabelTransformer(vertexLabelTransformer);
  viz.getRenderContext().setVertexFillPaintTransformer(vertexColorTransformer);

  BufferedImage bi = renderImage(viz);
  String imageType = null;
  if (mediaType.equals(CustomMediaTypes.IMAGE_JPEG_TYPE)) {
    imageType = "jpg";
  } else if (mediaType.equals(CustomMediaTypes.IMAGE_PNG_TYPE)) {
    imageType = "png";
  }
  ImageIO.write(bi, imageType, out);
}
 
Example 3
Source File: ApiWidgetTypeInterface.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String getApiResourceUrl(Object object, String applicationBaseUrl, String langCode, MediaType mediaType) {
	if (!(object instanceof WidgetType) || null == applicationBaseUrl || null == langCode) {
		return null;
	}
	WidgetType widgetType = (WidgetType) object;
	StringBuilder stringBuilder = new StringBuilder(applicationBaseUrl);
	stringBuilder.append("api/rs/").append(langCode).append("/core/widgetType");// ?code=").append(widgetType.getCode());
	if (null == mediaType || mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
		stringBuilder.append(".xml");
	} else {
		stringBuilder.append(".json");
	}
	stringBuilder.append("?code=").append(widgetType.getCode());
	return stringBuilder.toString();
}
 
Example 4
Source File: StaashAuditFilter.java    From staash with Apache License 2.0 6 votes vote down vote up
/**
 * Private helper that adds the request-id to the response payload.
 * @param response
 */
private void addRequestIdToResponse(ContainerResponse response) {
	
	// The request-id to be injected in the response
	String requestId = StaashRequestContext.getRequestId();
	
	// The key response attributes
	int status = response.getStatus();
	MediaType mediaType = response.getMediaType();
	
	if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
		
		String message = (String)response.getEntity();
		JsonObject json = new JsonObject(message);
		json.putString("request-id", requestId);
		
		Response newJerseyResponse = Response.status(status).type(mediaType).entity(json.toString()).build();
		response.setResponse(newJerseyResponse);
	}
		
	// Add the request id to the response regardless of the media type, 
	// this allows non json responses to have a request id in the response
	response.getHttpHeaders().add("x-nflx-staash-request-id", requestId);
}
 
Example 5
Source File: UDFCatalogResource.java    From streamline with Apache License 2.0 6 votes vote down vote up
/**
 * Add a new UDF.
 * <p>
 * curl -X POST 'http://localhost:8080/api/v1/catalog/udfs' -F udfJarFile=/tmp/foo-function.jar
 * -F udfConfig='{"name":"Foo", "description": "testing", "type":"FUNCTION", "className":"com.test.Foo"};type=application/json'
 * </p>
 */
@Timed
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/udfs")
public Response addUDF(@FormDataParam("udfJarFile") final InputStream inputStream,
                       @FormDataParam("udfJarFile") final FormDataContentDisposition contentDispositionHeader,
                       @FormDataParam("udfConfig") final FormDataBodyPart udfConfig,
                       @FormDataParam("builtin") final boolean builtin,
                       @Context SecurityContext securityContext) throws Exception {
    SecurityUtil.checkRole(authorizer, securityContext, Roles.ROLE_UDF_ADMIN);
    MediaType mediaType = udfConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    UDF udf = udfConfig.getValueAs(UDF.class);
    processUdf(inputStream, udf, true, builtin);
    UDF createdUdf = catalogService.addUDF(udf);
    SecurityUtil.addAcl(authorizer, securityContext, UDF.NAMESPACE, createdUdf.getId(), EnumSet.allOf(Permission.class));
    return WSUtils.respondEntity(createdUdf, CREATED);
}
 
Example 6
Source File: NotifierInfoCatalogResource.java    From streamline with Apache License 2.0 5 votes vote down vote up
/**
 * Sample request :
 * <pre>
 * curl -X POST 'http://localhost:8080/api/v1/catalog/notifiers' -F notifierJarFile=/tmp/email-notifier.jar
 * -F notifierConfig='{
 *  "name":"email_notifier",
 *  "description": "testing",
 * "className":"com.hortonworks.streamline.streams.notifiers.EmailNotifier",
 *   "properties": {
 *     "username": "[email protected]",
 *     "password": "testing12",
 *     "host": "smtp.gmail.com",
 *     "port": "587",
 *     "starttls": "true",
 *     "debug": "true"
 *     },
 *   "fieldValues": {
 *     "from": "[email protected]",
 *     "to": "[email protected]",
 *     "subject": "Testing email notifications",
 *     "contentType": "text/plain",
 *     "body": "default body"
 *     }
 * };type=application/json'
 * </pre>
 */
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/notifiers")
@Timed
public Response addNotifier(@FormDataParam("notifierJarFile") final InputStream inputStream,
                            @FormDataParam("notifierJarFile") final FormDataContentDisposition contentDispositionHeader,
                            @FormDataParam("notifierConfig") final FormDataBodyPart notifierConfig,
                            @Context SecurityContext securityContext) throws IOException {
    SecurityUtil.checkRole(authorizer, securityContext, Roles.ROLE_NOTIFIER_ADMIN);
    MediaType mediaType = notifierConfig.getMediaType();
    LOG.debug("Media type {}", mediaType);
    if (!mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        throw new UnsupportedMediaTypeException(mediaType.toString());
    }
    Notifier notifier = notifierConfig.getValueAs(Notifier.class);
    Collection<Notifier> existing = null;
    existing = catalogService.listNotifierInfos(Collections.singletonList(new QueryParam(Notifier.NOTIFIER_NAME, notifier.getName())));
    if (existing != null && !existing.isEmpty()) {
        LOG.warn("Received a post request for an already registered notifier. Not creating entity for " + notifier);
        return WSUtils.respondEntity(notifier, CONFLICT);
    }
    String jarFileName = uploadJar(inputStream, notifier.getName());
    notifier.setJarFileName(jarFileName);
    Notifier createdNotifier = catalogService.addNotifierInfo(notifier);
    SecurityUtil.addAcl(authorizer, securityContext, Notifier.NAMESPACE, createdNotifier.getId(),
            EnumSet.allOf(Permission.class));
    return WSUtils.respondEntity(createdNotifier, CREATED);
}
 
Example 7
Source File: ApiGuiFragmentInterface.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private String getApiResourceUrl(String fragmentCode, String applicationBaseUrl, String langCode, MediaType mediaType) {
	if (null == fragmentCode || null == applicationBaseUrl || null == langCode) {
		return null;
	}
	StringBuilder stringBuilder = new StringBuilder(applicationBaseUrl);
	stringBuilder.append("api/rs/").append(langCode).append("/core/guiFragment");//?code=").append(fragmentCode);
	if (null == mediaType || mediaType.equals(MediaType.APPLICATION_XML_TYPE)) {
		stringBuilder.append(".xml");
	} else {
		stringBuilder.append(".json");
	}
	stringBuilder.append("?code=").append(fragmentCode);
	return stringBuilder.toString();
}
 
Example 8
Source File: AtomBookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/books/feed")
@Produces({"application/atom+xml", "application/json" })
public Feed getBooksAsFeed(@Context UriInfo uParam) {

    MediaType mt = headers.getMediaType();
    if (!mt.equals(MediaType.valueOf(MediaType.MEDIA_TYPE_WILDCARD))
        && !mt.equals(MediaType.APPLICATION_JSON_TYPE)
        && !mt.equals(MediaType.APPLICATION_ATOM_XML_TYPE)) {
        throw new WebApplicationException();
    }

    return doGetBookAsFeed(uParam);
}
 
Example 9
Source File: BinaryProcessor.java    From swagger-inflector with Apache License 2.0 5 votes vote down vote up
@Override
public Object process(MediaType mediaType, InputStream entityStream, JavaType javaType) {
    try {
        if (mediaType.equals(MediaType.APPLICATION_OCTET_STREAM_TYPE)) {
            return entityStream;
        }else if (mediaType.equals(MediaType.MULTIPART_FORM_DATA_TYPE)){

        }else if (mediaType.equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE)){

        }
    } catch (Exception e) {
        LOGGER.error("unable to extract entity from content-type `" + mediaType, e);
    }
    return null;
}
 
Example 10
Source File: DataSourceProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void setContentTypeIfNeeded(MediaType type,
    MultivaluedMap<String, Object> headers, String ct) {

    if (!StringUtils.isEmpty(ct) && !type.equals(JAXRSUtils.toMediaType(ct))) {
        headers.putSingle("Content-Type", ct);
    }
}
 
Example 11
Source File: Util.java    From swagger-petstore with Apache License 2.0 5 votes vote down vote up
public static MediaType getMediaType(final RequestContext request) {
    MediaType outputType = MediaType.APPLICATION_JSON_TYPE;

    final List<String> accept = request.getHeaders().get("Accept");
    String responseMediaType = "";
    if (accept != null && accept.get(0) != null) {
        responseMediaType = accept.get(0);
    }
    if (MediaType.APPLICATION_XML.equals(responseMediaType)) {
        return MediaType.APPLICATION_XML_TYPE;
    }

    boolean isJsonOK = false;
    boolean isYamlOK = false;

    final MediaType yamlMediaType = new MediaType(APPLICATION, YAML);

    for (final MediaType mediaType : request.getAcceptableMediaTypes()) {
        if (mediaType.equals(MediaType.APPLICATION_JSON_TYPE)) {
            isJsonOK = true;
        } else if (mediaType.equals(yamlMediaType)) {
            isYamlOK = true;
        }
    }

    if (isYamlOK && !isJsonOK) {
        outputType = yamlMediaType;
    }

    return outputType;
}
 
Example 12
Source File: TestRMWebServicesAppsModification.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 90000)
public void testAppMove() throws Exception {

  client().addFilter(new LoggingFilter(System.out));

  boolean isCapacityScheduler =
      rm.getResourceScheduler() instanceof CapacityScheduler;

  // default root queue allows anyone to have admin acl
  CapacitySchedulerConfiguration csconf =
      new CapacitySchedulerConfiguration();
  String[] queues = { "default", "test" };
  csconf.setQueues("root", queues);
  csconf.setCapacity("root.default", 50.0f);
  csconf.setCapacity("root.test", 50.0f);
  csconf.setAcl("root", QueueACL.ADMINISTER_QUEUE, "someuser");
  csconf.setAcl("root.default", QueueACL.ADMINISTER_QUEUE, "someuser");
  csconf.setAcl("root.test", QueueACL.ADMINISTER_QUEUE, "someuser");
  rm.getResourceScheduler().reinitialize(csconf, rm.getRMContext());

  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  String[] mediaTypes =
      { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
  MediaType[] contentTypes =
      { MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
  for (String mediaType : mediaTypes) {
    for (MediaType contentType : contentTypes) {
      RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
      amNodeManager.nodeHeartbeat(true);
      AppQueue targetQueue = new AppQueue("test");
      Object entity;
      if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        entity = appQueueToJSON(targetQueue);
      } else {
        entity = targetQueue;
      }
      ClientResponse response =
          this
            .constructWebResource("apps", app.getApplicationId().toString(),
              "queue").entity(entity, contentType).accept(mediaType)
            .put(ClientResponse.class);

      if (!isAuthenticationEnabled()) {
        assertEquals(Status.UNAUTHORIZED, response.getClientResponseStatus());
        continue;
      }
      assertEquals(Status.OK, response.getClientResponseStatus());
      String expectedQueue = "test";
      if(!isCapacityScheduler) {
        expectedQueue = "root.test";
      }
      if (mediaType.equals(MediaType.APPLICATION_JSON)) {
        verifyAppQueueJson(response, expectedQueue);
      } else {
        verifyAppQueueXML(response, expectedQueue);
      }
      Assert.assertEquals(expectedQueue, app.getQueue());

      // check unauthorized
      app = rm.submitApp(CONTAINER_MB, "", "someuser");
      amNodeManager.nodeHeartbeat(true);
      response =
          this
            .constructWebResource("apps", app.getApplicationId().toString(),
              "queue").entity(entity, contentType).accept(mediaType)
            .put(ClientResponse.class);
      assertEquals(Status.FORBIDDEN, response.getClientResponseStatus());
      if(isCapacityScheduler) {
        Assert.assertEquals("default", app.getQueue());
      }
      else {
        Assert.assertEquals("root.someuser", app.getQueue());
      }

    }
  }
  rm.stop();
}
 
Example 13
Source File: PlainTextMultipartUploadReader.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isReadable(Class<?> type, Type genericType,
    Annotation[] annotations, MediaType mediaType) {
  return type.equals(CompleteMultipartUploadRequest.class)
      && mediaType.equals(MediaType.TEXT_PLAIN_TYPE);
}
 
Example 14
Source File: HalMessageBodyWriter.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
@Override
public boolean isWriteable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return HalRepresentation.class.isAssignableFrom(
            type) && (mediaType == MediaType.APPLICATION_JSON_TYPE || mediaType.equals(
            new MediaType("application", "hal+json")));
}
 
Example 15
Source File: TestRMWebServicesAppsModification.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Test
public void testSingleAppKillInvalidState() throws Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);

  String[] mediaTypes =
      { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
  MediaType[] contentTypes =
      { MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
  String[] targetStates =
      { YarnApplicationState.FINISHED.toString(), "blah" };

  for (String mediaType : mediaTypes) {
    for (MediaType contentType : contentTypes) {
      for (String targetStateString : targetStates) {
        RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
        amNodeManager.nodeHeartbeat(true);
        ClientResponse response;
        AppState targetState = new AppState(targetStateString);
        Object entity;
        if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
          entity = appStateToJSON(targetState);
        } else {
          entity = targetState;
        }
        response =
            this
              .constructWebResource("apps",
                app.getApplicationId().toString(), "state")
              .entity(entity, contentType).accept(mediaType)
              .put(ClientResponse.class);

        if (!isAuthenticationEnabled()) {
          assertEquals(Status.UNAUTHORIZED,
            response.getClientResponseStatus());
          continue;
        }
        assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
      }
    }
  }

  rm.stop();
}
 
Example 16
Source File: DcFormatWriterFactory.java    From io with Apache License 2.0 4 votes vote down vote up
/**
 * フォーマットライターのゲッター.
 * @param <T> 型
 * @param targetType フォーマットライターのタイプ
 * @param acceptTypes アクセプトタイプ
 * @param format フォーマット
 * @param callback コールバック
 * @return フォーマットライター
 */
@SuppressWarnings("unchecked")
public static <T> FormatWriter<T> getFormatWriter(Class<T> targetType,
        List<MediaType> acceptTypes,
        String format,
        String callback) {

    FormatType type = null;

    // if format is explicitly specified, use that
    if (format != null) {
        type = FormatType.parse(format);
    }

    // if header accepts json, use that
    if (type == null && acceptTypes != null) {
        for (MediaType acceptType : acceptTypes) {
            if (acceptType.equals(MediaType.APPLICATION_JSON_TYPE)) {
                type = FormatType.JSON;
                break;
            }
        }
    }

    // else default to atom
    if (type == null) {
        type = FormatType.ATOM;
    }

    FormatWriters formatWriters = null;
    if (type.equals(FormatType.JSON)) {
        formatWriters = new JsonWriters(callback);
    } else {
        formatWriters = new AtomWriters();
    }

    if (targetType.equals(EdmDataServices.class)) {
        return (FormatWriter<T>) formatWriters.getServiceDocumentFormatWriter();
    }

    if (targetType.equals(EntitiesResponse.class)) {
        return (FormatWriter<T>) formatWriters.getFeedFormatWriter();
    }

    if (targetType.equals(EntityResponse.class)) {
        return (FormatWriter<T>) formatWriters.getEntryFormatWriter();
    }

    if (targetType.equals(PropertyResponse.class)) {
        return (FormatWriter<T>) formatWriters.getPropertyFormatWriter();
    }

    if (Entry.class.isAssignableFrom(targetType)) {
        return (FormatWriter<T>) formatWriters.getRequestEntryFormatWriter();
    }

    if (SingleLink.class.isAssignableFrom(targetType)) {
        return (FormatWriter<T>) formatWriters.getSingleLinkFormatWriter();
    }

    if (SingleLinks.class.isAssignableFrom(targetType)) {
        return (FormatWriter<T>) formatWriters.getSingleLinksFormatWriter();
    }

    if (targetType.equals(ComplexObjectResponse.class)) {
        return (FormatWriter<T>) formatWriters.getComplexObjectFormatWriter();
    }

    if (targetType.equals(CollectionResponse.class)) {
        return (FormatWriter<T>) formatWriters.getCollectionFormatWriter();
    }

    throw new IllegalArgumentException("Unable to locate format writer for " + targetType.getName()
            + " and format " + type);

}
 
Example 17
Source File: TestRMWebServicesAppsModification.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 90000)
public void testAppMove() throws Exception {

  client().addFilter(new LoggingFilter(System.out));

  boolean isCapacityScheduler =
      rm.getResourceScheduler() instanceof CapacityScheduler;

  // default root queue allows anyone to have admin acl
  CapacitySchedulerConfiguration csconf =
      new CapacitySchedulerConfiguration();
  String[] queues = { "default", "test" };
  csconf.setQueues("root", queues);
  csconf.setCapacity("root.default", 50.0f);
  csconf.setCapacity("root.test", 50.0f);
  csconf.setAcl("root", QueueACL.ADMINISTER_QUEUE, "someuser");
  csconf.setAcl("root.default", QueueACL.ADMINISTER_QUEUE, "someuser");
  csconf.setAcl("root.test", QueueACL.ADMINISTER_QUEUE, "someuser");
  rm.getResourceScheduler().reinitialize(csconf, rm.getRMContext());

  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  String[] mediaTypes =
      { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
  MediaType[] contentTypes =
      { MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
  for (String mediaType : mediaTypes) {
    for (MediaType contentType : contentTypes) {
      RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
      amNodeManager.nodeHeartbeat(true);
      AppQueue targetQueue = new AppQueue("test");
      Object entity;
      if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        entity = appQueueToJSON(targetQueue);
      } else {
        entity = targetQueue;
      }
      ClientResponse response =
          this
            .constructWebResource("apps", app.getApplicationId().toString(),
              "queue").entity(entity, contentType).accept(mediaType)
            .put(ClientResponse.class);

      if (!isAuthenticationEnabled()) {
        assertEquals(Status.UNAUTHORIZED, response.getClientResponseStatus());
        continue;
      }
      assertEquals(Status.OK, response.getClientResponseStatus());
      String expectedQueue = "test";
      if(!isCapacityScheduler) {
        expectedQueue = "root.test";
      }
      if (mediaType.equals(MediaType.APPLICATION_JSON)) {
        verifyAppQueueJson(response, expectedQueue);
      } else {
        verifyAppQueueXML(response, expectedQueue);
      }
      Assert.assertEquals(expectedQueue, app.getQueue());

      // check unauthorized
      app = rm.submitApp(CONTAINER_MB, "", "someuser");
      amNodeManager.nodeHeartbeat(true);
      response =
          this
            .constructWebResource("apps", app.getApplicationId().toString(),
              "queue").entity(entity, contentType).accept(mediaType)
            .put(ClientResponse.class);
      assertEquals(Status.FORBIDDEN, response.getClientResponseStatus());
      if(isCapacityScheduler) {
        Assert.assertEquals("default", app.getQueue());
      }
      else {
        Assert.assertEquals("root.someuser", app.getQueue());
      }

    }
  }
  rm.stop();
}
 
Example 18
Source File: TestRMWebServicesAppsModification.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test
public void testSingleAppKillInvalidState() throws Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);

  String[] mediaTypes =
      { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
  MediaType[] contentTypes =
      { MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
  String[] targetStates =
      { YarnApplicationState.FINISHED.toString(), "blah" };

  for (String mediaType : mediaTypes) {
    for (MediaType contentType : contentTypes) {
      for (String targetStateString : targetStates) {
        RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
        amNodeManager.nodeHeartbeat(true);
        ClientResponse response;
        AppState targetState = new AppState(targetStateString);
        Object entity;
        if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
          entity = appStateToJSON(targetState);
        } else {
          entity = targetState;
        }
        response =
            this
              .constructWebResource("apps",
                app.getApplicationId().toString(), "state")
              .entity(entity, contentType).accept(mediaType)
              .put(ClientResponse.class);

        if (!isAuthenticationEnabled()) {
          assertEquals(Status.UNAUTHORIZED,
            response.getClientResponseStatus());
          continue;
        }
        assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
      }
    }
  }

  rm.stop();
}
 
Example 19
Source File: TestRMWebServicesAppsModification.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Test(timeout = 120000)
public void testSingleAppKill() throws Exception {
  rm.start();
  MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
  String[] mediaTypes =
      { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML };
  MediaType[] contentTypes =
      { MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_XML_TYPE };
  for (String mediaType : mediaTypes) {
    for (MediaType contentType : contentTypes) {
      RMApp app = rm.submitApp(CONTAINER_MB, "", webserviceUserName);
      amNodeManager.nodeHeartbeat(true);

      AppState targetState =
          new AppState(YarnApplicationState.KILLED.toString());

      Object entity;
      if (contentType.equals(MediaType.APPLICATION_JSON_TYPE)) {
        entity = appStateToJSON(targetState);
      } else {
        entity = targetState;
      }
      ClientResponse response =
          this
            .constructWebResource("apps", app.getApplicationId().toString(),
              "state").entity(entity, contentType).accept(mediaType)
            .put(ClientResponse.class);

      if (!isAuthenticationEnabled()) {
        assertEquals(Status.UNAUTHORIZED, response.getClientResponseStatus());
        continue;
      }
      assertEquals(Status.ACCEPTED, response.getClientResponseStatus());
      if (mediaType.equals(MediaType.APPLICATION_JSON)) {
        verifyAppStateJson(response, RMAppState.FINAL_SAVING,
          RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
      } else {
        verifyAppStateXML(response, RMAppState.FINAL_SAVING,
          RMAppState.KILLED, RMAppState.KILLING, RMAppState.ACCEPTED);
      }

      String locationHeaderValue =
          response.getHeaders().getFirst(HttpHeaders.LOCATION);
      Client c = Client.create();
      WebResource tmp = c.resource(locationHeaderValue);
      if (isAuthenticationEnabled()) {
        tmp = tmp.queryParam("user.name", webserviceUserName);
      }
      response = tmp.get(ClientResponse.class);
      assertEquals(Status.OK, response.getClientResponseStatus());
      assertTrue(locationHeaderValue.endsWith("/ws/v1/cluster/apps/"
          + app.getApplicationId().toString() + "/state"));

      while (true) {
        Thread.sleep(100);
        response =
            this
              .constructWebResource("apps",
                app.getApplicationId().toString(), "state").accept(mediaType)
              .entity(entity, contentType).put(ClientResponse.class);
        assertTrue((response.getClientResponseStatus() == Status.ACCEPTED)
            || (response.getClientResponseStatus() == Status.OK));
        if (response.getClientResponseStatus() == Status.OK) {
          assertEquals(RMAppState.KILLED, app.getState());
          if (mediaType.equals(MediaType.APPLICATION_JSON)) {
            verifyAppStateJson(response, RMAppState.KILLED);
          } else {
            verifyAppStateXML(response, RMAppState.KILLED);
          }
          break;
        }
      }
    }
  }

  rm.stop();
}
 
Example 20
Source File: ApplicationFooProvider.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    return mediaType.equals(new MediaType("application", "foo"));
}