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

The following are top voted examples for showing how to use javax.ws.rs.core.MediaType. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: cloudkarafka-broker   File: CloudKarafkaAdminService.java   View source code 7 votes vote down vote up
/**
 * Create a broker Instance
 *
 * @param brokerName
 * @return
 * @throws CloudKarafkaServiceException
 */
public CloudKarafkaCreateInstanceResponse createInstance(final String brokerName,
                                                         final String plan) throws CloudKarafkaServiceException {
    // build input form
    final MultivaluedMap<String, String> form = new MultivaluedHashMap<>();
    form.add("name", brokerName);
    form.add("plan", plan);
    form.add("region", brokerConfig.getCloudKarafkaRegion());

    //build post request
    final String target = String.format("%s/%s", brokerConfig.getCloudkarafkaApiUrl(), "instances");
    final WebTarget webTarget = client.target(target);

    // call create broker instances API
    return webTarget.request(MediaType.APPLICATION_JSON)
            .post(Entity.form(form), CloudKarafkaCreateInstanceResponse.class);
}
 
Example 2
Project: personium-core   File: ExtCellUtils.java   View source code 6 votes vote down vote up
/**
 * NP経由でExtCellを作成するユーティリティ.
 * @param cellName セル名
 * @param token トークン
 * @param extCellUrl ExtCellのUrl
 * @param srcEntitySet ソース側エンティティセット名
 * @param srcEntitySetKey ソース側エンティティのキー
 * @param code レスポンスコード
 * @return レスポンス
 */
@SuppressWarnings("unchecked")
public static TResponse createViaNP(
        final String token,
        final String cellName,
        final String extCellUrl,
        final String srcEntitySet,
        final String srcEntitySetKey,
        final int code) {
    JSONObject body = new JSONObject();
    body.put("Url", extCellUrl);

    return Http.request("createNP.txt")
            .with("token", token)
            .with("accept", MediaType.APPLICATION_JSON)
            .with("contentType", MediaType.APPLICATION_JSON)
            .with("cell", cellName)
            .with("entityType", srcEntitySet)
            .with("id", srcEntitySetKey)
            .with("navPropName", "_ExtCell")
            .with("body", body.toString())
            .returns()
            .statusCode(code);
}
 
Example 3
Project: hadoop   File: TestAMWebServicesJobs.java   View source code 6 votes vote down vote up
@Test
public void testJobCounters() throws JSONException, Exception {
  WebResource r = resource();
  Map<JobId, Job> jobsMap = appContext.getAllJobs();
  for (JobId id : jobsMap.keySet()) {
    String jobId = MRApps.toString(id);

    ClientResponse response = r.path("ws").path("v1").path("mapreduce")
        .path("jobs").path(jobId).path("counters")
        .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
    JSONObject json = response.getEntity(JSONObject.class);
    assertEquals("incorrect number of elements", 1, json.length());
    JSONObject info = json.getJSONObject("jobCounters");
    verifyAMJobCounters(info, jobsMap.get(id));
  }
}
 
Example 4
Project: personium-core   File: UserDataExpandTest.java   View source code 6 votes vote down vote up
/**
 * Keyあり取得時にexpandに存在しないリースを指定した場合に400が返却されること.
 */
@Test
public final void Keyあり取得時にexpandに存在しないリースを指定した場合に400が返却されること() {

    try {
        // データ作成
        createData();

        // $expandを指定してデータを取得
        Http.request("box/odatacol/list.txt")
                .with("cell", Setup.TEST_CELL1)
                .with("box", Setup.TEST_BOX1)
                .with("collection", Setup.TEST_ODATA)
                .with("entityType", navPropName + "('" + fromUserDataId + "')")
                .with("query", "?\\$expand=_test")
                .with("accept", MediaType.APPLICATION_JSON)
                .with("token", PersoniumUnitConfig.getMasterToken())
                .returns()
                .statusCode(HttpStatus.SC_BAD_REQUEST)
                .debug();

    } finally {
        // データ削除
        deleteData();
    }
}
 
Example 5
Project: redirector   File: NamespaceControllerOffline.java   View source code 6 votes vote down vote up
@POST
@Path("validate")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response addNamespacedList(final SnapshotList snapshotList) {
    NamespacedList namespace = (NamespacedList)snapshotList.getEntityToSave();

    if (!namespacedListsService.getNamespaceDuplicates(namespace, snapshotList.getNamespaces()).isEmpty()) {
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)
                .entity(new ErrorMessage("There are duplicates in the namespaced list.")).build());
    }

    try {
        ModelValidationFacade.validateNamespacedList(namespace);
        namespace.updateVersion();
        namespace.setValueCount(namespace.getValueSet().size());
    } catch (ExpressionValidationException ex) {
        String error = String.format("Failed to save namespace '%s' due to validation error(s). %s",  namespace.getName(), ex.getMessage());
        throw new WebApplicationException(error, ex, Response.Status.BAD_REQUEST);
    }

    return Response.ok(namespace).build();
}
 
Example 6
Project: vertx-zero   File: Answer.java   View source code 6 votes vote down vote up
public static void reply(
        final RoutingContext context,
        final Envelop envelop) {
    // 1. Get response reference
    final HttpServerResponse response
            = context.response();
    // 2. Set response status
    final HttpStatusCode code = envelop.status();
    response.setStatusCode(code.code());
    response.setStatusMessage(code.message());
    response.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    // 3. Response process
    if (!response.ended()) {
        response.end(envelop.response());
    }
    response.close();
}
 
Example 7
Project: hadoop-oss   File: KMS.java   View source code 6 votes vote down vote up
@GET
@Path(KMSRESTConstants.KEY_PAIR_VERSION_RESOURCE + "/{versionName:.*}")
@Produces(MediaType.APPLICATION_JSON)
public Response getKeyVersionPair(
    @PathParam("versionName") final String versionName) throws Exception {
  UserGroupInformation user = HttpUserGroupInformation.get();
  KMSClientProvider.checkNotEmpty(versionName, "versionName");
  KMSWebApp.getKeyCallsMeter().mark();
  assertAccess(KMSACLs.Type.GET, user, KMSOp.GET_KEY_VERSION);

  KeyPairVersion keyVersion = user.doAs(
      new PrivilegedExceptionAction<KeyPairVersion>() {
        @Override
        public KeyPairVersion run() throws Exception {
          return provider.getKeyPairVersion(versionName);
        }
      }
  );

  if (keyVersion != null) {
    kmsAudit.ok(user, KMSOp.GET_KEY_VERSION, keyVersion.getName(), "");
  }
  Object json = KMSServerJSONUtils.toJSON(keyVersion);
  return Response.ok().type(MediaType.APPLICATION_JSON).entity(json).build();
}
 
Example 8
Project: personium-core   File: UserDataListFilterBooleanTest.java   View source code 6 votes vote down vote up
/**
 * UserDataに前方一致検索クエリに真偽値trueを指定した場合ステータスコード400が返却されること.
 */
@Test
public final void UserDataに前方一致検索クエリに真偽値trueを指定した場合ステータスコード400が返却されること() {
    // ユーザデータの一覧取得
    String sdEntityTypeName = "SalesDetail";

    Http.request("box/odatacol/list.txt")
            .with("cell", cellName)
            .with("box", boxName)
            .with("collection", colName)
            .with("entityType", sdEntityTypeName)
            .with("query", "?\\$filter=startswith%28truth%2ctrue%29")
            .with("accept", MediaType.APPLICATION_JSON)
            .with("token", PersoniumUnitConfig.getMasterToken())
            .returns()
            .statusCode(HttpStatus.SC_BAD_REQUEST)
            .debug();
}
 
Example 9
Project: redirector   File: RuleNameIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void testInvalidRuleName() throws InstantiationException, IllegalAccessException {

    
    IfExpressionBuilder builder = new IfExpressionBuilder();
    IfExpression expression = builder.
            withRuleName(invalidRuleName).
            withExpression(newSingleParamExpression(Equals.class, "param1", "value1")).
            withExpression(newSingleParamExpression(Matches.class, "param2", "value2")).
            withExpression(newSingleParamExpression(NotEqual.class, "param3", "value3")).
            withExpression(newSingleParamExpression(LessThan.class, "param4", "4")).
            withReturnStatement(newSimpleServerForFlavor("1.1")).build();


    // now trying to post rule with invalid name
    WebTarget webTarget = HttpTestServerHelper.target().path(RULES_SERVICE_PATH).path(SERVICE_NAME).path(expression.getId());
    ValidationState error = ServiceHelper.post(webTarget, expression, MediaType.APPLICATION_JSON, ValidationState.class, true);

    // should get error ValidationState.ErrorType.InvalidRuleName
    Assert.assertEquals(1, error.getErrors().size());
    Assert.assertEquals(ValidationState.ErrorType.InvalidRuleName, error.getErrors().keySet().iterator().next());
}
 
Example 10
Project: hadoop   File: TestHsWebServicesJobsQuery.java   View source code 6 votes vote down vote up
@Test
public void testJobsQueryFinishTimeBeginNegative() throws JSONException,
    Exception {
  WebResource r = resource();
  ClientResponse response = r.path("ws").path("v1").path("history")
      .path("mapreduce").path("jobs")
      .queryParam("finishedTimeBegin", String.valueOf(-1000))
      .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
  assertEquals(Status.BAD_REQUEST, response.getClientResponseStatus());
  assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType());
  JSONObject msg = response.getEntity(JSONObject.class);
  JSONObject exception = msg.getJSONObject("RemoteException");
  assertEquals("incorrect number of elements", 3, exception.length());
  String message = exception.getString("message");
  String type = exception.getString("exception");
  String classname = exception.getString("javaClassName");
  WebServicesTestUtils.checkStringMatch("exception message",
      "java.lang.Exception: finishedTimeBegin must be greater than 0",
      message);
  WebServicesTestUtils.checkStringMatch("exception type",
      "BadRequestException", type);
  WebServicesTestUtils.checkStringMatch("exception classname",
      "org.apache.hadoop.yarn.webapp.BadRequestException", classname);
}
 
Example 11
Project: athena   File: VirtualNetworkWebResource.java   View source code 6 votes vote down vote up
/**
 * Creates a virtual network from the JSON input stream.
 *
 * @param stream tenant identifier JSON stream
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel TenantId
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createVirtualNetwork(InputStream stream) {
    try {
        final TenantId tid = TenantId.tenantId(getFromJsonStream(stream, "id").asText());
        VirtualNetwork newVnet = vnetAdminService.createVirtualNetwork(tid);
        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path("vnets")
                .path(newVnet.id().toString());
        return Response
                .created(locationBuilder.build())
                .build();
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 12
Project: ctsms   File: FileResource.java   View source code 6 votes vote down vote up
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
public FileOutVO addFile(@FormDataParam("json") FormDataBodyPart json,
		@FormDataParam("data") FormDataBodyPart content,
		@FormDataParam("data") FormDataContentDisposition contentDisposition,
		@FormDataParam("data") final InputStream input) throws AuthenticationException, AuthorisationException, ServiceException {
	// in.setTrialId(trialId);
	// in.setModule(FileModule.TRIAL_DOCUMENT);
	// https://stackoverflow.com/questions/27609569/file-upload-along-with-other-object-in-jersey-restful-web-service
	json.setMediaType(MediaType.APPLICATION_JSON_TYPE);
	FileInVO in = json.getValueAs(FileInVO.class);
	FileStreamInVO stream = new FileStreamInVO();
	stream.setStream(input);
	stream.setMimeType(content.getMediaType().toString()); // .getType());
	stream.setSize(contentDisposition.getSize());
	stream.setFileName(contentDisposition.getFileName());
	return WebUtil.getServiceLocator().getFileService().addFile(auth, in, stream);
}
 
Example 13
Project: hadoop   File: RMWebServices.java   View source code 6 votes vote down vote up
@GET
@Path("/apps/{appid}/state")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public AppState getAppState(@Context HttpServletRequest hsr,
    @PathParam("appid") String appId) throws AuthorizationException {
  init();
  UserGroupInformation callerUGI = getCallerUserGroupInformation(hsr, true);
  String userName = "";
  if (callerUGI != null) {
    userName = callerUGI.getUserName();
  }
  RMApp app = null;
  try {
    app = getRMAppForAppId(appId);
  } catch (NotFoundException e) {
    RMAuditLogger.logFailure(userName, AuditConstants.KILL_APP_REQUEST,
      "UNKNOWN", "RMWebService",
      "Trying to get state of an absent application " + appId);
    throw e;
  }

  AppState ret = new AppState();
  ret.setState(app.getState().toString());

  return ret;
}
 
Example 14
Project: acmeair   File: AuthenticationCommandValidationTest.java   View source code 6 votes vote down vote up
@Pact(consumer = "AuthenticationService")
public PactFragment createFragment(PactDslWithProvider pactDslWithProvider) throws JsonProcessingException {
    Map<String, String> headers = new HashMap<>();
    headers.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    return pactDslWithProvider
            .given("Customer Sean is registered")
            .uponReceiving("a request to validate Sean")
            .path("/rest/api/login/validate")
            .method("POST")
            .query("sessionId=" + customerSessionInfo.getId())
            .headers(headers)
            .willRespondWith()
            .status(200)
            .body(objectMapper.writeValueAsString(customerSessionInfo), MediaType.APPLICATION_JSON)
            .toFragment();
}
 
Example 15
Project: wechat-mall   File: IndexResource.java   View source code 6 votes vote down vote up
@POST
@Path("register")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public String register(@FormParam("userName") String userName,
		@FormParam("password") String password,
		@FormParam("phone") Long phone, @FormParam("email") String email,
		@FormParam("nick") String nick, @FormParam("addr") String addr,
		@FormParam("gender") String gender) {
	// check not null
	User u = new User();// dao 应该查询
	u.setAddr(addr);
	u.setEmail(email);
	u.setGender(gender);
	u.setNick(nick);
	u.setPassword(password);
	u.setPhone(phone);
	u.setUsername(userName);
	return JsonUtil.bean2Json(u);
}
 
Example 16
Project: personium-core   File: ReadTest.java   View source code 6 votes vote down vote up
/**
 * Cellの取得で認証トークンにBasic形式でトークン値空文字を指定した場合に認証エラーが返却されること.
 */
@Test
public final void Cellの取得で認証トークンにBasic形式でトークン値空文字を指定した場合に認証エラーが返却されること() {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HttpHeaders.AUTHORIZATION, "Basic ");
    this.setHeaders(headers);

    PersoniumResponse res = this.restGet(getUrl(this.cellId));

    // ステータスコード:401
    // コンテンツタイプ:application/json
    // Etagヘッダが存在しない
    // ボディのエラーコードチェック
    assertEquals(HttpStatus.SC_UNAUTHORIZED, res.getStatusCode());
    assertEquals(MediaType.APPLICATION_JSON, res.getResponseHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue());
}
 
Example 17
Project: Biliomi   File: CommandRequestService.java   View source code 6 votes vote down vote up
@POST
@Path("/cli/run")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response runCliCommand(CommandRequest commandRequest) {
  if (StringUtils.isEmpty(commandRequest.getCommand())) {
    return Responses.badRequest();
  }

  MutableString command = new MutableString(commandRequest.getCommand());
  command.prependIfMissing("/");
  ConsoleInputEvent event = new ConsoleInputEvent(command.toString(), false);
  cliCommandRouter.onConsoleInputEvent(event);

  return Responses.ok();
}
 
Example 18
Project: pipe   File: UserService.java   View source code 6 votes vote down vote up
@GET // 修改类使用PUT
@Path("{id}") // htpp://127.0.0.1/api/user/{id}
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public ResponseModel<UserCard> getUser(@PathParam("id") String id) {
    if (Strings.isNullOrEmpty(id)) {
        return ResponseModel.buildParameterError(); // 参数异常
    }

    User self = getSelf();
    if (self.getId().equalsIgnoreCase(id)) {
        // 返回自己不需要查询
        return ResponseModel.buildOk(new UserCard(self, true));
    }
    User user = UserFactory.findById(id);
    if (user == null) {
        // 没找到返回没找到
        return ResponseModel.buildNotFoundUserError(null);
    }
    // 如果我们直接有关注的记录,则我已经关注需要查询信息的用户
    boolean isFollow = UserFactory.getUserFollow(self, user) != null;
    return ResponseModel.buildOk(new UserCard(user, isFollow));

}
 
Example 19
Project: incubator-servicecomb-java-chassis   File: BodyProcessorCreator.java   View source code 6 votes vote down vote up
@Override
public Object getValue(HttpServletRequest request) throws Exception {
  Object body = request.getAttribute(RestConst.BODY_PARAMETER);
  if (body != null) {
    return convertValue(body, targetType);
  }

  // for standard HttpServletRequest, getInputStream will never return null
  // but for mocked HttpServletRequest, maybe get a null
  //  like org.apache.servicecomb.provider.springmvc.reference.ClientToHttpServletRequest
  InputStream inputStream = request.getInputStream();
  if (inputStream == null) {
    return null;
  }

  String contentType = request.getContentType();
  if (contentType != null && !contentType.toLowerCase(Locale.US).startsWith(MediaType.APPLICATION_JSON)) {
    // TODO: we should consider body encoding
    return IOUtils.toString(inputStream, "UTF-8");
  }
  return RestObjectMapper.INSTANCE.readValue(inputStream, targetType);
}
 
Example 20
Project: outland   File: Protobuf3MessageBodyProvider.java   View source code 6 votes vote down vote up
@Override
public void writeTo(final Message m,
    final Class<?> type,
    final Type genericType,
    final Annotation[] annotations,
    final MediaType mediaType,
    final MultivaluedMap<String, Object> httpHeaders,
    final OutputStream entityStream
) throws IOException {

  if (mediaType.getSubtype().contains("protobuf+text")) {
    entityStream.write(m.toString().getBytes(StandardCharsets.UTF_8));
  } else if (mediaType.getSubtype().contains("json")) {
    try {
      entityStream.write(Protobuf3Support.toJsonString(m).getBytes(StandardCharsets.UTF_8));
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  } else {
    entityStream.write(m.toByteArray());
  }
}
 
Example 21
Project: microprofile-jwt-auth   File: RequiredClaimsEndpoint.java   View source code 6 votes vote down vote up
@GET
@Path("/verifyIssuedAt")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject verifyIssuedAt(@QueryParam("iat") Long iat) {
    boolean pass = false;
    String msg;
    // iat
    Long iatValue = rawTokenJson.getIssuedAtTime();
    if (iatValue == null || iatValue.intValue() == 0) {
        msg = Claims.iat.name() + "value is null or empty, FAIL";
    }
    else if (iatValue.equals(iat)) {
        msg = Claims.iat.name() + " PASS";
        pass = true;
    }
    else {
        msg = String.format("%s: %s != %s", Claims.iat.name(), iatValue, iat);
    }
    JsonObject result = Json.createObjectBuilder()
            .add("pass", pass)
            .add("msg", msg)
            .build();
    return result;
}
 
Example 22
Project: personium-core   File: UserDataExpandTest.java   View source code 6 votes vote down vote up
/**
 * Keyなし取得時にexpandにアンダースコアのみを指定した場合に400が返却されること.
 */
@Test
public final void Keyなし取得時にexpandにアンダースコアのみを指定した場合に400が返却されること() {

    try {
        // データ作成
        createData();

        // $expandを指定してデータを取得
        Http.request("box/odatacol/list.txt")
                .with("cell", Setup.TEST_CELL1)
                .with("box", Setup.TEST_BOX1)
                .with("collection", Setup.TEST_ODATA)
                .with("entityType", navPropName)
                .with("query", "?\\$expand=_")
                .with("accept", MediaType.APPLICATION_JSON)
                .with("token", PersoniumUnitConfig.getMasterToken())
                .returns()
                .statusCode(HttpStatus.SC_BAD_REQUEST)
                .debug();

    } finally {
        // データ削除
        deleteData();
    }
}
 
Example 23
Project: E-Clinic   File: AuthenticationRestEndPoint.java   View source code 6 votes vote down vote up
@POST
@Path("auth")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response login(@Valid Login value) {
    try {
        String auth = authenticationService.auth(value.getUserName(), value.getPassword());
        //TODO Do not hardcode roles, query from database
        if (auth == null) {
            return Response.ok().entity("false").build();
        } else if ("Doctor".equals(auth)) {
            return Response.ok().entity("Doctor").build();
        } else if ("AdminClinic".equals(auth)) {
            return Response.ok().entity("AdminClinic").build();
        } else if ("Nurse".equals(auth)) {
            return Response.ok().entity("Nurse").build();
        } else if ("HRManager".equals(auth)) {
            return Response.ok().entity("HRManager").build();
        }
    } catch (Exception ex) {
        return Response.ok().header("Exception", ex.getMessage()).build();
    }
    return Response.ok().entity("Unknown").build();
}
 
Example 24
Project: opencps-v2   File: OfficeSiteManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/{id}/preferences/{key}")
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Response getOfficeSitePreferencesByKey(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id, @PathParam("key") String key);
 
Example 25
Project: rest-basic-tutorial   File: PeopleResource.java   View source code 5 votes vote down vote up
@POST
@Consumes({MediaType.APPLICATION_JSON})
public Response postPerson(@Valid @NotNull ValidatedPerson person) {
    POSTED_PEOPLE.add(person);

    return Response.ok()
            .build();
}
 
Example 26
Project: opencps-v2   File: ServiceProcessManagement.java   View source code 5 votes vote down vote up
@DELETE
@Path("/{id}/roles/{roleid}")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@ApiOperation(value = "Remove a ServiceProcessRole of a ServiceProcess", response = RoleInputModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a ServiceProcessRole was deleted", response = RoleInputModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })

public Response removeServiceProcessRole(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext, @PathParam("id") long id, @PathParam("roleid") long roleid);
 
Example 27
Project: personium-core   File: ReadListTest.java   View source code 5 votes vote down vote up
/**
 * Cellの一覧取得の不正なQueryを無視するのテスト.
 */
@Test
public final void Cellの一覧取得の不正なQueryを無視するのテスト() {
    cellCreate(DEF_CELL_NUM);
    PersoniumRequest req = PersoniumRequest.get(UrlUtils.unitCtl(Cell.EDM_TYPE_NAME));
    req.header("Accept", MediaType.APPLICATION_JSON);
    // 不正なQueryを指定しても無視される事
    req.query("query=test");
    this.cellListNormal(req);
}
 
Example 28
Project: keycloak-protocol-cas   File: KeycloakCASClientInstallation.java   View source code 5 votes vote down vote up
@Override
public Response generateInstallation(KeycloakSession session, RealmModel realm, ClientModel client, URI baseUri) {
    UriBuilder bindingUrlBuilder = UriBuilder.fromUri(baseUri);
    String bindingUrl = RealmsResource.protocolUrl(bindingUrlBuilder)
            .build(realm.getName(), CASLoginProtocol.LOGIN_PROTOCOL).toString();
    String description = "CAS Server URL: " + bindingUrl + "\n" +
            "CAS Protocol: CAS 2.0/3.0 (SAML 1.1 is not supported)\n" +
            "Use CAS REST API: false (unsupported)";
    return Response.ok(description, MediaType.TEXT_PLAIN_TYPE).build();
}
 
Example 29
Project: redirector   File: RestSupport.java   View source code 5 votes vote down vote up
@GET
@Path(URL_RULES_CONTROLLER_PATH + "/{serviceName}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getAllUrlRules(@PathParam("serviceName") final String serviceName) {
    if (commonBeans.connector().isConnected()) {
        return Response.ok(extractAllUrlRules(serviceName)).build();
    }
    return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
}
 
Example 30
Project: redirector   File: RedirectorDataSourceExceptionMapper.java   View source code 5 votes vote down vote up
@Override
public Response toResponse(RedirectorDataSourceException exception) {
    log.error("Exception happened in RedirectorWebService", exception);

    return Response.status(Response.Status.SERVICE_UNAVAILABLE)
        .entity(new ErrorMessage(getHumanReadableMessage(exception)))
        .type(MediaType.APPLICATION_JSON)
        .build();
}
 
Example 31
Project: soapbox-race-core   File: User.java   View source code 5 votes vote down vote up
@POST
@Secured
@Path("SecureLogout")
@Produces(MediaType.APPLICATION_XML)
public String secureLogout() {
	return "";
}
 
Example 32
Project: eadlsync   File: SeRepoConector.java   View source code 5 votes vote down vote up
/**
 * Creates a Multipart which will be needed for the SE-Repo API call to commit SE-Items.
 *
 * @param commit
 * @param seItemsWithContent
 * @return
 */
protected static MultipartFormDataOutput createMultipart(CreateCommit commit, List<SeItemWithContent> seItemsWithContent) {
    MultipartFormDataOutput multipart = new MultipartFormDataOutput();

    multipart.addFormData("commit", commit, MediaType.APPLICATION_JSON_TYPE);
    int partCounter = 0;
    // We create for each SE-Item a "multipart-pair" with JSON data (metadata_) and "binary" data (content_)
    for (SeItemWithContent seItem : seItemsWithContent) {
        multipart.addFormData("metadata_" + partCounter, seItem, MediaType.APPLICATION_JSON_TYPE);
        multipart.addFormData("content_" + partCounter, seItem.getContent(), MediaType.valueOf(seItem.getMimeType()), seItem.getName());
        partCounter++;
    }

    return multipart;
}
 
Example 33
Project: uavstack   File: GodEyeRestService.java   View source code 5 votes vote down vote up
@GET
@Path("filter/group/query")
@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
public void groupFilterQuery(@Suspended AsyncResponse response) {

    Map<String, String> resultMap = cm.getHashAll(godeyeFilterGroupCacheRegion, godeyeFilterGroupCacheRegionKey);
    response.resume(JSONHelper.toString(resultMap));
}
 
Example 34
Project: databricks-client-java   File: ClustersClient.java   View source code 5 votes vote down vote up
public ClusterInfoDTO getCluster(String clusterId) throws HttpException {
    //TODO should be DEBUG logging statement
    System.out.println("getCluster HTTP request for id "+clusterId);
    Response response = _target.path("get")
            .register(Session.Authentication)
            .queryParam("cluster_id", clusterId)
            .request()
            .accept(MediaType.APPLICATION_JSON)
            .get();

    checkResponse(response);
    return response.readEntity(ClusterInfoDTO.class);
}
 
Example 35
Project: opencps-v2   File: DeliverablesManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/deliverables/{id}/preview")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "Get info preview for deliverable id")
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns"),
		@ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not Found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access defined", response = ExceptionModel.class) })
public Response getPreview(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@ApiParam(value = "id of Deliverable", required = true) @PathParam("id") Long id);
 
Example 36
Project: nuls   File: RestFulUtils.java   View source code 5 votes vote down vote up
public RpcClientResult put(String path, String content) {
    if (null == serverUri) {
        throw new RuntimeException("service url is null");
    }
    WebTarget target = client.target(serverUri).path(path);
    return target.request().buildPut(Entity.entity(content, MediaType.APPLICATION_JSON)).invoke(RpcClientResult.class);
}
 
Example 37
Project: opencps-v2   File: DeliverablesManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/deliverables/{id}/formdata")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
public Response getFormData(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user, @Context ServiceContext serviceContext,
		@ApiParam(value = "id of Deliverable", required = true) @PathParam("id") Long id);
 
Example 38
Project: redirector   File: RestSupport.java   View source code 5 votes vote down vote up
@GET
@Path(NAMESPACE_CONTROLLER_PATH + "getOne/{name}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public Response getNamespace(@PathParam("name") final String name) {
    if (!commonBeans.connector().isConnected()) {
        return Response.status(Response.Status.SERVICE_UNAVAILABLE).build();
    }

    NamespacedList namespacedList = extractNamespacedListByName(name);
    if (namespacedList == null) {
        return Response.status(Response.Status.NOT_FOUND).build();
    } else {
        return Response.ok(namespacedList).build();
    }
}
 
Example 39
Project: fuck_zookeeper   File: ZNodeResource.java   View source code 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_XML)
public Response getZNodeList(
        @PathParam("path") String path,
        @QueryParam("callback") String callback,
        @DefaultValue("data") @QueryParam("view") String view,
        @DefaultValue("base64") @QueryParam("dataformat") String dataformat,
        @Context UriInfo ui) throws InterruptedException, KeeperException {
    return getZNodeList(false, path, callback, view, dataformat, ui);
}
 
Example 40
Project: opencps-v2   File: DossierFileManagement.java   View source code 5 votes vote down vote up
@GET
@Path("/{id}/files/{referenceUid}")
@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
@ApiOperation(value = "getDossierFilesByDossierReferenceUid", response = DossierFileResultsModel.class)
@ApiResponses(value = {
		@ApiResponse(code = HttpURLConnection.HTTP_OK, message = "downloadByDossierId_ReferenceUid"),
		@ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found", response = ExceptionModel.class),
		@ApiResponse(code = HttpURLConnection.HTTP_FORBIDDEN, message = "Access denied", response = ExceptionModel.class) })
public Response downloadByDossierId_ReferenceUid(@Context HttpServletRequest request, @Context HttpHeaders header,
		@Context Company company, @Context Locale locale, @Context User user,
		@Context ServiceContext serviceContext,
		@ApiParam(value = "id of dossier", required = true) @PathParam("id") long id,
		@ApiParam(value = "referenceUid of dossierfile", required = true) @PathParam("referenceUid") String referenceUid,
		@ApiParam(value = "password for access dossier file", required = false) @PathParam("password") String password);