Java Code Examples for javax.ws.rs.core.MultivaluedMap#add()

The following examples show how to use javax.ws.rs.core.MultivaluedMap#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestJaxrsProducerResponseMapper.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void mapResponse_withHeaders() {
  MultivaluedMap<String, Object> headers = new MultivaluedHashMap<>();
  headers.add("h", "v");

  new Expectations() {
    {
      jaxrsResponse.getStatusInfo();
      result = Status.OK;
      jaxrsResponse.getEntity();
      result = "result";
      jaxrsResponse.getHeaders();
      result = headers;
    }
  };
  Response response = mapper.mapResponse(null, jaxrsResponse);
  Assert.assertEquals(Status.OK, response.getStatus());
  Assert.assertEquals("result", response.getResult());
  Assert.assertEquals(1, response.getHeaders().getHeaderMap().size());
  Assert.assertThat(response.getHeaders().getHeader("h"), Matchers.contains("v"));
}
 
Example 2
Source File: JRestlessContainerResponseWriterTest.java    From jrestless with Apache License 2.0 6 votes vote down vote up
@Test
public void writeResponseStatusAndHeaders_ContextHeaderAndStatusGiven_ShouldUpdateResponseStatusAndHeaders() {
	MultivaluedMap<String, String> actualHeaders = new MultivaluedHashMap<>();
	actualHeaders.add("header0", "value0_0");
	actualHeaders.add("header0", "value0_1");
	actualHeaders.add("header1", "value1_0");
	MultivaluedMap<String, String> expectedHeaders = new MultivaluedHashMap<>();
	expectedHeaders.add("header0", "value0_0");
	expectedHeaders.add("header0", "value0_1");
	expectedHeaders.add("header1", "value1_0");

	ContainerResponse context = mock(ContainerResponse.class);
	when(context.getStatusInfo()).thenReturn(Status.CONFLICT);
	when(context.getStringHeaders()).thenReturn(actualHeaders);

	containerResponseWriter.writeResponseStatusAndHeaders(-1, context);

	assertEquals(Status.CONFLICT, response.getStatusType());
	assertEquals(expectedHeaders, response.getHeaders());
}
 
Example 3
Source File: DefaultUUIDModificationRequest.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public MultivaluedMap<String,String> toMap() {
    MultivaluedMap<String,String> p = new MultivaluedMapImpl<String,String>();
    p.putAll(super.toMap());
    if (this.events != null) {
        for (ModificationEvent e : events) {
            p.add("Events", e.toString());
        }
    }
    return p;
}
 
Example 4
Source File: GZIPWriterInterceptor.java    From wings with Apache License 2.0 5 votes vote down vote up
@Override
public void aroundWriteTo(WriterInterceptorContext context)
    throws IOException, WebApplicationException {

  boolean compress = false;
  String ae = request.getHeader("accept-encoding");
  if (ae != null && ae.indexOf("gzip") >= 0) {
    compress = true;
  }
  if(compress) {
    MultivaluedMap<String, Object> headers = context.getHeaders(); 
    for(Object type : headers.get("content-type")) {
      String ctype = type.toString();
      if(ctype.contains("zip") || 
          ctype.contains("compress") ||
          ctype.contains("image")) {
        compress = false;
        break;
      }
    }
    if(compress) {
      headers.add("Content-Encoding", "gzip");
      final OutputStream outputStream = context.getOutputStream();
      context.setOutputStream(new GZIPOutputStream(outputStream));
    }      
  }
  context.proceed();
}
 
Example 5
Source File: MetadataDiscoveryJerseyResourceIT.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = AtlasServiceException.class)
public void testSearchByDSLForUnknownType() throws Exception {
    String dslQuery = "from blah";
    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add("query", dslQuery);
    atlasClientV1.callAPIWithQueryParams(AtlasClient.API.SEARCH_DSL, queryParams);
}
 
Example 6
Source File: CORSFilter.java    From tool.accelerate.core with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext req, ContainerResponseContext res) throws IOException {
    MultivaluedMap<String, Object> headers = res.getHeaders();
    headers.add("Access-Control-Allow-Origin", "*");
    headers.add("Access-Control-Allow-Methods", "GET, POST");
    headers.add("Access-Control-Max-Age", "86400");
    headers.add("Access-Control-Allow-Credentials", "true");
    headers.add("Access-Control-Allow-Headers", "Content-Type");
}
 
Example 7
Source File: AssetMapUtilsTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testFilterAsset_AssetMapNoClassifier_AssetParamEmptyClassifier() {
  when(searchUtils.getFullAssetAttributeName(any(String.class))).thenReturn(CLASSIFIER_ATTRIBUTE_NAME);
  MultivaluedMap<String, String>  assetParams = new MultivaluedHashMap<>();
  assetParams.add(CLASSIFIER_ATTRIBUTE_NAME, "");

  assertTrue(underTest.filterAsset(assetMap, assetParams));
}
 
Example 8
Source File: SimpleRestClient.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void addAuthorizations(Builder request, String userId, MultivaluedMap<String, Object> myHeaders) throws Exception {
	logger.debug("Adding auth for user " + userId);

	String encodedBytes = Base64.encode(userId.getBytes("UTF-8"));
	request.header("Authorization", "Direct " + encodedBytes);
	myHeaders.add("Authorization", "Direct " + encodedBytes);
}
 
Example 9
Source File: CorsFilter.java    From Java-EE-8-and-Angular with MIT License 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext,
        ContainerResponseContext responseContext)
        throws IOException {
    MultivaluedMap<String, Object> headers = responseContext.getHeaders();
    headers.add("Access-Control-Allow-Origin", "*");
    headers.add("Access-Control-Allow-Credentials", "true");
    headers.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
}
 
Example 10
Source File: ApiOriginFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
    throws IOException {
    MultivaluedMap<String, Object> headers = responseContext.getHeaders();
    headers.add("Access-Control-Allow-Origin", "*");
    headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
    headers.add("Access-Control-Allow-Headers", "Content-Type");
}
 
Example 11
Source File: DashboardRESTTest.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAppHistoryMetrics(){
	WebResource webResource = resource();
	MultivaluedMap<String, String> map = new MultivaluedMapImpl();
	map.add("appId", TESTAPPID);
	ClientResponse response = webResource.path("/metrics/"+TESTSERVICEID+"/"+TESTAPPID).get(ClientResponse.class);
	assertEquals(response.getStatus(), STATUS200);
}
 
Example 12
Source File: AssetMapUtilsTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testFilterAsset_AssetMapNoClassifier_AssetParamNoClassifier() {
  when(searchUtils.getFullAssetAttributeName(any(String.class))).thenReturn(EXTENSION_ATTRIBUTE_NAME);
  MultivaluedMap<String, String>  assetParams = new MultivaluedHashMap<>();
  assetParams.add(EXTENSION_ATTRIBUTE_NAME, "jar");

  assertTrue(underTest.filterAsset(assetMap, assetParams));
}
 
Example 13
Source File: BulkFetchAndUpdate.java    From atlas with Apache License 2.0 5 votes vote down vote up
private List<AtlasClassificationDef> getAllClassificationsDefs() throws Exception {
    MultivaluedMap<String, String> searchParams = new MultivaluedMapImpl();
    searchParams.add(SearchFilter.PARAM_TYPE, "CLASSIFICATION");
    SearchFilter searchFilter = new SearchFilter(searchParams);

    AtlasTypesDef typesDef = atlasClientV2.getAllTypeDefs(searchFilter);
    displayCrLf("Found classifications: " + typesDef.getClassificationDefs().size());
    return typesDef.getClassificationDefs();
}
 
Example 14
Source File: EntityLineageJerseyResourceIT.java    From atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testInputLineageInfo() throws Exception {
    String tableId = atlasClientV1.getEntity(HIVE_TABLE_TYPE,
            AtlasClient.REFERENCEABLE_ATTRIBUTE_NAME, salesMonthlyTable).getId()._getId();

    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add(DIRECTION_PARAM, INPUT_DIRECTION);
    queryParams.add(DEPTH_PARAM, "5");
    ObjectNode response = atlasClientV1.callAPI(LINEAGE_V2_API, ObjectNode.class, queryParams, tableId);
    Assert.assertNotNull(response);
    System.out.println("input lineage info = " + response
    );

    AtlasLineageInfo inputLineageInfo = AtlasType.fromJson(response.toString(), AtlasLineageInfo.class);

    Map<String, AtlasEntityHeader> entities = inputLineageInfo.getGuidEntityMap();
    Assert.assertNotNull(entities);

    Set<AtlasLineageInfo.LineageRelation> relations = inputLineageInfo.getRelations();
    Assert.assertNotNull(relations);

    Assert.assertEquals(entities.size(), 6);
    Assert.assertEquals(relations.size(), 5);
    Assert.assertEquals(inputLineageInfo.getLineageDirection(), AtlasLineageInfo.LineageDirection.INPUT);
    Assert.assertEquals(inputLineageInfo.getLineageDepth(), 5);
    Assert.assertEquals(inputLineageInfo.getBaseEntityGuid(), tableId);
}
 
Example 15
Source File: TaxonomyInterpreter.java    From occurrence with Apache License 2.0 4 votes vote down vote up
public OccurrenceParseResult<NameUsageMatch> match(String kingdom, String phylum, String clazz, String order,
                                                   String family, String genus, String scientificName,
                                                   String authorship, String genericName, String specificEpithet,
                                                   String infraspecificEpithet, Rank rank) {

  String cleanGenus = ClassificationUtils.clean(genus);
  String cleanGenericName = ClassificationUtils.clean(genericName);
  String cleanSpecificEpithet = ClassificationUtils.cleanAuthor(specificEpithet);
  String cleanInfraspecificEpithet = ClassificationUtils.cleanAuthor(infraspecificEpithet);
  String cleanAuthorship = ClassificationUtils.cleanAuthor(authorship);

  String sciname = buildScientificName(scientificName, cleanAuthorship, cleanGenericName, cleanGenus,
                                             cleanSpecificEpithet, cleanInfraspecificEpithet);
  OccurrenceParseResult<NameUsageMatch> result;
  MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
  queryParams.add("kingdom", ClassificationUtils.clean(kingdom));
  queryParams.add("phylum",  ClassificationUtils.clean(phylum));
  queryParams.add("class",   ClassificationUtils.clean(clazz));
  queryParams.add("order",   ClassificationUtils.clean(order));
  queryParams.add("family",  ClassificationUtils.clean(family));
  queryParams.add("genus",  cleanGenus);

  queryParams.add("name",   sciname);
  if (rank != null) {
    queryParams.add("rank", rank.name());
  }

  LOG.debug("Attempt to match name [{}]", sciname);
  WebResource res = matchingWs.queryParams(queryParams);
  LOG.debug("WS call with: {}", res.getURI());
  try {
    NameUsageMatch lookup = MATCH_CACHE.get(res);
    result = OccurrenceParseResult.success(ParseResult.CONFIDENCE.DEFINITE, lookup);
    switch (lookup.getMatchType()) {
      case NONE:
        result = OccurrenceParseResult.fail(lookup, OccurrenceIssue.TAXON_MATCH_NONE);
        LOG.info("match for [{}] returned no match. Lookup note: [{}]", scientificName, lookup.getNote());
        break;
      case FUZZY:
        result.addIssue(OccurrenceIssue.TAXON_MATCH_FUZZY);
        LOG.debug("match for [{}] was fuzzy. Match note: [{}]", scientificName, lookup.getNote());
        break;
      case HIGHERRANK:
        result.addIssue(OccurrenceIssue.TAXON_MATCH_HIGHERRANK);
        LOG.debug("match for [{}] was to higher rank only. Match note: [{}]", scientificName, lookup.getNote());
        break;
    }
  } catch (Exception e) {
    // Log the error
    LOG.error("Failed WS call with: {}", res.getURI());
    result = OccurrenceParseResult.error(e);
  }

  return result;
}
 
Example 16
Source File: TypedefsJerseyResourceIT.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdate() throws Exception {
    String entityType = randomString();
    AtlasEntityDef typeDefinition =
            createClassTypeDef(entityType, ImmutableSet.<String>of(),
                    AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"));

    AtlasTypesDef atlasTypesDef = new AtlasTypesDef();
    atlasTypesDef.getEntityDefs().add(typeDefinition);

    AtlasTypesDef createdTypeDefs = clientV2.createAtlasTypeDefs(atlasTypesDef);
    assertNotNull(createdTypeDefs);
    assertEquals(createdTypeDefs.getEntityDefs().size(), atlasTypesDef.getEntityDefs().size());

    //Add attribute description
    typeDefinition = createClassTypeDef(typeDefinition.getName(),
            ImmutableSet.<String>of(),
            AtlasTypeUtil.createUniqueRequiredAttrDef("name", "string"),
            AtlasTypeUtil.createOptionalAttrDef("description", "string"));

    emptyTypeDefs(atlasTypesDef);

    atlasTypesDef.getEntityDefs().add(typeDefinition);

    AtlasTypesDef updatedTypeDefs = clientV2.updateAtlasTypeDefs(atlasTypesDef);
    assertNotNull(updatedTypeDefs);
    assertEquals(updatedTypeDefs.getEntityDefs().size(), atlasTypesDef.getEntityDefs().size());
    assertEquals(updatedTypeDefs.getEntityDefs().get(0).getName(), atlasTypesDef.getEntityDefs().get(0).getName());

    MultivaluedMap<String, String> filterParams = new MultivaluedMapImpl();
    filterParams.add(SearchFilter.PARAM_TYPE, "ENTITY");
    AtlasTypesDef allTypeDefs = clientV2.getAllTypeDefs(new SearchFilter(filterParams));
    assertNotNull(allTypeDefs);
    Boolean entityDefFound = false;
    for (AtlasEntityDef atlasEntityDef : allTypeDefs.getEntityDefs()){
        if (atlasEntityDef.getName().equals(typeDefinition.getName())) {
            assertEquals(atlasEntityDef.getAttributeDefs().size(), 2);
            entityDefFound = true;
            break;
        }
    }
    assertTrue(entityDefFound, "Required entityDef not found.");
}
 
Example 17
Source File: DockerClient.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public ClientResponse build(File dockerFolder, String tag, boolean noCache) throws DockerException {
	Preconditions.checkNotNull(dockerFolder, "Folder is null");
	Preconditions.checkArgument(dockerFolder.exists(), "Folder %s doesn't exist", dockerFolder);
	Preconditions.checkState(new File(dockerFolder, "Dockerfile").exists(), "Dockerfile doesn't exist in " + dockerFolder);

	//We need to use Jersey HttpClient here, since ApacheHttpClient4 will not add boundary filed to
	//Content-Type: multipart/form-data; boundary=Boundary_1_372491238_1372806136625

	MultivaluedMap<String, String> params = new MultivaluedMapImpl();
	params.add("t", tag);
	if (noCache) {
		params.add("nocache", "true");
	}

	// ARCHIVE TAR
	String archiveNameWithOutExtension = UUID.randomUUID().toString();

	File dockerFolderTar = null;

	try {
		File dockerFile = new File(dockerFolder, "Dockerfile");
		List<String> dockerFileContent = FileUtils.readLines(dockerFile);

		if (dockerFileContent.size() <= 0) {
			throw new DockerException(String.format("Dockerfile %s is empty", dockerFile));
		}

		List<File> filesToAdd = new ArrayList<File>();
		filesToAdd.add(dockerFile);

		for (String cmd : dockerFileContent) {
			if (StringUtils.startsWithIgnoreCase(cmd.trim(), "ADD")) {
				String addArgs[] = StringUtils.split(cmd, " \t");
				if (addArgs.length != 3) {
					throw new DockerException(String.format("Wrong format on line [%s]", cmd));
				}

				String resource = addArgs[1];
				
				if(isFileResource(resource)) {
					File src = new File(resource);
					if (!src.isAbsolute()) {
						src = new File(dockerFolder, resource).getCanonicalFile();
					} else {
						throw new DockerException(String.format("Source file %s must be relative to %s", src, dockerFolder));
					}

					if (!src.exists()) {
						throw new DockerException(String.format("Source file %s doesn't exist", src));
					}
					if (src.isDirectory()) {
						filesToAdd.addAll(FileUtils.listFiles(src, null, true));
					} else {
						filesToAdd.add(src);
					}
				} 
			}
		}

		dockerFolderTar = CompressArchiveUtil.archiveTARFiles(dockerFolder, filesToAdd, archiveNameWithOutExtension);

	} catch (IOException ex) {
		FileUtils.deleteQuietly(dockerFolderTar);
		throw new DockerException("Error occurred while preparing Docker context folder.", ex);
	}

	WebResource webResource = client.resource(restEndpointUrl + "/build").queryParams(params);

	try {
		LOGGER.trace("POST: {}", webResource);
		return webResource
				.type("application/tar")
				.accept(MediaType.TEXT_PLAIN)
				.post(ClientResponse.class, FileUtils.openInputStream(dockerFolderTar));
	} catch (UniformInterfaceException exception) {
		if (exception.getResponse().getStatus() == 500) {
			throw new DockerException("Server error", exception);
		} else {
			throw new DockerException(exception);
		}
	} catch (IOException e) {
		throw new DockerException(e);
	} finally {
		FileUtils.deleteQuietly(dockerFolderTar);
	}
}
 
Example 18
Source File: AtlasClientV2.java    From atlas with Apache License 2.0 4 votes vote down vote up
public AtlasSearchResult dslSearch(final String query) throws AtlasServiceException {
    MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
    queryParams.add(QUERY, query);

    return callAPI(API_V2.DSL_SEARCH, AtlasSearchResult.class, queryParams);
}
 
Example 19
Source File: ServerHeaderFilter.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
    final MultivaluedMap<String, Object> headers = responseContext.getHeaders();
    headers.add( "Server", "Quarkus");
    headers.add( "Date", date);
}
 
Example 20
Source File: ElastistorUtil.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public Object executeCommand(String command, MultivaluedMap<String, String> params, Object responeObj) throws Throwable {

            if (!initialized) {
                throw new IllegalStateException("Error : ElastiCenterClient is not initialized.");
            }

            if (command == null || command.trim().isEmpty()) {
                throw new InvalidParameterException("No command to execute.");
            }

            try {
                ClientConfig config = new DefaultClientConfig();
                Client client = Client.create(config);
                WebResource webResource = client.resource(UriBuilder.fromUri(restprotocol + elastiCenterAddress + restpath).build());

                MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
                queryParams.add(queryparamapikey, apiKey);
                queryParams.add(queryparamresponse, responseType);

                queryParams.add(queryparamcommand, command);

                if (null != params) {
                    for (String key : params.keySet()) {
                        queryParams.add(key, params.getFirst(key));
                    }
                }
                if (debug) {
                    System.out.println("Command Sent " + command + " : " + queryParams);
                }
                ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);

                if (response.getStatus() >= 300) {
                    if (debug)
                        System.out.println("ElastiCenter returned error code : " + response.getStatus());
                    if (401 == response.getStatus()) {
                        throw new InvalidCredentialsException("Please specify a valid API Key.");
                    } else if (431 == response.getStatus()) {
                        throw new InvalidParameterException(response.getHeaders().getFirst("X-Description"));
                    } else if (432 == response.getStatus()) {
                        throw new InvalidParameterException(command + " does not exist on the ElastiCenter server.  Please specify a valid command or contact your ElastiCenter Administrator.");
                    } else {
                        throw new ServiceUnavailableException("Internal Error. Please contact your ElastiCenter Administrator.");
                    }
                } else if (null != responeObj) {
                    String jsonResponse = response.getEntity(String.class);
                    if (debug) {
                        System.out.println("Command Response : " + jsonResponse);
                    }
                    Gson gson = new Gson();
                    return gson.fromJson(jsonResponse, responeObj.getClass());
                } else {
                    return "Success";
                }
            } catch (Throwable t) {
                throw t;
            }
        }