Java Examples for javax.ws.rs.core.MultivaluedHashMap
The following java examples will help you to understand the usage of javax.ws.rs.core.MultivaluedHashMap. These source code samples are taken from different open source projects.
Example 1
| Project: Resteasy-master File: TokenManagement.java View source code |
protected boolean authenticate(Realm realm, User user, MultivaluedMap<String, String> formData) {
MultivaluedMap<String, UserCredential> userCredentials = new MultivaluedHashMap<String, UserCredential>();
List<UserCredential> creds = identityManager.getCredentials(user);
for (UserCredential userCredential : creds) {
userCredentials.add(userCredential.getType(), userCredential);
}
for (RequiredCredential credential : identityManager.getRequiredCredentials(realm)) {
if (credential.isInput()) {
String value = formData.getFirst(credential.getType());
if (value == null) {
return false;
}
UserCredential userCredential = userCredentials.getFirst(credential.getType());
if (userCredential == null) {
LogMessages.LOGGER.warn(Messages.MESSAGES.missingRequiredUserCredential());
return false;
}
if (userCredential.isHashed()) {
value = hash(value);
}
if (!value.equals(userCredential.getValue())) {
LogMessages.LOGGER.warn(Messages.MESSAGES.credentialMismatch());
return false;
}
} else {
if (credential.getType().equals(RequiredCredentialRepresentation.CALLER_PRINCIPAL)) {
List<UserCredential> principals = userCredentials.get(RequiredCredentialRepresentation.CALLER_PRINCIPAL);
if (principals == null)
return false;
boolean found = false;
for (UserCredential userCredential : principals) {
if (userCredential.getValue().equals(securityContext.getUserPrincipal().getName())) {
found = true;
break;
}
}
if (!found) {
LogMessages.LOGGER.warn(Messages.MESSAGES.callerPrincipalNotMatched());
return false;
}
} else // todo support other credentials
{
throw new NotImplementedYetException();
}
}
}
return true;
}Example 2
| Project: opencit-master File: AsyncRpc.java View source code |
// @Context
// private MessageBodyWorkers workers;
@Path("/{name}")
@POST
@Consumes(MediaType.WILDCARD)
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, DataMediaType.APPLICATION_YAML, DataMediaType.TEXT_YAML })
public Rpc invokeAsyncRemoteProcedureCall(@PathParam("name") String name, @Context HttpServletRequest request, byte[] input) {
// make sure we have an extension to handle this rpc
RpcAdapter adapter = getAdapter(name);
// convert the client's input into our internal format
Object inputObject = getInput(input, adapter.getInputClass(), request);
// now serialize the input object with xstream; even though we're going to process immediately, we are still going to record the call in the RPC table so we need the xml
byte[] inputXml = toXml(inputObject);
// prepare the rpc task with the input
RpcPriv rpc = new RpcPriv();
rpc.setId(new UUID());
rpc.setName(name);
rpc.setInput(inputXml);
// com.intel.dcsg.cpg.util.MultivaluedHashMap<String,String> headers = RpcUtil.convertHeadersToMultivaluedMap(request);
// rpc.setInputHeaders(toRfc822(headers));
rpc.setStatus(Rpc.Status.QUEUE);
// store it
repository.create(rpc);
// queue it (must follow storage to prevent situation where an executing task needs to store an update to the table and it hasn't been stored yet)
// RpcInvoker.getInstance().add(rpc.getId());
Rpc status = new Rpc();
status.copyFrom(rpc);
return status;
}Example 3
| Project: datacollector-master File: HttpClientSource.java View source code |
/**
* Resolves any expressions in the Header value entries of the request.
* @return map of evaluated headers to add to the request
* @throws StageException if an unhandled error is encountered
*/
private MultivaluedMap<String, Object> resolveHeaders() throws StageException {
MultivaluedMap<String, Object> requestHeaders = new MultivaluedHashMap<>();
for (Map.Entry<String, String> entry : conf.headers.entrySet()) {
List<Object> header = new ArrayList<>(1);
Object resolvedValue = headerEval.eval(headerVars, entry.getValue(), String.class);
header.add(resolvedValue);
requestHeaders.put(entry.getKey(), header);
hasher.putString(entry.getKey(), Charset.forName(conf.dataFormatConfig.charset));
hasher.putString(entry.getValue(), Charset.forName(conf.dataFormatConfig.charset));
}
return requestHeaders;
}Example 4
| Project: everrest-master File: RequestDispatcherTest.java View source code |
private void mockApplicationContext() {
applicationContext = mock(ApplicationContext.class, RETURNS_DEEP_STUBS);
when(applicationContext.getQueryParameters()).thenReturn(new MultivaluedHashMap<>());
when(applicationContext.getMethodInvoker(isA(GenericResourceMethod.class))).thenReturn(methodInvoker);
pathParameterValues = newArrayList();
when(applicationContext.getParameterValues()).thenReturn(pathParameterValues);
when(applicationContext.getAttributes().get("org.everrest.lifecycle.PerRequest")).thenReturn(newArrayList());
when(applicationContext.getBaseUriBuilder()).thenReturn(UriBuilderImpl.fromPath("http://localhost:8080/servlet"));
ApplicationContext.setCurrent(applicationContext);
}Example 5
| Project: robe-master File: SearchFactoryTest.java View source code |
@Test
public void provide() throws Exception {
SearchModel expected = new SearchModel();
expected.setQ("qparam");
expected.setOffset(1);
expected.setLimit(10);
expected.setFields(new String[] { "field1", "field2" });
expected.setSort(new String[] { "+field1", "-field2" });
expected.setFilterExpression("field1=1");
MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>();
queryParameters.put("_q", Lists.newArrayList("qparam"));
queryParameters.put("_offset", Lists.newArrayList("1"));
queryParameters.put("_limit", Lists.newArrayList("10"));
queryParameters.put("_fields", Lists.newArrayList("field1,field2"));
queryParameters.put("_sort", Lists.newArrayList("+field1,-field2"));
queryParameters.put("_filter", Lists.newArrayList("field1=1"));
queryParameters.put("_none", Lists.newArrayList("none"));
UriInfo uriInfo = mock(UriInfo.class);
when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
SearchFactory factory = mock(SearchFactory.class);
when(factory.getUriInfo()).thenReturn(uriInfo);
when(factory.getMethod()).thenReturn("GET");
when(factory.provide()).thenCallRealMethod();
assertEquals(uriInfo, factory.getUriInfo());
assertEquals("GET", factory.getMethod());
SearchModel actual = factory.provide();
assertEquals(expected, actual);
}Example 6
| Project: dropwizard-simpleauth-master File: BasicCredentialAuthFilterTest.java View source code |
@Test
public void testValidAuth() throws IOException {
AuthFilter authFilter = new BasicCredentialAuthFilter.Builder<String>().setAuthenticator(new StringAuthenticator()).setPrincipal(String.class).setRealm("Hmm").buildAuthFilter();
MultivaluedMap<String, String> headers = new MultivaluedHashMap<String, String>() {
{
add(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpmb28=");
}
};
ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class);
when(containerRequestContext.getHeaders()).thenReturn(headers);
authFilter.filter(containerRequestContext);
ArgumentCaptor<SecurityContext> captor = ArgumentCaptor.forClass(SecurityContext.class);
verify(containerRequestContext).setSecurityContext(captor.capture());
assertTrue(captor.getValue().getUserPrincipal() instanceof AuthPrincipal);
assertEquals(((AuthPrincipal) captor.getValue().getUserPrincipal()).getAuthenticated(), "user");
}Example 7
| Project: fcrepo4-master File: StreamingBaseHtmlProviderTest.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testWriteTo() throws WebApplicationException, IllegalArgumentException, IOException {
final Template mockTemplate = mock(Template.class);
final ByteArrayOutputStream outStream = new ByteArrayOutputStream();
doAnswer(new Answer<Object>() {
@Override
public Object answer(final InvocationOnMock invocation) {
outStream.write("abcdefighijk".getBytes(), 0, 10);
return "I am pretending to merge a template for you.";
}
}).when(mockTemplate).merge(isA(Context.class), isA(Writer.class));
setField(testProvider, "templatesMap", singletonMap(REPOSITORY_NAMESPACE + "Binary", mockTemplate));
testProvider.writeTo(testData, RdfNamespacedStream.class, mock(Type.class), new Annotation[] {}, MediaType.valueOf("text/html"), (MultivaluedMap) new MultivaluedHashMap<>(), outStream);
final byte[] results = outStream.toByteArray();
assertTrue("Got no output from serialization!", results.length > 0);
}Example 8
| Project: jrs-rest-java-client-master File: SingleResourceAdapterTest.java View source code |
@Test
/**
* for {@link com.jaspersoft.jasperserver.jaxrs.client.apiadapters.resources.SingleResourceAdapter#details()}
*/
@SuppressWarnings("unchecked")
public void should_return_operation_result_with_client_resource_folder() {
String resourceUri = "/";
when(sessionStorageMock.getConfiguration()).thenReturn(configurationMock);
when(configurationMock.getAcceptMimeType()).thenReturn(MimeType.JSON);
mockStatic(JerseyRequest.class);
when(buildRequest(eq(sessionStorageMock), eq(ClientResource.class), eq(new String[] { "resources" }), any(DefaultErrorHandler.class))).thenReturn(jerseyRequestMock);
doReturn(operationResultMock).when(jerseyRequestMock).get();
SingleResourceAdapter adapter = new SingleResourceAdapter(sessionStorageMock, resourceUri);
OperationResult<ClientResource> retrieved = adapter.details();
assertNotNull(retrieved);
assertSame(retrieved, operationResultMock);
Mockito.verify(jerseyRequestMock).addParams(any(MultivaluedHashMap.class));
Mockito.verify(jerseyRequestMock).setAccept(ResourceMediaType.FOLDER_JSON);
Mockito.verify(jerseyRequestMock).get();
}Example 9
| Project: minnal-master File: RouterTest.java View source code |
@Test
public void shouldCreateHttpResponseFromContainerResponseWithHeaders() {
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
headers.add("header1", "value1");
headers.addAll("header2", Arrays.<Object>asList("value2", "value3"));
ContainerResponse response = mock(ContainerResponse.class);
when(response.getHeaders()).thenReturn(headers);
when(response.getStatus()).thenReturn(200);
ByteBuf buffer = mock(ByteBuf.class);
FullHttpResponse httpResponse = router.createHttpResponse(context, response, buffer);
assertEquals(HttpHeaders.getHeader(httpResponse, "header1"), "value1");
assertEquals(HttpHeaders.getHeader(httpResponse, "header2"), "value2, value3");
}Example 10
| Project: ambari-master File: ProxyHelperTest.java View source code |
@Test
public void shouldBuildURLWithNoQueryParameters() throws Exception {
ViewContext context = createNiceMock(ViewContext.class);
ProxyHelper helper = new ProxyHelper(context);
assertEquals("http://abc.com/", helper.getProxyUrl("http://abc.com", "", new MultivaluedHashMap<String, String>(), "kerberos"));
assertEquals("http://abc.com/test/abcd", helper.getProxyUrl("http://abc.com", "test/abcd", new MultivaluedHashMap<String, String>(), "kerberos"));
}Example 11
| Project: appverse-web-master File: XSSSecurityFilter.java View source code |
/**
* @see javax.ws.rs.container.ContainerRequestFilter#filter(javax.ws.rs.container.ContainerRequestContext)
*/
@Override
public void filter(ContainerRequestContext request) {
// Clean the query string
// The query string parameters come in an inmutable data structure, so they cannot be modified.
// It will be necessary to copy the query string parameters to a brand new hash, clean them and later
// rebuild the request URI with the cleaned parameters.
final MultivaluedMap<String, String> parameters = request.getUriInfo().getQueryParameters();
if (parameters != null && !parameters.isEmpty()) {
MultivaluedHashMap<String, String> parametersToClean = new MultivaluedHashMap<String, String>();
parametersToClean.putAll(parameters);
ESAPIHelper.cleanParams(parametersToClean);
UriBuilder query = request.getUriInfo().getRequestUriBuilder().replaceQuery("");
for (Map.Entry<String, List<String>> e : parametersToClean.entrySet()) {
final String key = e.getKey();
for (String v : e.getValue()) {
query = query.queryParam(key, v);
}
}
request.setRequestUri(query.build());
}
// Clean the headers
MultivaluedMap<String, String> headers = request.getHeaders();
if (headers != null && !headers.isEmpty()) {
ESAPIHelper.cleanParams(headers);
}
}Example 12
| Project: camel-master File: BonitaAuthFilter.java View source code |
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
if (requestContext.getCookies().get("JSESSIONID") == null) {
String username = bonitaApiConfig.getUsername();
String password = bonitaApiConfig.getPassword();
String bonitaApiToken = null;
if (ObjectHelper.isEmpty(username)) {
throw new IllegalArgumentException("Username provided is null or empty.");
}
if (ObjectHelper.isEmpty(password)) {
throw new IllegalArgumentException("Password provided is null or empty.");
}
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
Client client = clientBuilder.build();
WebTarget webTarget = client.target(bonitaApiConfig.getBaseBonitaURI()).path("loginservice");
MultivaluedMap<String, String> form = new MultivaluedHashMap<String, String>();
form.add("username", username);
form.add("password", password);
form.add("redirect", "false");
Response response = webTarget.request().accept(MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
Map<String, NewCookie> cr = response.getCookies();
ArrayList<Object> cookies = new ArrayList<>();
for (NewCookie cookie : cr.values()) {
if ("X-Bonita-API-Token".equals(cookie.getName())) {
bonitaApiToken = cookie.getValue();
requestContext.getHeaders().add("X-Bonita-API-Token", bonitaApiToken);
}
cookies.add(cookie.toCookie());
}
requestContext.getHeaders().put("Cookie", cookies);
}
}Example 13
| Project: cloudbreak-master File: CloudbreakClient.java View source code |
private void renewEndpoints(String token) {
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
headers.add("Authorization", "Bearer " + token);
this.t = client.target(cloudbreakAddress).path(CoreApi.API_ROOT_CONTEXT);
this.credentialEndpoint = newResource(this.credentialEndpoint, CredentialEndpoint.class, headers);
this.templateEndpoint = newResource(this.templateEndpoint, TemplateEndpoint.class, headers);
this.topologyEndpoint = newResource(this.topologyEndpoint, TopologyEndpoint.class, headers);
this.usageEndpoint = newResource(this.usageEndpoint, UsageEndpoint.class, headers);
this.eventEndpoint = newResource(this.eventEndpoint, EventEndpoint.class, headers);
this.securityGroupEndpoint = newResource(this.securityGroupEndpoint, SecurityGroupEndpoint.class, headers);
this.stackEndpoint = newResource(this.stackEndpoint, StackEndpoint.class, headers);
this.subscriptionEndpoint = newResource(this.subscriptionEndpoint, SubscriptionEndpoint.class, headers);
this.networkEndpoint = newResource(this.networkEndpoint, NetworkEndpoint.class, headers);
this.recipeEndpoint = newResource(this.recipeEndpoint, RecipeEndpoint.class, headers);
this.sssdConfigEndpoint = newResource(this.sssdConfigEndpoint, SssdConfigEndpoint.class, headers);
this.rdsConfigEndpoint = newResource(this.rdsConfigEndpoint, RdsConfigEndpoint.class, headers);
this.accountPreferencesEndpoint = newResource(this.accountPreferencesEndpoint, AccountPreferencesEndpoint.class, headers);
this.blueprintEndpoint = newResource(this.blueprintEndpoint, BlueprintEndpoint.class, headers);
this.clusterEndpoint = newResource(this.clusterEndpoint, ClusterEndpoint.class, headers);
this.connectorEndpoint = newResource(this.connectorEndpoint, ConnectorEndpoint.class, headers);
this.userEndpoint = newResource(this.userEndpoint, UserEndpoint.class, headers);
this.constraintTemplateEndpoint = newResource(this.constraintTemplateEndpoint, ConstraintTemplateEndpoint.class, headers);
this.utilEndpoint = newResource(this.utilEndpoint, UtilEndpoint.class, headers);
this.ldapConfigEndpoint = newResource(this.ldapConfigEndpoint, LdapConfigEndpoint.class, headers);
LOGGER.info("Endpoints have been renewed for CloudbreakClient");
}Example 14
| Project: dropwizard-protobuf-master File: ProtocolBufferMessageBodyProviderTest.java View source code |
@Test
public void deserializesRequestEntities() throws Exception {
final ByteArrayInputStream entity = new ByteArrayInputStream(example.toByteArray());
final Class<?> klass = Example.class;
final Object obj = provider.readFrom((Class<Message>) klass, Example.class, NONE, ProtocolBufferMediaType.APPLICATION_PROTOBUF_TYPE, new MultivaluedHashMap<String, String>(), entity);
assertThat(obj).isInstanceOf(Example.class);
assertThat(((Example) obj).getId()).isEqualTo(1337L);
}Example 15
| Project: fastjson-master File: FastJsonProviderTest.java View source code |
@SuppressWarnings("deprecation")
public void test_1() throws Exception {
FastJsonProvider provider1 = new FastJsonProvider("UTF-8");
Assert.assertEquals("UTF-8", provider1.getCharset().name());
FastJsonProvider provider2 = new FastJsonProvider();
provider2.setCharset(Charset.forName("GBK"));
Assert.assertEquals("GBK", provider2.getCharset().name());
Assert.assertNull(provider2.getDateFormat());
provider2.setDateFormat("yyyyMMdd");
provider2.setFeatures(SerializerFeature.IgnoreErrorGetter);
Assert.assertEquals(1, provider2.getFeatures().length);
Assert.assertEquals(SerializerFeature.IgnoreErrorGetter, provider2.getFeatures()[0]);
provider2.setFilters(serializeFilter);
Assert.assertEquals(1, provider2.getFilters().length);
Assert.assertEquals(serializeFilter, provider2.getFilters()[0]);
FastJsonProvider provider = new FastJsonProvider(new Class[] { VO.class });
Assert.assertNotNull(provider.getFastJsonConfig());
provider.setFastJsonConfig(new FastJsonConfig());
Assert.assertEquals(true, provider.isReadable(VO.class, VO.class, null, MediaType.APPLICATION_JSON_TYPE));
Assert.assertEquals(true, provider.isWriteable(VO.class, VO.class, null, MediaType.APPLICATION_JSON_TYPE));
Assert.assertEquals(true, provider.isReadable(VO.class, VO.class, null, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
Assert.assertEquals(true, provider.isWriteable(VO.class, VO.class, null, MediaType.APPLICATION_FORM_URLENCODED_TYPE));
Assert.assertEquals(false, provider.isReadable(VO.class, VO.class, null, MediaType.APPLICATION_XML_TYPE));
Assert.assertEquals(false, provider.isWriteable(VO.class, VO.class, null, MediaType.APPLICATION_XML_TYPE));
Assert.assertEquals(false, provider.isReadable(String.class, String.class, null, MediaType.valueOf("application/javascript")));
Assert.assertEquals(false, provider.isWriteable(String.class, String.class, null, MediaType.valueOf("application/x-javascript")));
Assert.assertEquals(false, provider.isReadable(String.class, String.class, null, MediaType.valueOf("applications/+json")));
Assert.assertEquals(false, provider.isWriteable(String.class, String.class, null, MediaType.valueOf("applications/x-json")));
Assert.assertEquals(false, provider.isReadable(null, null, null, MediaType.valueOf("application/x-javascript")));
Assert.assertEquals(false, provider.isWriteable(null, null, null, null));
VO vo = (VO) provider.readFrom(null, VO.class, null, MediaType.APPLICATION_JSON_TYPE, null, new ByteArrayInputStream("{\"id\":123}".getBytes(Charset.forName("UTF-8"))));
Assert.assertEquals(123, vo.getId());
final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
provider.writeTo(vo, VO.class, VO.class, null, MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<String, Object>(), byteOut);
byte[] bytes = byteOut.toByteArray();
Assert.assertEquals("{\"id\":123}", new String(bytes, "UTF-8"));
provider.getSize(vo, VO.class, VO.class, null, MediaType.APPLICATION_JSON_TYPE);
}Example 16
| Project: grill-master File: TestParameterResolution.java View source code |
@Test
public void testWithProperValues() throws ParameterValueException, MissingParameterException {
MultivaluedMap<String, String> parameterValues = new MultivaluedHashMap<>();
parameterValues.put("param6", Lists.newArrayList("true", "false"));
String resolvedQuery = ParameterResolver.resolve(QUERY, parameterValues);
Assert.assertEquals("select * from table where col = 'val' and col = 'val' and col = 'a :param1 inside single quotes' " + "and col = \"a :param1 inside double quotes\" and col in ('val1','val2') and col = 1 and col in (1,2) " + "and col = true and col = 1.0 and col in (1.2,2.1) and col in (true,false)", resolvedQuery, "Query resolution did not happen correctly");
}Example 17
| Project: hapi-fhir-master File: JaxRsHttpClient.java View source code |
@Override
public IHttpRequest createParamRequest(FhirContext theContext, Map<String, List<String>> theParams, EncodingEnum theEncoding) {
MultivaluedMap<String, String> map = new MultivaluedHashMap<String, String>();
for (Map.Entry<String, List<String>> nextParam : theParams.entrySet()) {
List<String> value = nextParam.getValue();
for (String s : value) {
map.add(nextParam.getKey(), s);
}
}
Entity<Form> entity = Entity.form(map);
JaxRsHttpRequest retVal = createHttpRequest(entity);
addHeadersToRequest(retVal, theEncoding, theContext);
return retVal;
}Example 18
| Project: javaee7-samples-master File: TestServlet.java View source code |
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Request Binding</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Resource Validation in JAX-RS</h1>");
Client client = ClientBuilder.newClient();
List<WebTarget> targets = new ArrayList<>();
for (int i = 0; i < 3; i++) {
targets.add(client.target("http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/webresources/names" + (i + 1)));
}
for (WebTarget target : targets) {
out.println("<h2>Using target: " + target.getUri() + "</h2>");
MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
out.print("<br><br>POSTing with valid data ...<br>");
map.add("firstName", "Sheldon");
map.add("lastName", "Cooper");
map.add("email", "random@example.com");
Response r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 200);
out.println();
out.print("<br><br>POSTing with invalid (null) \"firstName\" ...<br>");
map.putSingle("firstName", null);
r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 200);
out.println();
out.print("<br><br>POSTing with invalid (null) \"lastName\" ...<br>");
map.putSingle("firstName", "Sheldon");
map.putSingle("lastName", null);
r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 400);
out.print("<br><br>POSTing with invalid (missing @) email \"email\" ...<br>");
map.putSingle("lastName", "Cooper");
map.putSingle("email", "randomexample.com");
r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 400);
out.print("<br><br>POSTing with invalid (missing .com) email \"email\" ...<br>");
map.putSingle("email", "random@examplecom");
r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 400);
}
WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/webresources/nameadd");
out.println("<h2>Using target: " + target.getUri() + "</h2>");
out.print("<br><br>POSTing using @Valid (all vaild data) ...<br>");
Response r = target.request().post(Entity.json(new Name("Sheldon", "Cooper", "sheldon@cooper.com")));
printResponseStatus(out, r, 200);
out.print("<br><br>POSTing using @Valid, with invalid (null) \"firstName\" ...<br>");
r = target.request().post(Entity.json(new Name(null, "Cooper", "sheldon@cooper.com")));
printResponseStatus(out, r, 400);
out.print("<br><br>POSTing using @Valid, with invalid (null) \"lastName\" ...<br>");
r = target.request().post(Entity.json(new Name("Sheldon", null, "sheldon@cooper.com")));
printResponseStatus(out, r, 400);
out.print("<br><br>POSTing using @Valid, with invalid (missing @) email \"email\" ...<br>");
r = target.request().post(Entity.json(new Name("Sheldon", "Cooper", "sheldoncooper.com")));
printResponseStatus(out, r, 400);
out.println("<br>... done.<br>");
out.println("</body>");
out.println("</html>");
}Example 19
| Project: jersey-hmac-auth-master File: PrincipalFactoryTest.java View source code |
@Test
public final void verifyProvideDeniesAccess() throws URISyntaxException {
// given
final MultivaluedMap<String, String> parameterMap = new MultivaluedHashMap<String, String>();
parameterMap.putSingle("apiKey", "invalidApiKey");
final URI uri = new URI("https://api.example.com/path/to/resource?apiKey=invalidApiKey");
final ExtendedUriInfo uriInfo = mock(ExtendedUriInfo.class);
given(uriInfo.getQueryParameters()).willReturn(parameterMap);
given(uriInfo.getRequestUri()).willReturn(uri);
given(request.getUriInfo()).willReturn(uriInfo);
given(request.getHeaderString("X-Auth-Version")).willReturn("1");
given(request.getHeaderString("X-Auth-Signature")).willReturn("invalidSignature");
given(request.getHeaderString("X-Auth-Timestamp")).willReturn("two days ago");
given(request.getMethod()).willReturn("POST");
given(authenticator.authenticate(any(Credentials.class))).willReturn(null);
// when
try {
factory.provide();
// then
fail("Expected 401 status code");
} catch (final NotAuthorizedException nae) {
}
}Example 20
| Project: lens-master File: TestParameterResolution.java View source code |
@Test
public void testWithProperValues() throws ParameterValueException, MissingParameterException {
MultivaluedMap<String, String> parameterValues = new MultivaluedHashMap<>();
parameterValues.put("param6", Lists.newArrayList("true", "false"));
String resolvedQuery = ParameterResolver.resolve(QUERY, parameterValues);
Assert.assertEquals("select * from table where col = 'val' and col = 'val' and col = 'a :param1 inside single quotes' " + "and col = \"a :param1 inside double quotes\" and col in ('val1','val2') and col = 1 and col in (1,2) " + "and col = true and col = 1.0 and col in (1.2,2.1) and col in (true,false)", resolvedQuery, "Query resolution did not happen correctly");
}Example 21
| Project: resource-manager-master File: RestDataspaceImpl.java View source code |
/**
* Retrieve metadata of file in the location specified in <i>dataspace</i>.
* The format of the HEAD URI is:
* <p>
* {@code http://<rest-server-path>/data/<dataspace>/<path-name>}
* <p>
* Example:
* {@code http://localhost:8080/rest/rest/data/user/my-files/my-text-file.txt}
*
*/
@HEAD
@Path("/{dataspace}/{path-name:.*}")
public Response metadata(@HeaderParam("sessionid") String sessionId, @PathParam("dataspace") String dataspacePath, @PathParam("path-name") String pathname) throws NotConnectedRestException, PermissionRestException {
Session session = checkSessionValidity(sessionId);
try {
checkPathParams(dataspacePath, pathname);
FileObject fo = resolveFile(session, dataspacePath, pathname);
if (!fo.exists()) {
return notFoundRes();
}
logger.debug(String.format("Retrieving metadata for %s in %s", pathname, dataspacePath));
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(FileSystem.metadata(fo));
return Response.ok().replaceAll(headers).build();
} catch (Throwable error) {
logger.error(String.format("Cannot retrieve metadata for %s in %s.", pathname, dataspacePath), error);
throw rethrow(error);
}
}Example 22
| Project: scheduling-master File: RestDataspaceImpl.java View source code |
/**
* Retrieve metadata of file in the location specified in <i>dataspace</i>.
* The format of the HEAD URI is:
* <p>
* {@code http://<rest-server-path>/data/<dataspace>/<path-name>}
* <p>
* Example:
* {@code http://localhost:8080/rest/rest/data/user/my-files/my-text-file.txt}
*
*/
@HEAD
@Path("/{dataspace}/{path-name:.*}")
public Response metadata(@HeaderParam("sessionid") String sessionId, @PathParam("dataspace") String dataspacePath, @PathParam("path-name") String pathname) throws NotConnectedRestException, PermissionRestException {
Session session = checkSessionValidity(sessionId);
try {
checkPathParams(dataspacePath, pathname);
FileObject fo = resolveFile(session, dataspacePath, pathname);
if (!fo.exists()) {
return notFoundRes();
}
logger.debug(String.format("Retrieving metadata for %s in %s", pathname, dataspacePath));
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>(FileSystem.metadata(fo));
return Response.ok().replaceAll(headers).build();
} catch (Throwable error) {
logger.error(String.format("Cannot retrieve metadata for %s in %s.", pathname, dataspacePath), error);
throw rethrow(error);
}
}Example 23
| Project: swagger-inflector-master File: RequestTestIT.java View source code |
@Test
public void verifyPostFormData() throws Exception {
String path = "/formTest";
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("user", "tony,the tam");
String str = client.invokeAPI(// path
path, // method
"POST", // query
new HashMap<String, String>(), // body
null, // header
new HashMap<String, String>(), // form
Entity.form(formData), // accept
"application/json", // contentType
"x-www-form-urlencoded", new String[0]);
assertEquals(str, "tony,the tam");
}Example 24
| Project: swiftproxy-master File: BlobStoreResource.java View source code |
private void debugWrite(Object root, MediaType format) {
MessageBodyWriter messageBodyWriter = workers.getMessageBodyWriter(root.getClass(), root.getClass(), new Annotation[] {}, format);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
// use the MBW to serialize myBean into baos
messageBodyWriter.writeTo(root, root.getClass(), root.getClass(), new Annotation[] {}, format, new MultivaluedHashMap<String, Object>(), baos);
} catch (Throwable e) {
logger.error(String.format("could not serialize %s to format %s", root, format), e);
throw propagate(e);
}
logger.info("{}", baos);
}Example 25
| Project: user-master File: QueryAnalyzerExceptionMapper.java View source code |
// This mapper is used to short-circuit the query process on any collection query. Therefore, it does its best
// job to build a normal ApiResponse format with 200 OK status.
@Override
public Response toResponse(QueryAnalyzerException e) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.add("ql", e.getOriginalQuery());
params.add("analyzeOnly", "true");
// build a proper ApiResponse object
ApiResponse apiResponse = new ApiResponse();
apiResponse.setParams(params);
apiResponse.setSuccess();
// remove large_index warnings because indexes are shared buckets and not specific for an app
for (int i = 0; i < e.getViolations().size(); i++) {
if (e.getViolations().get(i).get(QueryAnalyzer.k_violation) == QueryAnalyzer.v_large_index) {
e.getViolations().remove(i);
}
}
apiResponse.setMetadata(new HashMap<String, Object>() {
{
put("queryWarnings", e.getViolations());
}
});
apiResponse.setEntities(Collections.emptyList());
apiResponse.setAction("query analysis only");
// give toResponse() the json string value of the ApiResponse
return toResponse(OK, mapToFormattedJsonString(apiResponse));
}Example 26
| Project: usergrid-master File: QueryAnalyzerExceptionMapper.java View source code |
// This mapper is used to short-circuit the query process on any collection query. Therefore, it does its best
// job to build a normal ApiResponse format with 200 OK status.
@Override
public Response toResponse(QueryAnalyzerException e) {
MultivaluedMap<String, String> params = new MultivaluedHashMap<>();
params.add("ql", e.getOriginalQuery());
params.add("analyzeOnly", "true");
// build a proper ApiResponse object
ApiResponse apiResponse = new ApiResponse();
apiResponse.setParams(params);
apiResponse.setSuccess();
// remove large_index warnings because indexes are shared buckets and not specific for an app
for (int i = 0; i < e.getViolations().size(); i++) {
if (e.getViolations().get(i).get(QueryAnalyzer.k_violation) == QueryAnalyzer.v_large_index) {
e.getViolations().remove(i);
}
}
apiResponse.setMetadata(new HashMap<String, Object>() {
{
put("queryWarnings", e.getViolations());
}
});
apiResponse.setEntities(Collections.emptyList());
apiResponse.setAction("query analysis only");
// give toResponse() the json string value of the ApiResponse
return toResponse(OK, mapToFormattedJsonString(apiResponse));
}Example 27
| Project: vitam-master File: ConnectionImpl.java View source code |
/**
* Generate the default header map
*
* @param tenantId
* the tenantId
* @param command
* the command to be added
* @param digest
* the digest of the object to be added
* @param digestType
* the type of the digest to be added
* @return header map
*/
private MultivaluedHashMap<String, Object> getDefaultHeaders(Integer tenantId, String command, String digest, String digestType) {
final MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<>();
if (tenantId != null) {
headers.add(GlobalDataRest.X_TENANT_ID, tenantId);
}
if (command != null) {
headers.add(GlobalDataRest.X_COMMAND, command);
}
if (digest != null) {
headers.add(GlobalDataRest.X_DIGEST, digest);
}
if (digestType != null) {
headers.add(GlobalDataRest.X_DIGEST_ALGORITHM, digestType);
}
return headers;
}Example 28
| Project: wl-course-signup-master File: SignupResourceTest.java View source code |
@Test
public void testSignup() throws JSONException {
when(proxy.isAnonymousUser()).thenReturn(false);
CourseSignup signup = mock(CourseSignup.class);
when(signup.getId()).thenReturn("id");
when(signup.getNotes()).thenReturn("notes");
when(signup.getSpecialReq()).thenReturn("specialReq");
when(courseSignupService.signup(anyString(), anyString(), anyString(), anyString(), anySet(), anyString())).thenReturn(signup);
MultivaluedHashMap<String, String> formData = new MultivaluedHashMap<String, String>();
Response response = target("/signup/new").request("application/json").post(Entity.form(formData));
assertEquals(201, response.getStatus());
verify(courseSignupService, times(1)).signup(anyString(), anyString(), anyString(), anyString(), anySet(), anyString());
String json = response.readEntity(String.class);
JSONAssert.assertEquals("{id: 'id', notes: 'notes', specialReq: 'specialReq'}", json, JSONCompareMode.LENIENT);
}Example 29
| Project: airlift-master File: JaxrsTestingHttpProcessor.java View source code |
@Override
public Response handle(Request request) throws Exception {
// prepare request to jax-rs resource
MultivaluedMap<String, Object> requestHeaders = new MultivaluedHashMap<>();
for (Map.Entry<String, String> entry : request.getHeaders().entries()) {
requestHeaders.add(entry.getKey(), entry.getValue());
}
Invocation.Builder invocationBuilder = client.target(request.getUri()).request().headers(requestHeaders);
Invocation invocation;
if (request.getBodyGenerator() == null) {
invocation = invocationBuilder.build(request.getMethod());
} else {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
request.getBodyGenerator().write(byteArrayOutputStream);
byteArrayOutputStream.close();
byte[] bytes = byteArrayOutputStream.toByteArray();
Entity<byte[]> entity = Entity.entity(bytes, (String) getOnlyElement(requestHeaders.get("Content-Type")));
invocation = invocationBuilder.build(request.getMethod(), entity);
}
// issue request, and handle exceptions
javax.ws.rs.core.Response result;
try {
result = invocation.invoke(javax.ws.rs.core.Response.class);
} catch (ProcessingException exception) {
if (trace) {
log.warn(exception.getCause(), "%-8s %s -> Exception", request.getMethod(), request.getUri());
}
if (exception.getCause() instanceof Exception) {
throw (Exception) exception.getCause();
}
throw exception;
} catch (Throwable throwable) {
if (trace) {
log.warn(throwable, "%-8s %s -> Fail", request.getMethod(), request.getUri());
}
throw throwable;
}
// process response from jax-rs resource
ImmutableListMultimap.Builder<String, String> responseHeaders = ImmutableListMultimap.builder();
for (Map.Entry<String, List<String>> headerEntry : result.getStringHeaders().entrySet()) {
for (String value : headerEntry.getValue()) {
responseHeaders.put(headerEntry.getKey(), value);
}
}
if (trace) {
log.warn("%-8s %s -> OK", request.getMethod(), request.getUri());
}
return new TestingResponse(HttpStatus.OK, responseHeaders.build(), result.readEntity(byte[].class));
}Example 30
| Project: cloud-odata-java-master File: ODataExceptionMapperImplTest.java View source code |
@Before
public void before() throws URISyntaxException {
exceptionMapper = new ODataExceptionMapperImpl();
exceptionMapper.httpHeaders = mock(HttpHeaders.class);
exceptionMapper.uriInfo = mock(UriInfo.class);
exceptionMapper.servletConfig = mock(ServletConfig.class);
exceptionMapper.servletRequest = mock(HttpServletRequest.class);
MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
when(exceptionMapper.uriInfo.getQueryParameters()).thenReturn(map);
uri = new URI("http://localhost:8080/ODataService.svc/Entity");
when(exceptionMapper.uriInfo.getRequestUri()).thenReturn(uri);
MultivaluedHashMap<String, String> httpHeaders = new MultivaluedHashMap<String, String>();
when(exceptionMapper.httpHeaders.getRequestHeaders()).thenReturn(httpHeaders);
disableLogging();
}Example 31
| Project: dropwizard-master File: JacksonMessageBodyProviderTest.java View source code |
@Test
public void deserializesRequestEntities() throws Exception {
final ByteArrayInputStream entity = new ByteArrayInputStream("{\"id\":1}".getBytes(StandardCharsets.UTF_8));
final Class<?> klass = Example.class;
final Object obj = provider.readFrom((Class<Object>) klass, Example.class, NONE, MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<>(), entity);
assertThat(obj).isInstanceOf(Example.class);
assertThat(((Example) obj).id).isEqualTo(1);
}Example 32
| Project: ff-master File: ApiKeyValidatorFilterTest.java View source code |
@Test(expected = WebApplicationException.class)
public void testFilterInvalid() throws Exception {
ContainerRequestContext mockRequest = mock(ContainerRequestContext.class);
MultivaluedMap<String, String> mvm = new MultivaluedHashMap<>();
mvm.putSingle(ApiKeyValidatorFilter.HEADER_APIKEY, "12");
when(mockRequest.getHeaders()).thenReturn(mvm);
ApiKeyValidatorFilter f1 = new ApiKeyValidatorFilter();
f1.filter(mockRequest);
}Example 33
| Project: ff4j-master File: ApiKeyValidatorFilterTest.java View source code |
@Test(expected = WebApplicationException.class)
public void testFilterInvalid() throws Exception {
ContainerRequestContext mockRequest = mock(ContainerRequestContext.class);
MultivaluedMap<String, String> mvm = new MultivaluedHashMap<>();
mvm.putSingle(ApiKeyValidatorFilter.HEADER_APIKEY, "12");
when(mockRequest.getHeaders()).thenReturn(mvm);
ApiKeyValidatorFilter f1 = new ApiKeyValidatorFilter();
f1.filter(mockRequest);
}Example 34
| Project: glassfish-main-master File: RestUtil.java View source code |
//*******************************************************************************************************************
//*******************************************************************************************************************
protected static MultivaluedMap buildMultivalueMap(Map<String, Object> payload) {
MultivaluedMap formData = new MultivaluedHashMap();
if (payload == null || payload.isEmpty()) {
return formData;
}
for (final Map.Entry<String, Object> entry : payload.entrySet()) {
final Object value = entry.getValue();
final String key = entry.getKey();
if (value instanceof Collection) {
for (Object obj : ((Collection) value)) {
try {
formData.add(key, obj);
} catch (ClassCastException ex) {
Logger logger = GuiUtil.getLogger();
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, GuiUtil.getCommonMessage("LOG_BUILD_MULTI_VALUE_MAP_ERROR", new Object[] { key, obj }));
}
}
}
} else {
//formData.putSingle(key, (value != null) ? value.toString() : value);
try {
formData.putSingle(key, value);
} catch (ClassCastException ex) {
Logger logger = GuiUtil.getLogger();
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, GuiUtil.getCommonMessage("LOG_BUILD_MULTI_VALUE_MAP_ERROR", new Object[] { key, value }));
}
}
}
}
return formData;
}Example 35
| Project: javaee7-archetypes-master File: EmployeeResourceTest.java View source code |
/**
* Test of getList method, of class MyResource.
*/
@Test
@InSequence(1)
public void testPostAndGet() {
MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
map.add("name", "Penny");
map.add("age", "1");
target.request().post(Entity.form(map));
map.clear();
map.add("name", "Leonard");
map.add("age", "2");
target.request().post(Entity.form(map));
map.clear();
map.add("name", "Sheldon");
map.add("age", "3");
target.request().post(Entity.form(map));
Employee[] list = target.request().get(Employee[].class);
assertEquals(3, list.length);
assertEquals("Penny", list[0].getName());
assertEquals(1, list[0].getAge());
assertEquals("Leonard", list[1].getName());
assertEquals(2, list[1].getAge());
assertEquals("Sheldon", list[2].getName());
assertEquals(3, list[2].getAge());
}Example 36
| Project: JavaIncrementalParser-master File: TestServlet.java View source code |
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Request Binding</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Resource Validation in JAX-RS</h1>");
Client client = ClientBuilder.newClient();
List<WebTarget> targets = new ArrayList<>();
for (int i = 0; i < 3; i++) {
targets.add(client.target("http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/webresources/names" + (i + 1)));
}
for (WebTarget target : targets) {
out.println("<h2>Using target: " + target.getUri() + "</h2>");
MultivaluedHashMap<String, String> map = new MultivaluedHashMap<>();
out.print("<br><br>POSTing with valid data ...<br>");
map.add("firstName", "Sheldon");
map.add("lastName", "Cooper");
map.add("email", "random@example.com");
Response r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 200);
out.println();
out.print("<br><br>POSTing with invalid (null) \"firstName\" ...<br>");
map.putSingle("firstName", null);
r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 200);
out.println();
out.print("<br><br>POSTing with invalid (null) \"lastName\" ...<br>");
map.putSingle("firstName", "Sheldon");
map.putSingle("lastName", null);
r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 400);
out.print("<br><br>POSTing with invalid (missing @) email \"email\" ...<br>");
map.putSingle("lastName", "Cooper");
map.putSingle("email", "randomexample.com");
r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 400);
out.print("<br><br>POSTing with invalid (missing .com) email \"email\" ...<br>");
map.putSingle("email", "random@examplecom");
r = target.request().post(Entity.form(map));
printResponseStatus(out, r, 400);
}
WebTarget target = client.target("http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/webresources/nameadd");
out.println("<h2>Using target: " + target.getUri() + "</h2>");
out.print("<br><br>POSTing using @Valid (all vaild data) ...<br>");
Response r = target.request().post(Entity.json(new Name("Sheldon", "Cooper", "sheldon@cooper.com")));
printResponseStatus(out, r, 200);
out.print("<br><br>POSTing using @Valid, with invalid (null) \"firstName\" ...<br>");
r = target.request().post(Entity.json(new Name(null, "Cooper", "sheldon@cooper.com")));
printResponseStatus(out, r, 400);
out.print("<br><br>POSTing using @Valid, with invalid (null) \"lastName\" ...<br>");
r = target.request().post(Entity.json(new Name("Sheldon", null, "sheldon@cooper.com")));
printResponseStatus(out, r, 400);
out.print("<br><br>POSTing using @Valid, with invalid (missing @) email \"email\" ...<br>");
r = target.request().post(Entity.json(new Name("Sheldon", "Cooper", "sheldoncooper.com")));
printResponseStatus(out, r, 400);
out.println("<br>... done.<br>");
out.println("</body>");
out.println("</html>");
}Example 37
| Project: javaone2015-cloudone-master File: GsonProviderTest.java View source code |
@Test
public void testReadWrite() throws Exception {
GsonProvider provider = new GsonProvider();
A a = new A("foo", 100);
ByteArrayOutputStream os = new ByteArrayOutputStream();
provider.writeTo(a, a.getClass(), a.getClass(), new Annotation[0], MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<String, Object>(), os);
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
Object o = provider.readFrom(A.class, A.class, new Annotation[0], MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<String, String>(), is);
assertTrue(o instanceof A);
assertEquals(a, o);
}Example 38
| Project: jersey-master File: ResourceMethodInvoker.java View source code |
private <T> void addNameBoundProviders(final Collection<RankedProvider<T>> targetCollection, final NameBound nameBound, final MultivaluedMap<Class<? extends Annotation>, RankedProvider<T>> nameBoundProviders, final MultivaluedMap<RankedProvider<T>, Class<? extends Annotation>> nameBoundProvidersInverse) {
final MultivaluedMap<RankedProvider<T>, Class<? extends Annotation>> foundBindingsMap = new MultivaluedHashMap<>();
for (final Class<? extends Annotation> nameBinding : nameBound.getNameBindings()) {
final Iterable<RankedProvider<T>> providers = nameBoundProviders.get(nameBinding);
if (providers != null) {
for (final RankedProvider<T> provider : providers) {
foundBindingsMap.add(provider, nameBinding);
}
}
}
for (final Map.Entry<RankedProvider<T>, List<Class<? extends Annotation>>> entry : foundBindingsMap.entrySet()) {
final RankedProvider<T> provider = entry.getKey();
final List<Class<? extends Annotation>> foundBindings = entry.getValue();
final List<Class<? extends Annotation>> providerBindings = nameBoundProvidersInverse.get(provider);
if (foundBindings.size() == providerBindings.size()) {
targetCollection.add(provider);
}
}
}Example 39
| Project: kickr-master File: FormDataReaderWriter.java View source code |
@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
MultivaluedMap<String, String> bodyMap = readFrom(new MultivaluedHashMap<>(), mediaType, true, entityStream);
Object instance = FormParser.toForm(type, bodyMap);
if (isAnnotated(Valid.class, annotations)) {
Set<ConstraintViolation<Object>> violations = validator.validate(instance);
if (!violations.isEmpty()) {
throw new ConstraintViolationException(violations);
}
}
return instance;
}Example 40
| Project: mdmconnectors-master File: MDMRestConnection.java View source code |
public EnvelopeVO executeCommand(ICommand command) {
if (command instanceof CommandPostStagingC) {
this.client.register(GZipReaderInterceptor.class);
this.client.register(GZipWriterInterceptor.class);
}
Map<String, String> parametersHeader = command.getParametersHeader();
Map<String, String> parameterPath = command.getParameterPath();
Set<String> keySetPath = parameterPath != null ? parameterPath.keySet() : null;
Set<String> keySetHeader = parametersHeader != null ? parametersHeader.keySet() : null;
WebTarget webResource = this.client.target(mdmURL + command.getCommandURL());
if (keySetPath != null) {
for (String string : keySetPath) {
webResource = webResource.queryParam(string, parameterPath.get(string));
}
}
Builder request = webResource.request(MediaType.APPLICATION_JSON);
if (keySetHeader != null) {
for (String string : keySetHeader) {
request = request.header(string, parametersHeader.get(string));
}
}
if (command instanceof AuthenticationRequired) {
request = request.header("Authorization", MDMRestAuthentication.getInstance().getAuthVO().getAccess_token());
}
Response response = null;
switch(command.getType()) {
case GET:
long initialTimeGet = System.currentTimeMillis();
response = request.accept(MediaType.APPLICATION_JSON).get();
log.info("Time to execute the GET service ('" + command.getCommandURL() + "'): " + (System.currentTimeMillis() - initialTimeGet));
break;
case POST:
String type = MediaType.APPLICATION_JSON;
String additionalInformation = "";
if (command instanceof CommandPostStagingC) {
request.header(HttpHeaders.ACCEPT_ENCODING, "gzip");
additionalInformation = " - COMPRESS";
}
Map<String, String> formDataCommand = command.getFormData();
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
if (formDataCommand != null && formDataCommand.size() > 0) {
Set<String> keySet = formDataCommand.keySet();
for (String key : keySet) {
String value = formDataCommand.get(key);
formData.add(key, value);
}
}
long initialTimeConvertJson = System.currentTimeMillis();
String string = command.getData() != null ? command.getData().toString() : "";
log.info("Time to convert the OBJECT to JSON: " + (System.currentTimeMillis() - initialTimeConvertJson));
long initialTime = System.currentTimeMillis();
if (formData != null && formData.size() > 0) {
response = request.accept(type).post(Entity.form(formData));
} else {
response = request.accept(type).post(Entity.entity(string, type));
}
log.info("Time to execute the POST service ('" + command.getCommandURL() + "'" + additionalInformation + "): " + (System.currentTimeMillis() - initialTime));
break;
}
if (response.getStatus() != Response.Status.OK.getStatusCode()) {
if (command.getData() != null) {
log.info("Data response:" + command.getData().toString());
}
String readEntity = response.readEntity(String.class);
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus() + " -> " + readEntity);
}
Gson gson = new Gson();
Object resultVO = gson.fromJson(response.readEntity(String.class), command.getResponseType());
EnvelopeVO envelopeVO = null;
if (resultVO instanceof EnvelopeVO) {
envelopeVO = (EnvelopeVO) resultVO;
} else {
envelopeVO = new EnvelopeVO();
List<GenericVO> genericVO = new ArrayList<GenericVO>();
genericVO.add((GenericVO) resultVO);
envelopeVO.setHits(genericVO);
}
return envelopeVO;
}Example 41
| Project: NetLicensingClient-java-master File: BaseEntityImpl.java View source code |
protected MultivaluedMap<String, Object> asPropertiesMap() {
final MultivaluedMap<String, Object> map = new MultivaluedHashMap<>();
map.add(Constants.NUMBER, getNumber());
map.add(Constants.ACTIVE, getActive());
if (properties != null) {
for (final Map.Entry<String, String> lp : properties.entrySet()) {
map.add(lp.getKey(), lp.getValue());
}
}
return map;
}Example 42
| Project: olingo-odata2-master File: ODataExceptionMapperImplTest.java View source code |
@Before
public void before() throws URISyntaxException {
exceptionMapper = new ODataExceptionMapperImpl();
exceptionMapper.httpHeaders = mock(HttpHeaders.class);
exceptionMapper.uriInfo = mock(UriInfo.class);
exceptionMapper.servletConfig = mock(ServletConfig.class);
exceptionMapper.servletRequest = mock(HttpServletRequest.class);
MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
when(exceptionMapper.uriInfo.getQueryParameters()).thenReturn(map);
uri = new URI("http://localhost:8080/ODataService.svc/Entity");
when(exceptionMapper.uriInfo.getRequestUri()).thenReturn(uri);
when(exceptionMapper.servletConfig.getInitParameter(ODataServiceFactory.FACTORY_LABEL)).thenReturn(ODataServiceFactoryImpl.class.getName());
when(exceptionMapper.servletRequest.getAttribute(ODataServiceFactory.FACTORY_CLASSLOADER_LABEL)).thenReturn(ODataServiceFactoryImpl.class.getClassLoader());
MultivaluedHashMap<String, String> httpHeaders = new MultivaluedHashMap<String, String>();
when(exceptionMapper.httpHeaders.getRequestHeaders()).thenReturn(httpHeaders);
disableLogging();
}Example 43
| Project: SocialSemanticServer-master File: SSCoreSQL.java View source code |
public List<SSUri> getEntityURIs(final SSServPar servPar, final List<SSUri> entities, final List<SSEntityE> types, final Long startTime, final Long endTime) throws SSErr {
ResultSet resultSet = null;
try {
if ((entities == null || entities.isEmpty()) && (types == null || types.isEmpty())) {
throw SSErr.get(SSErrE.parameterMissing);
}
final List<MultivaluedMap<String, String>> wheres = new ArrayList<>();
final MultivaluedMap<String, MultivaluedMap<String, String>> wheresNumeric = new MultivaluedHashMap<>();
final List<SSSQLTableI> tables = new ArrayList<>();
final List<String> columns = new ArrayList<>();
final List<String> tableCons = new ArrayList<>();
column(columns, SSEntitySQLTableE.entity, SSSQLVarNames.id);
table(tables, SSEntitySQLTableE.entity);
if (types != null && !types.isEmpty()) {
final MultivaluedMap<String, String> whereTypes = new MultivaluedHashMap<>();
for (SSEntityE type : types) {
where(whereTypes, SSEntitySQLTableE.entity, SSSQLVarNames.type, type);
}
wheres.add(whereTypes);
}
if (entities != null && !entities.isEmpty()) {
final MultivaluedMap<String, String> whereEntities = new MultivaluedHashMap<>();
for (SSUri entity : entities) {
where(whereEntities, SSEntitySQLTableE.entity, SSSQLVarNames.id, entity);
}
wheres.add(whereEntities);
}
if (startTime != null && startTime != 0) {
final List<MultivaluedMap<String, String>> greaterWheres = new ArrayList<>();
final MultivaluedMap<String, String> whereNumbericStartTimes = new MultivaluedHashMap<>();
wheresNumeric.put(SSStrU.greaterThan, greaterWheres);
where(whereNumbericStartTimes, SSEntitySQLTableE.entity, SSSQLVarNames.creationTime, startTime);
greaterWheres.add(whereNumbericStartTimes);
}
if (endTime != null && endTime != 0) {
final List<MultivaluedMap<String, String>> lessWheres = new ArrayList<>();
final MultivaluedMap<String, String> whereNumbericEndTimes = new MultivaluedHashMap<>();
wheresNumeric.put(SSStrU.lessThan, lessWheres);
where(whereNumbericEndTimes, SSEntitySQLTableE.entity, SSSQLVarNames.creationTime, endTime);
lessWheres.add(whereNumbericEndTimes);
}
resultSet = dbSQL.select(new SSDBSQLSelectPar(servPar, tables, columns, //orWheres
wheres, //andWheres
null, //numericWheres
wheresNumeric, tableCons));
return getURIsFromResult(resultSet, SSSQLVarNames.id);
} catch (Exception error) {
SSServErrReg.regErrThrow(error);
return null;
} finally {
try {
dbSQL.closeStmt(resultSet);
} catch (Exception sqlError) {
SSServErrReg.regErrThrow(sqlError);
}
}
}Example 44
| Project: web-framework-master File: JacksonMessageBodyProviderTest.java View source code |
@Test
public void deserializesRequestEntities() throws Exception {
final ByteArrayInputStream entity = new ByteArrayInputStream("{\"id\":1}".getBytes(StandardCharsets.UTF_8));
final Class<?> klass = Example.class;
final Object obj = provider.readFrom((Class<Object>) klass, Example.class, NONE, MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<>(), entity);
assertThat(obj).isInstanceOf(Example.class);
assertThat(((Example) obj).id).isEqualTo(1);
}Example 45
| Project: _Whydah-UserAdminService-master File: CreateUserIntegrationTest.java View source code |
public String logonUserAdmin(String appTokenID) {
// @Path("/{applicationtokenid}/usertoken")
// public Response getUserToken(@PathParam("applicationtokenid") String applicationtokenid,
// @FormParam("apptoken") String appTokenXml,
// @FormParam("usercredential") String userCredentialXml) {
target = stsPath().path("/token/" + appTokenID + "/usertoken");
MultivaluedMap<String, String> formData = new MultivaluedHashMap<>();
formData.add("apptoken", uasCredentialXml());
formData.add("usercredential", userAdminCredentialXml());
Response response = target.request(MediaType.APPLICATION_XML).post(Entity.entity(formData, MediaType.APPLICATION_FORM_URLENCODED));
String responseBody = readResponse("UserAdmin", response);
return responseBody;
}Example 46
| Project: ddf-master File: TestOpenSearchSource.java View source code |
private OpenSearchSource givenSource(Answer<BinaryContent> answer) throws IOException, ResourceNotFoundException, ResourceNotSupportedException {
WebClient client = mock(WebClient.class);
ResourceReader mockReader = mock(ResourceReader.class);
Response clientResponse = mock(Response.class);
when(clientResponse.getEntity()).thenReturn(getBinaryData());
when(clientResponse.getHeaderString(eq(OpenSearchSource.HEADER_ACCEPT_RANGES))).thenReturn(OpenSearchSource.BYTES);
when(client.get()).thenReturn(clientResponse);
SecureCxfClientFactory factory = getMockFactory(client);
when(mockReader.retrieveResource(any(URI.class), any(Map.class))).thenReturn(new ResourceResponseImpl(new ResourceImpl(getBinaryData(), "")));
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
headers.put(HttpHeaders.CONTENT_TYPE, Arrays.<Object>asList("application/octet-stream"));
when(clientResponse.getHeaders()).thenReturn(headers);
OverriddenOpenSearchSource source = new OverriddenOpenSearchSource(FILTER_ADAPTER, encryptionService);
source.setEndpointUrl("http://localhost:8181/services/catalog/query");
source.setParameters(DEFAULT_PARAMETERS);
source.init();
source.setLocalQueryOnly(true);
source.setInputTransformer(getMockInputTransformer());
source.factory = factory;
source.setResourceReader(mockReader);
return source;
}Example 47
| Project: eureka-master File: Jersey2ApplicationClientFactory.java View source code |
@Override
public Jersey2ApplicationClientFactory build() {
ClientBuilder clientBuilder = ClientBuilder.newBuilder();
ClientConfig clientConfig = new ClientConfig();
for (ClientRequestFilter filter : additionalFilters) {
clientBuilder.register(filter);
}
for (Feature feature : features) {
clientConfig.register(feature);
}
addProviders(clientConfig);
addSSLConfiguration(clientBuilder);
addProxyConfiguration(clientConfig);
// Common properties to all clients
final String fullUserAgentName = (userAgent == null ? clientName : userAgent) + "/v" + buildVersion();
clientBuilder.register(new // Can we do it better, without filter?
ClientRequestFilter() {
@Override
public void filter(ClientRequestContext requestContext) {
requestContext.getHeaders().put(HttpHeaders.USER_AGENT, Collections.<Object>singletonList(fullUserAgentName));
}
});
clientConfig.property(ClientProperties.FOLLOW_REDIRECTS, allowRedirect);
clientConfig.property(ClientProperties.READ_TIMEOUT, readTimeout);
clientConfig.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout);
clientBuilder.withConfig(clientConfig);
// Add gzip content encoding support
clientBuilder.register(new GZipEncoder());
// always enable client identity headers
String ip = myInstanceInfo == null ? null : myInstanceInfo.getIPAddr();
final AbstractEurekaIdentity identity = clientIdentity == null ? new EurekaClientIdentity(ip) : clientIdentity;
clientBuilder.register(new Jersey2EurekaIdentityHeaderFilter(identity));
JerseyClient jersey2Client = (JerseyClient) clientBuilder.build();
MultivaluedMap<String, Object> additionalHeaders = new MultivaluedHashMap<>();
if (allowRedirect) {
additionalHeaders.add(HTTP_X_DISCOVERY_ALLOW_REDIRECT, "true");
}
if (EurekaAccept.compact == eurekaAccept) {
additionalHeaders.add(EurekaAccept.HTTP_X_EUREKA_ACCEPT, eurekaAccept.name());
}
return new Jersey2ApplicationClientFactory(jersey2Client, additionalHeaders);
}Example 48
| Project: graylog2-server-master File: ShiroSecurityContextFilterTest.java View source code |
@Test
public void filterWithoutAuthorizationHeaderShouldDoNothing() throws Exception {
final MultivaluedHashMap<String, String> headers = new MultivaluedHashMap<>();
when(requestContext.getHeaders()).thenReturn(headers);
filter.filter(requestContext);
final ArgumentCaptor<SecurityContext> argument = ArgumentCaptor.forClass(SecurityContext.class);
verify(requestContext).setSecurityContext(argument.capture());
assertThat(argument.getValue()).isExactlyInstanceOf(ShiroSecurityContext.class);
assertThat(argument.getValue().getAuthenticationScheme()).isNull();
}Example 49
| Project: keycloak-master File: KerberosStandaloneTest.java View source code |
@Override
protected ComponentRepresentation getUserStorageConfiguration() {
Map<String, String> kerberosConfig = kerberosRule.getConfig();
MultivaluedHashMap<String, String> config = toComponentConfig(kerberosConfig);
UserStorageProviderModel model = new UserStorageProviderModel();
model.setLastSync(0);
model.setChangedSyncPeriod(-1);
model.setFullSyncPeriod(-1);
model.setName("kerberos-standalone");
model.setPriority(0);
model.setProviderId(KerberosFederationProviderFactory.PROVIDER_NAME);
model.setConfig(config);
ComponentRepresentation rep = ModelToRepresentation.toRepresentationWithoutConfig(model);
return rep;
}Example 50
| Project: plus-master File: RESTProvenanceClient.java View source code |
// End validateResponse
/**
* Report a provenance collection to a remote service. This has the effect of writing the given
* provenance collection to the remote service's store.
* @param col the collection to report
* @return true if successful, false if not successful.
* @throws ProvenanceClientException
*/
public boolean report(ProvenanceCollection col) throws ProvenanceClientException {
Builder r = getRequestBuilderForPath(NEW_GRAPH_PATH);
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
String json = JSONConverter.provenanceCollectionToD3Json(col);
// System.out.println("POSTING:\n" + json + "\n\n");
formData.add("provenance", json);
Response response = r.post(Entity.form(formData));
validateResponse(response);
String output = response.readEntity(String.class);
System.out.println(response);
System.out.println(response.getLength());
System.out.println(response.getStatus());
System.out.println(output);
return true;
}Example 51
| Project: transactions-essentials-master File: CoordinatorImpTestJUnit.java View source code |
public static void main(String[] args) throws DatatypeConfigurationException, IOException {
Transaction transaction = createTransaction("2002-05-30T09:30:10Z", "http://1", "http://2");
JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
provider.writeTo(transaction, Transaction.class, Transaction.class, null, MediaType.APPLICATION_JSON_TYPE, new MultivaluedHashMap<String, Object>(), System.out);
}Example 52
| Project: dropwizard-xml-master File: JacksonXMLMessageBodyProviderTest.java View source code |
@Test
public void deserializesRequestEntities() throws Exception {
final ByteArrayInputStream entity = new ByteArrayInputStream("<Example xmlns=\"\"><id>1</id></Example>".getBytes());
final Class<?> klass = Example.class;
final Object obj = provider.readFrom((Class<Object>) klass, Example.class, NONE, MediaType.APPLICATION_XML_TYPE, new MultivaluedHashMap<>(), entity);
assertThat(obj).isInstanceOf(Example.class);
assertThat(((Example) obj).id).isEqualTo(1);
}Example 53
| Project: glassfish-master File: RestUtil.java View source code |
//*******************************************************************************************************************
//*******************************************************************************************************************
protected static MultivaluedMap buildMultivalueMap(Map<String, Object> payload) {
MultivaluedMap formData = new MultivaluedHashMap();
if (payload == null || payload.isEmpty()) {
return formData;
}
for (final Map.Entry<String, Object> entry : payload.entrySet()) {
final Object value = entry.getValue();
final String key = entry.getKey();
if (value instanceof Collection) {
for (Object obj : ((Collection) value)) {
try {
formData.add(key, obj);
} catch (ClassCastException ex) {
Logger logger = GuiUtil.getLogger();
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, GuiUtil.getCommonMessage("LOG_BUILD_MULTI_VALUE_MAP_ERROR", new Object[] { key, obj }));
}
}
}
} else {
//formData.putSingle(key, (value != null) ? value.toString() : value);
try {
if (key.equals("availabilityEnabled")) {
System.out.println("================== availabilityEnabled skipped ");
}
formData.putSingle(key, value);
} catch (ClassCastException ex) {
Logger logger = GuiUtil.getLogger();
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, GuiUtil.getCommonMessage("LOG_BUILD_MULTI_VALUE_MAP_ERROR", new Object[] { key, value }));
}
}
}
}
return formData;
}Example 54
| Project: oxAuth-master File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java View source code |
/**
* Call to Token Endpoint with Auth Method <code>client_secret_basic</code>.
*/
@Parameters({ "tokenPath", "redirectUri" })
@Test(dependsOnMethods = { "tokenEndpointAuthMethodClientSecretBasicStep3" })
public void tokenEndpointAuthMethodClientSecretBasicStep4(final String tokenPath, final String redirectUri) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();
TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
tokenRequest.setCode(authorizationCode2);
tokenRequest.setRedirectUri(redirectUri);
tokenRequest.setAuthUsername(clientId2);
tokenRequest.setAuthPassword(clientSecret2);
request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());
request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
Response response = request.post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
String entity = response.readEntity(String.class);
showResponse("tokenEndpointAuthMethodClientSecretBasicStep4", response, entity);
assertEquals(response.getStatus(), 200, "Unexpected response code.");
assertTrue(response.getHeaderString("Cache-Control") != null && response.getHeaderString("Cache-Control").equals("no-store"), "Unexpected result: " + response.getHeaderString("Cache-Control"));
assertTrue(response.getHeaderString("Pragma") != null && response.getHeaderString("Pragma").equals("no-cache"), "Unexpected result: " + response.getHeaderString("Pragma"));
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has("access_token"), "Unexpected result: access_token not found");
assertTrue(jsonObj.has("token_type"), "Unexpected result: token_type not found");
assertTrue(jsonObj.has("refresh_token"), "Unexpected result: refresh_token not found");
assertTrue(jsonObj.has("id_token"), "Unexpected result: id_token not found");
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}Example 55
| Project: Payara-master File: RestUtil.java View source code |
//*******************************************************************************************************************
//*******************************************************************************************************************
protected static MultivaluedMap buildMultivalueMap(Map<String, Object> payload) {
MultivaluedMap formData = new MultivaluedHashMap();
if (payload == null || payload.isEmpty()) {
return formData;
}
for (final Map.Entry<String, Object> entry : payload.entrySet()) {
final Object value = entry.getValue();
final String key = entry.getKey();
if (value instanceof Collection) {
for (Object obj : ((Collection) value)) {
try {
formData.add(key, obj);
} catch (ClassCastException ex) {
Logger logger = GuiUtil.getLogger();
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, GuiUtil.getCommonMessage("LOG_BUILD_MULTI_VALUE_MAP_ERROR", new Object[] { key, obj }));
}
}
}
} else {
//formData.putSingle(key, (value != null) ? value.toString() : value);
try {
if (key.equals("availabilityEnabled")) {
System.out.println("================== availabilityEnabled skipped ");
}
formData.putSingle(key, value);
} catch (ClassCastException ex) {
Logger logger = GuiUtil.getLogger();
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, GuiUtil.getCommonMessage("LOG_BUILD_MULTI_VALUE_MAP_ERROR", new Object[] { key, value }));
}
}
}
}
return formData;
}Example 56
| Project: stanbol-master File: ContentItemReaderWriterTest.java View source code |
/**
* @param out
* @return
* @throws IOException
*/
private MediaType serializeContentItem(ByteArrayOutputStream out) throws IOException {
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
ciWriter.writeTo(contentItem, ContentItem.class, null, null, MediaType.MULTIPART_FORM_DATA_TYPE, headers, out);
//check the returned content type
String contentTypeString = (String) headers.getFirst(HttpHeaders.CONTENT_TYPE);
assertNotNull(contentTypeString);
MediaType contentType = MediaType.valueOf(contentTypeString);
return contentType;
}Example 57
| Project: uma-master File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java View source code |
/**
* Call to Token Endpoint with Auth Method <code>client_secret_basic</code>.
*/
@Parameters({ "tokenPath", "redirectUri" })
@Test(dependsOnMethods = { "tokenEndpointAuthMethodClientSecretBasicStep3" })
public void tokenEndpointAuthMethodClientSecretBasicStep4(final String tokenPath, final String redirectUri) throws Exception {
Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();
TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_BASIC);
tokenRequest.setCode(authorizationCode2);
tokenRequest.setRedirectUri(redirectUri);
tokenRequest.setAuthUsername(clientId2);
tokenRequest.setAuthPassword(clientSecret2);
request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());
request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
Response response = request.post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
String entity = response.readEntity(String.class);
showResponse("tokenEndpointAuthMethodClientSecretBasicStep4", response, entity);
assertEquals(response.getStatus(), 200, "Unexpected response code.");
assertTrue(response.getHeaderString("Cache-Control") != null && response.getHeaderString("Cache-Control").equals("no-store"), "Unexpected result: " + response.getHeaderString("Cache-Control"));
assertTrue(response.getHeaderString("Pragma") != null && response.getHeaderString("Pragma").equals("no-cache"), "Unexpected result: " + response.getHeaderString("Pragma"));
assertNotNull(entity, "Unexpected result: " + entity);
try {
JSONObject jsonObj = new JSONObject(entity);
assertTrue(jsonObj.has("access_token"), "Unexpected result: access_token not found");
assertTrue(jsonObj.has("token_type"), "Unexpected result: token_type not found");
assertTrue(jsonObj.has("refresh_token"), "Unexpected result: refresh_token not found");
assertTrue(jsonObj.has("id_token"), "Unexpected result: id_token not found");
} catch (JSONException e) {
e.printStackTrace();
fail(e.getMessage() + "\nResponse was: " + entity);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}Example 58
| Project: vertx-jersey-master File: VertxResponseWriterTest.java View source code |
@Test
public void testWriteResponseStatusAndHeaders() throws Exception {
ContainerResponse cr = mock(ContainerResponse.class);
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
when(cr.getStatusInfo()).thenReturn(mock(Response.StatusType.class));
when(cr.getStringHeaders()).thenReturn(headers);
VertxResponseProcessor processor1 = mock(VertxResponseProcessor.class);
VertxResponseProcessor processor2 = mock(VertxResponseProcessor.class);
responseProcessors.add(processor1);
responseProcessors.add(processor2);
headers.add("x-test", "custom header");
OutputStream outputStream = writer.writeResponseStatusAndHeaders(15, cr);
assertNotNull(outputStream);
verify(response, times(1)).setStatusCode(anyInt());
verify(response, times(1)).setStatusMessage(anyString());
verify(response, times(1)).putHeader(anyString(), anyListOf(String.class));
verify(processor1).process(eq(response), eq(cr));
verify(processor2).process(eq(response), eq(cr));
writer.writeResponseStatusAndHeaders(-1, cr);
verify(response, times(2)).putHeader(anyString(), anyListOf(String.class));
}Example 59
| Project: ddf-catalog-master File: TestOpenSearchSource.java View source code |
private OpenSearchSource givenSource(Answer<BinaryContent> answer) throws IOException {
WebClient client = mock(WebClient.class);
OpenSearchConnection openSearchConnection = mock(OpenSearchConnection.class);
Client proxy = mock(Client.class);
when(openSearchConnection.newRestClient(any(String.class), any(Query.class), any(String.class), any(Boolean.class))).thenReturn(proxy);
when(openSearchConnection.getWebClientFromClient(proxy)).thenReturn(client);
Response clientResponse = mock(Response.class);
when(client.get()).thenReturn(clientResponse);
when(clientResponse.getEntity()).thenReturn(getBinaryData());
when(clientResponse.getHeaderString(eq(OpenSearchSource.HEADER_ACCEPT_RANGES))).thenReturn(OpenSearchSource.BYTES);
when(openSearchConnection.getOpenSearchWebClient()).thenReturn(client);
MultivaluedMap<String, Object> headers = new MultivaluedHashMap<String, Object>();
headers.put(HttpHeaders.CONTENT_TYPE, Arrays.<Object>asList("application/octet-stream"));
when(clientResponse.getHeaders()).thenReturn(headers);
OverridenOpenSearchSource source = new OverridenOpenSearchSource(FILTER_ADAPTER);
source.setEndpointUrl("http://localhost:8181/services/catalog/query");
source.setParameters("q,src,mr,start,count,mt,dn,lat,lon,radius,bbox,polygon,dtstart,dtend,dateName,filter,sort");
source.init();
source.setLocalQueryOnly(true);
source.setInputTransformer(getMockInputTransformer());
source.openSearchConnection = openSearchConnection;
return source;
}Example 60
| Project: geoplatform-oauth2-extensions-master File: OAuth2CoreClientConnector.java View source code |
@Override
public Boolean saveCheckStatusLayerAndTreeModifications(Long layerID, boolean checked) throws Exception {
String accessToken = super.createToken();
logger.trace(LOGGER_MESSAGE, accessToken, "saveCheckStatusLayerAndTreeModifications");
MultivaluedMap<String, String> formData = new MultivaluedHashMap();
formData.add("layerID", String.valueOf(layerID));
formData.add("checked", String.valueOf(checked));
return client.target(super.getRestServiceURL().concat("jsonSecureLayer/layers/saveCheckStatusLayerAndTreeModifications")).request(MediaType.APPLICATION_JSON).header(HttpHeaders.AUTHORIZATION, "bearer ".concat(accessToken)).put(Entity.form(formData), Boolean.class);
}Example 61
| Project: of-patch-manager-master File: LogicalBusinessImpl.java View source code |
public String updateLogicalTopology(String requestedTopologyJson) {
final String fname = "updateLogicalTopology";
if (logger.isDebugEnabled()) {
logger.trace(String.format("%s(requestedTopology=%s) - start", fname, requestedTopologyJson));
}
LogicalTopologyUpdateJsonOut res = new LogicalTopologyUpdateJsonOut();
res.setStatus(STATUS_SUCCESS);
res.setResult(null);
LogicalTopologyUpdateJsonIn requestedTopology = null;
try {
requestedTopology = LogicalTopologyUpdateJsonIn.fromJson(requestedTopologyJson);
} catch (JsonSyntaxException jse) {
OFPMUtils.logErrorStackTrace(logger, jse);
res.setStatus(STATUS_BAD_REQUEST);
res.setMessage(INVALID_JSON);
String ret = res.toString();
if (logger.isDebugEnabled()) {
logger.debug(String.format("%s(ret=%s) - end", fname, ret));
}
return ret;
}
try {
LogicalTopologyValidate validator = new LogicalTopologyValidate();
validator.checkValidationRequestIn(requestedTopology);
// TODO: check user tenant (by used-info in DMDB).
} catch (ValidateException ve) {
OFPMUtils.logErrorStackTrace(logger, ve);
res.setStatus(STATUS_BAD_REQUEST);
res.setMessage(ve.getMessage());
if (logger.isDebugEnabled()) {
logger.debug(String.format("%s(ret=%s) - end", fname, res));
}
return res.toJson();
}
MultivaluedMap<String, SetFlowToOFC> reducedFlows = new MultivaluedHashMap<String, SetFlowToOFC>();
MultivaluedMap<String, SetFlowToOFC> augmentedFlows = new MultivaluedHashMap<String, SetFlowToOFC>();
ConnectionUtilsJdbc utilsJdbc = null;
Connection conn = null;
try {
/* initialize db connectors */
utilsJdbc = new ConnectionUtilsJdbcImpl();
conn = utilsJdbc.getConnection(false);
dao = new DaoImpl(utilsJdbc);
/* compute Inclement/Declement LogicalLink */
List<LogicalLink> incLinkList = new ArrayList<LogicalLink>();
List<LogicalLink> decLinkList = new ArrayList<LogicalLink>();
{
List<OfpConDeviceInfo> requestedNodes = requestedTopology.getNodes();
List<LogicalLink> requestedLinkList = requestedTopology.getLinks();
Set<LogicalLink> currentLinkList = new HashSet<LogicalLink>();
/* Create current links */
for (OfpConDeviceInfo requestedNode : requestedNodes) {
String devName = requestedNode.getDeviceName();
Set<LogicalLink> linkSet = this.getLogicalLink(conn, devName, false);
if (linkSet != null) {
currentLinkList.addAll(linkSet);
}
}
this.normalizeLogicalLink(requestedNodes, currentLinkList);
/* Set port number 0, because when run Collection.removeAll, port number remove influence. */
for (LogicalLink link : requestedLinkList) {
for (PortData port : link.getLink()) {
port.setPortNumber(null);
}
}
/* get difference between current and next */
decLinkList.addAll(currentLinkList);
decLinkList.removeAll(requestedLinkList);
incLinkList.addAll(requestedLinkList);
incLinkList.removeAll(currentLinkList);
/* sort incliment links. 1st link have port name, final link no have port name. */
Collections.sort(incLinkList, new Comparator<LogicalLink>() {
@Override
public int compare(LogicalLink link1, LogicalLink link2) {
int score1 = 0;
for (PortData port1 : link1.getLink()) {
if (StringUtils.isBlank(port1.getPortName())) {
score1++;
}
}
int score2 = 0;
for (PortData port2 : link2.getLink()) {
if (StringUtils.isBlank(port2.getPortName())) {
score2++;
}
}
return score1 - score2;
}
});
List<LogicalLink> trushIncLinkList = new ArrayList<LogicalLink>();
for (LogicalLink incLink : incLinkList) {
List<PortData> incPorts = incLink.getLink();
for (LogicalLink decLink : decLinkList) {
List<PortData> decPorts = decLink.getLink();
if (OFPMUtils.PortDataNonStrictEquals(decPorts.get(0), incPorts.get(0)) && OFPMUtils.PortDataNonStrictEquals(decPorts.get(1), incPorts.get(1))) {
decLinkList.remove(decLink);
trushIncLinkList.add(incLink);
break;
} else if (OFPMUtils.PortDataNonStrictEquals(decPorts.get(0), incPorts.get(1)) && OFPMUtils.PortDataNonStrictEquals(decPorts.get(1), incPorts.get(0))) {
decLinkList.remove(decLink);
trushIncLinkList.add(incLink);
break;
}
}
}
incLinkList.removeAll(trushIncLinkList);
}
/* update patch wiring and make patch link */
for (LogicalLink link : decLinkList) {
this.addDeclementLogicalLink(conn, link, reducedFlows);
}
for (LogicalLink link : incLinkList) {
this.addInclementLogicalLink(conn, link, augmentedFlows);
}
/* Make nodes and links */
List<LogicalLink> linkList = new ArrayList<LogicalLink>();
Set<LogicalLink> linkSet = new HashSet<LogicalLink>();
List<OfpConDeviceInfo> nodeList = requestedTopology.getNodes();
for (OfpConDeviceInfo node : nodeList) {
String devName = node.getDeviceName();
Set<LogicalLink> links = this.getLogicalLink(conn, devName, false);
if (links == null) {
continue;
}
linkSet.addAll(links);
}
linkList.addAll(linkSet);
LogicalTopology topology = new LogicalTopology();
topology.setNodes(nodeList);
topology.setLinks(linkList);
// create response data
res.setResult(topology);
utilsJdbc.commit(conn);
} catch (NoRouteException e) {
utilsJdbc.rollback(conn);
OFPMUtils.logErrorStackTrace(logger, e);
res.setStatus(STATUS_NOTFOUND);
res.setMessage(e.getMessage());
return res.toJson();
} catch (Exception e) {
utilsJdbc.rollback(conn);
OFPMUtils.logErrorStackTrace(logger, e);
res.setStatus(STATUS_INTERNAL_ERROR);
res.setMessage(e.getMessage());
return res.toJson();
} finally {
utilsJdbc.close(conn);
if (logger.isDebugEnabled()) {
logger.trace(String.format("%s(ret=%s) - end", fname, res));
}
}
/* PHASE : Set flow to OFPS via OFC */
try {
for (Entry<String, List<SetFlowToOFC>> entry : reducedFlows.entrySet()) {
OFCClient client = new OFCClientImpl();
String ofpIp = (String) entry.getKey();
for (SetFlowToOFC flow : entry.getValue()) {
client.deleteFlows(ofpIp, flow);
}
}
for (Entry<String, List<SetFlowToOFC>> entry : augmentedFlows.entrySet()) {
OFCClient client = new OFCClientImpl();
String ofpIp = (String) entry.getKey();
for (SetFlowToOFC flow : entry.getValue()) {
client.addFlows(ofpIp, flow);
}
}
} catch (OFCClientException e) {
OFPMUtils.logErrorStackTrace(logger, e);
res.setStatus(STATUS_INTERNAL_ERROR);
res.setMessage(e.getMessage());
if (logger.isDebugEnabled()) {
logger.debug(String.format("%s(ret=%s) - end", fname, res));
}
return res.toJson();
}
String ret = res.toJson();
if (logger.isDebugEnabled()) {
logger.trace(String.format("%s(ret=%s) - end", fname, ret));
}
return ret;
}Example 62
| Project: para-master File: ParaClient.java View source code |
private MultivaluedMap<String, String> pagerToParams(Pager... pager) {
MultivaluedMap<String, String> map = new MultivaluedHashMap<String, String>();
if (pager != null && pager.length > 0) {
Pager p = pager[0];
if (p != null) {
map.put("page", Collections.singletonList(Long.toString(p.getPage())));
map.put("desc", Collections.singletonList(Boolean.toString(p.isDesc())));
map.put("limit", Collections.singletonList(Integer.toString(p.getLimit())));
if (p.getSortby() != null) {
map.put("sort", Collections.singletonList(p.getSortby()));
}
}
}
return map;
}Example 63
| Project: docker-client-master File: DefaultDockerClient.java View source code |
@Override
public void restartContainer(String containerId, int secondsToWaitBeforeRestart) throws DockerException, InterruptedException {
checkNotNull(containerId, "containerId");
checkNotNull(secondsToWaitBeforeRestart, "secondsToWait");
MultivaluedMap<String, String> queryParameters = new MultivaluedHashMap<>();
queryParameters.add("t", String.valueOf(secondsToWaitBeforeRestart));
containerAction(containerId, "restart", queryParameters);
}Example 64
| Project: olingo-odata4-master File: Services.java View source code |
private Response bodyPartRequest(final MimeBodyPart body, final Map<String, String> references) throws Exception {
@SuppressWarnings("unchecked") final Enumeration<Header> en = body.getAllHeaders();
Header header = en.nextElement();
final String request = header.getName() + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : "");
final Matcher matcher = REQUEST_PATTERN.matcher(request);
final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request);
final MultivaluedMap<String, String> headers = new MultivaluedHashMap<String, String>();
while (en.hasMoreElements()) {
header = en.nextElement();
headers.putSingle(header.getName(), header.getValue());
}
final Response res;
final String url;
final String method;
if (matcher.find()) {
url = matcher.group(2);
method = matcher.group(1);
} else if (matcherRef.find()) {
url = references.get(matcherRef.group(2)) + matcherRef.group(3);
method = matcherRef.group(1);
} else {
url = null;
method = null;
}
if (url == null) {
res = null;
} else {
final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null);
client.headers(headers);
if ("DELETE".equals(method)) {
res = client.delete();
} else {
final InputStream is = body.getDataHandler().getInputStream();
String content = IOUtils.toString(is);
IOUtils.closeQuietly(is);
final Matcher refs = REF_PATTERN.matcher(content);
while (refs.find()) {
content = content.replace(refs.group(1), references.get(refs.group(1)));
}
if ("PATCH".equals(method) || "MERGE".equals(method)) {
client.header("X-HTTP-METHOD", method);
res = client.invoke("POST", IOUtils.toInputStream(content));
} else {
res = client.invoke(method, IOUtils.toInputStream(content));
}
}
// When updating to CXF 3.0.1, uncomment the following line, see CXF-5865
// client.close();
}
return res;
}Example 65
| Project: clc-java-sdk-master File: BearerAuthenticationTest.java View source code |
private ClientRequestContext stubRequestContext() {
ClientRequestContext context = mock(ClientRequestContext.class);
when(context.getHeaders()).thenReturn(new MultivaluedHashMap<>());
return context;
}Example 66
| Project: droolsjbpm-integration-master File: CaseQueryResourceTest.java View source code |
@Before
public void init() {
when(httpHeaders.getRequestHeaders()).thenReturn(new MultivaluedHashMap<>());
caseQueryResource = new CaseQueryResource(runtimeDataService, kieServerRegistry);
}Example 67
| Project: lightfish-master File: MonitoringAdmin.java View source code |
private boolean changeMonitoringState(String state) {
authenticator.get().addAuthenticator(client, username, password);
MultivaluedMap formData = new MultivaluedHashMap();
for (String module : modules) {
formData.add(module, state);
}
return postForms(formData);
}Example 68
| Project: paymill-java-master File: JerseyClient.java View source code |
private static MultivaluedMap<String, String> convertMap(final ParameterMap<String, String> map) {
if (map == null) {
return null;
}
MultivaluedMap<String, String> params = new MultivaluedHashMap<String, String>();
params.putAll(map);
return params;
}Example 69
| Project: atsd-api-java-master File: TestUtil.java View source code |
public static MultivaluedMap<String, String> toMVM(String... tagNamesAndValues) {
return new MultivaluedHashMap<>(AtsdUtil.toMap(tagNamesAndValues));
}Example 70
| Project: keywhiz-master File: CookieRenewingFilterTest.java View source code |
@Before
public void setUp() {
CookieConfig cookieConfig = new CookieConfig();
cookieConfig.setName(SESSION_COOKIE);
filter = new CookieRenewingFilter(cookieConfig, authenticator, sessionLoginResource);
when(response.getHeaders()).thenReturn(new MultivaluedHashMap<>());
}Example 71
| Project: karate-master File: JerseyHttpClient.java View source code |
@Override
public Entity getEntity(MultiValuedMap fields, String mediaType) {
MultivaluedHashMap<String, Object> map = new MultivaluedHashMap<>();
for (Entry<String, List> entry : fields.entrySet()) {
map.put(entry.getKey(), entry.getValue());
}
return Entity.entity(map, mediaType);
}Example 72
| Project: GeoKnowGeneratorUI-master File: AuthorizedSessions.java View source code |
@GET
@Path("{sessionToken}")
public Response get(@PathParam("sessionToken") String sessionToken, @Context UriInfo uriInfo, @Context HttpHeaders headers) throws Exception {
MultivaluedMap<String, String> formParams = new MultivaluedHashMap<String, String>();
return post(sessionToken, uriInfo, formParams, headers);
}