Java Examples for javax.ws.rs.HeaderParam

The following java examples will help you to understand the usage of javax.ws.rs.HeaderParam. These source code samples are taken from different open source projects.

Example 1
Project: XChange-master  File: BTCMarketsDigestTest.java View source code
@Test
public void shouldEncodeRestInvocation() throws Exception {
    // given
    String expected = "wPYiZy9kIfRsexepi81dvv/eHv8fiyWdAoRSlaZrE3D63GbK3VOPRExKe5alTcNoldn2xd+7RS2avbCInTltlA==";
    RestInvocation invocation = mock(RestInvocation.class);
    PowerMockito.when(invocation, "getParamValue", Mockito.eq(HeaderParam.class), Mockito.eq("timestamp")).thenReturn("nonce");
    PowerMockito.when(invocation, "getMethodPath").thenReturn("/path/to/method");
    PowerMockito.when(invocation, "getRequestBody").thenReturn("request body");
    // when
    String encoded = btcMarketsDigest.digestParams(invocation);
    // then
    assertThat(encoded).isEqualTo(expected);
}
Example 2
Project: javaone2015-cloudone-master  File: LaterResource.java View source code
@Path("all")
@POST
public String all(@HeaderParam("Content-Type") String contentType, @QueryParam("method") String methodName, @QueryParam("uri") String uri, @QueryParam("services") String services, @QueryParam("retention-count") @DefaultValue("-1") int retentionCount, InputStream is) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    if (is != null) {
        byte[] buff = new byte[64];
        int count = -1;
        try {
            while ((count = is.read(buff)) > 0) {
                baos.write(buff, 0, count);
            }
        } catch (IOException e) {
            throw new WebApplicationException(500);
        }
    }
    LaterService.getInstance().addAllItem(contentType, methodName, uri, services, retentionCount, baos.toByteArray());
    return null;
}
Example 3
Project: jive-sdk-java-jersey-master  File: FileStorageService.java View source code
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public ExStorageFileEntity upload(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorization, @PathParam("workspaceId") String workspaceId, @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileData, @FormDataParam("metadata") ExStorageFileEntity metadata) {
    String externalId = Long.toString(ExternalDocumentIDGenerator.getNextID());
    String externalVersionId = Long.toString(ExternalDocumentVersionIDGenerator.getNextID());
    Long fileSize = FileStorage.uploadFile(workspaceId, uploadedInputStream, fileData.getFileName(), externalId, externalVersionId);
    metadata.setExternalId(externalId);
    metadata.getVersion().setExternalId(externalVersionId);
    metadata.getVersion().setSize(fileSize);
    metadata = FileStorageResponseResourceWrapper.wrapWithResources(workspaceId, metadata);
    return metadata;
}
Example 4
Project: airship-master  File: CoordinatorSlotResource.java View source code
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response install(AssignmentRepresentation assignmentRepresentation, @DefaultValue("1") @QueryParam("limit") int limit, @Context UriInfo uriInfo, @HeaderParam(AIRSHIP_AGENTS_VERSION_HEADER) String expectedAgentsVersion) {
    Preconditions.checkNotNull(assignmentRepresentation, "assignmentRepresentation must not be null");
    Preconditions.checkArgument(limit > 0, "limit must be at least 1");
    Assignment assignment = assignmentRepresentation.toAssignment();
    // select the target agents
    Predicate<AgentStatus> agentFilter = AgentFilterBuilder.build(uriInfo, transform(coordinator.getAgents(), idGetter()), transform(coordinator.getAllSlotStatus(), uuidGetter()), false, repository);
    List<AgentStatus> agents = coordinator.getAgents(agentFilter);
    // verify the expected status of agents
    checkAgentsVersion(expectedAgentsVersion, agents);
    // install the software
    List<SlotStatus> slots = coordinator.install(agentFilter, limit, assignment);
    // calculate unique prefix size with the new slots included
    return Response.ok(transform(slots, fromSlotStatus(coordinator.getAllSlotStatus(), repository))).header(AIRSHIP_SLOTS_VERSION_HEADER, createSlotsVersion(slots)).build();
}
Example 5
Project: coprhd-controller-master  File: ConsistencyGroupService.java View source code
/**
     * This function handles Get request for a consistency group detail
     * 
     * @param openstackTenantId Openstack tenant id
     * @param consistencyGroupId Consistency group id
     * @param isV1Call openstack cinder V1 call
     * @param header HTTP header
     * @brief Get Consistency Group Info
     * @return Response
     */
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Path("/{consistencyGroup_id}")
@CheckPermission(roles = { Role.SYSTEM_MONITOR, Role.TENANT_ADMIN }, acls = { ACL.ANY })
public Response getCosistencyGroup(@PathParam("tenant_id") String openstackTenantId, @PathParam("consistencyGroup_id") String consistencyGroupId, @HeaderParam("X-Cinder-V1-Call") String isV1Call, @Context HttpHeaders header) {
    Project project = getCinderHelper().getProject(openstackTenantId, getUserFromContext());
    if (project == null) {
        String message = "Bad Request: Project with the OpenStack Tenant Id : " + openstackTenantId + " does not exist";
        _log.error(message);
        return CinderApiUtils.createErrorResponse(400, message);
    }
    final BlockConsistencyGroup blockConsistencyGroup = findConsistencyGroup(consistencyGroupId, openstackTenantId);
    if (blockConsistencyGroup == null) {
        return CinderApiUtils.createErrorResponse(404, "Invalid Request: No Such Consistency Group Found");
    } else if (!consistencyGroupId.equals(CinderApiUtils.splitString(blockConsistencyGroup.getId().toString(), ":", 3))) {
        _log.error("Bad Request : There is no consistency group with id {} , please retry with correct consistency group id", consistencyGroupId);
        return CinderApiUtils.createErrorResponse(400, "Bad Request : There is no consistency group exist, please retry with correct consistency group id");
    } else {
        ConsistencyGroupDetail response = getConsistencyGroupDetail(blockConsistencyGroup);
        return CinderApiUtils.getCinderResponse(response, header, true, CinderConstants.STATUS_OK);
    }
}
Example 6
Project: everrest-master  File: FieldInjectorImplTest.java View source code
@SuppressWarnings("unchecked")
private void mockParameterResolverFactory() {
    parameterResolverFactory = mock(ParameterResolverFactory.class);
    pathParameterResolver = mock(ParameterResolver.class);
    queryParameterResolver = mock(ParameterResolver.class);
    matrixParameterResolver = mock(ParameterResolver.class);
    cookieParameterResolver = mock(ParameterResolver.class);
    headerParameterResolver = mock(ParameterResolver.class);
    when(parameterResolverFactory.createParameterResolver(isA(PathParam.class))).thenReturn(pathParameterResolver);
    when(parameterResolverFactory.createParameterResolver(isA(QueryParam.class))).thenReturn(queryParameterResolver);
    when(parameterResolverFactory.createParameterResolver(isA(MatrixParam.class))).thenReturn(matrixParameterResolver);
    when(parameterResolverFactory.createParameterResolver(isA(CookieParam.class))).thenReturn(cookieParameterResolver);
    when(parameterResolverFactory.createParameterResolver(isA(HeaderParam.class))).thenReturn(headerParameterResolver);
}
Example 7
Project: gitlab-jira-integration-master  File: HookResource.java View source code
@POST
@Produces(MediaType.APPLICATION_JSON)
@Timed
public void hook(@Auth Principal principal, @HeaderParam(GITLAB_HEADER) String gitLabHeader, @Valid Event event) {
    new Thread(() -> {
        setThreadName(principal);
        metricRegistry.counter(principal.getName()).inc();
        log.info("Hook received > {}", event);
        switch(event.getType()) {
            case PUSH:
            case TAG_PUSH:
                service.performPushEvent(event);
                break;
        }
    }).start();
}
Example 8
Project: JaxRs2Retrofit-master  File: ParamConverterManager.java View source code
/**
	 * Returns an instance of this manager which is preconfigured with a number of converters,
	 * e.g. {@link javax.ws.rs.PathParam} to {@link retrofit.http.Path}.
	 */
public static ParamConverterManager getDefaultInstance() {
    ParamConverterManager manager = new ParamConverterManager();
    manager.registerConverter(ClassName.get(HeaderParam.class), new MappingConverter(ClassName.get(Header.class)));
    manager.registerConverter(ClassName.get(PathParam.class), new MappingConverter(ClassName.get(Path.class)));
    manager.registerConverter(ClassName.get(QueryParam.class), new MappingConverter(ClassName.get(Query.class)));
    manager.registerConverter(ClassName.get(Void.class), new MappingConverter(ClassName.get(Body.class)));
    return manager;
}
Example 9
Project: jersey-doc-generator-master  File: ParameterParser.java View source code
/**
	 * Parse a paramater with their jersey annotation
	 * 
	 * @param parameter The current parameter
	 * @param annotationList The associated annotation
	 * @return
	 */
public static ParameterContent parse(Class<?> parameter, Annotation[] annotationList) {
    ParameterContent pc = new ParameterContent();
    pc.setType(parameter.getName());
    for (Annotation annotation : annotationList) {
        // Jersey - @DefaultValue
        if (annotation instanceof DefaultValue) {
            DefaultValue dv = (DefaultValue) annotation;
            pc.setDefaultValue(dv.value());
        }
        // Jersey - @CookieParam
        if (annotation instanceof CookieParam) {
            CookieParam cp = (CookieParam) annotation;
            pc.setContext(cp.annotationType().getName());
            pc.setName(cp.value());
        }
        // Jersey - @FormParam
        if (annotation instanceof FormParam) {
            FormParam fp = (FormParam) annotation;
            pc.setContext(fp.annotationType().getName());
            pc.setName(fp.value());
        }
        // Jersey - @HeaderParam
        if (annotation instanceof HeaderParam) {
            HeaderParam hp = (HeaderParam) annotation;
            pc.setContext(hp.annotationType().getName());
            pc.setName(hp.value());
        }
        // Jersey - @MatrixParam
        if (annotation instanceof MatrixParam) {
            MatrixParam mp = (MatrixParam) annotation;
            pc.setContext(mp.annotationType().getName());
            pc.setName(mp.value());
        }
        // Jersey - @PathParam
        if (annotation instanceof PathParam) {
            PathParam pp = (PathParam) annotation;
            pc.setContext(pp.annotationType().getName());
            pc.setName(pp.value());
        }
        // Jersey - @QueryParam
        if (annotation instanceof QueryParam) {
            QueryParam qp = (QueryParam) annotation;
            pc.setContext(qp.annotationType().getName());
            pc.setName(qp.value());
        }
    }
    return pc;
}
Example 10
Project: bennu-master  File: ExternalApplicationResource.java View source code
@GET
@Path("/{app}/logo")
public Response logo(@PathParam("app") ExternalApplication app, @HeaderParam("If-None-Match") String ifNoneMatch) {
    if (app != null && app.getLogo() != null) {
        EntityTag etag = buildETag(app);
        if (etag.toString().equals(ifNoneMatch)) {
            return Response.notModified(etag).build();
        }
        return Response.ok(Base64.getDecoder().decode(app.getLogo()), "image/jpeg").tag(etag).build();
    } else {
        try (InputStream placeholder = getClass().getResourceAsStream("/noapplication.png")) {
            return Response.ok(ByteStreams.toByteArray(placeholder), "image/png").build();
        } catch (IOException e) {
            throw new WebApplicationException(Status.NOT_FOUND);
        }
    }
}
Example 11
Project: dropwizard-master  File: JerseyParameterNameProvider.java View source code
/**
     * Derives member's name and type from it's annotations
     */
public static Optional<String> getParameterNameFromAnnotations(Annotation[] memberAnnotations) {
    for (Annotation a : memberAnnotations) {
        if (a instanceof QueryParam) {
            return Optional.of("query param " + ((QueryParam) a).value());
        } else if (a instanceof PathParam) {
            return Optional.of("path param " + ((PathParam) a).value());
        } else if (a instanceof HeaderParam) {
            return Optional.of("header " + ((HeaderParam) a).value());
        } else if (a instanceof CookieParam) {
            return Optional.of("cookie " + ((CookieParam) a).value());
        } else if (a instanceof FormParam) {
            return Optional.of("form field " + ((FormParam) a).value());
        } else if (a instanceof Context) {
            return Optional.of("context");
        } else if (a instanceof MatrixParam) {
            return Optional.of("matrix param " + ((MatrixParam) a).value());
        }
    }
    return Optional.empty();
}
Example 12
Project: etk-component-master  File: BaseWadlGeneratorImpl.java View source code
/**
   * {@inheritDoc}
   */
public Param createParam(MethodParameter methodParameter) {
    Param wadlParemeter = null;
    Annotation annotation = methodParameter.getAnnotation();
    Class<?> annotationClass = methodParameter.getAnnotation().annotationType();
    // MethodParameterHelper#PARAMETER_ANNOTATIONS_MAP
    if (annotationClass == PathParam.class) {
        wadlParemeter = new Param();
        // attribute 'name'
        wadlParemeter.setName(((PathParam) annotation).value());
        // attribute 'style'
        wadlParemeter.setStyle(ParamStyle.TEMPLATE);
    } else if (annotationClass == MatrixParam.class) {
        wadlParemeter = new Param();
        wadlParemeter.setName(((MatrixParam) annotation).value());
        wadlParemeter.setStyle(ParamStyle.MATRIX);
    } else if (annotationClass == QueryParam.class) {
        wadlParemeter = new Param();
        wadlParemeter.setName(((QueryParam) annotation).value());
        wadlParemeter.setStyle(ParamStyle.QUERY);
    } else if (annotationClass == HeaderParam.class) {
        wadlParemeter = new Param();
        wadlParemeter.setName(((HeaderParam) annotation).value());
        wadlParemeter.setStyle(ParamStyle.HEADER);
    }
    if (wadlParemeter == null)
        // ignore this method parameter
        return null;
    // attribute 'repeat'
    Class<?> parameterClass = methodParameter.getParameterClass();
    if (parameterClass == List.class || parameterClass == Set.class || parameterClass == SortedSet.class)
        wadlParemeter.setRepeating(true);
    // attribute 'default'
    if (methodParameter.getDefaultValue() != null)
        wadlParemeter.setDefault(methodParameter.getDefaultValue());
    // attribute 'type'
    if (parameterClass.equals(Boolean.class) || parameterClass.equals(boolean.class))
        wadlParemeter.setType(new QName("http://www.w3.org/2001/XMLSchema", "boolean", "xs"));
    else if (parameterClass.equals(Byte.class) || parameterClass.equals(byte.class))
        wadlParemeter.setType(new QName("http://www.w3.org/2001/XMLSchema", "byte", "xs"));
    else if (parameterClass.equals(Short.class) || parameterClass.equals(short.class))
        wadlParemeter.setType(new QName("http://www.w3.org/2001/XMLSchema", "short", "xs"));
    else if (parameterClass.equals(Integer.class) || parameterClass.equals(int.class))
        wadlParemeter.setType(new QName("http://www.w3.org/2001/XMLSchema", "integer", "xs"));
    else if (parameterClass.equals(Long.class) || parameterClass.equals(long.class))
        wadlParemeter.setType(new QName("http://www.w3.org/2001/XMLSchema", "long", "xs"));
    else if (parameterClass.equals(Float.class) || parameterClass.equals(float.class))
        wadlParemeter.setType(new QName("http://www.w3.org/2001/XMLSchema", "float", "xs"));
    else if (parameterClass.equals(Double.class) || parameterClass.equals(double.class))
        wadlParemeter.setType(new QName("http://www.w3.org/2001/XMLSchema", "double", "xs"));
    else
        wadlParemeter.setType(new QName("http://www.w3.org/2001/XMLSchema", "string", "xs"));
    return wadlParemeter;
}
Example 13
Project: lemon-master  File: RestFilter.java View source code
public Map<String, String> getMetaData(Annotation[] annotations) {
    Map<String, String> metaData = new HashMap<String, String>();
    for (Annotation annotation : annotations) {
        String name = null;
        String type = null;
        String value = null;
        String defaultValue = null;
        if (annotation instanceof PathParam) {
            name = ((PathParam) annotation).value();
            type = "path";
            metaData.put("name", name);
            metaData.put("type", type);
        // value = this.getPathParam(request, name, method);
        } else if (annotation instanceof QueryParam) {
            name = ((QueryParam) annotation).value();
            type = "query";
            metaData.put("name", name);
            metaData.put("type", type);
        // value = request.getParameter(name);
        } else if (annotation instanceof FormParam) {
            name = ((FormParam) annotation).value();
            type = "form";
            metaData.put("name", name);
            metaData.put("type", type);
        // value = parameters.get(name);
        } else if (annotation instanceof HeaderParam) {
            name = ((HeaderParam) annotation).value();
            type = "header";
            metaData.put("name", name);
            metaData.put("type", type);
        // value = request.getHeader(name);
        } else if (annotation instanceof DefaultValue) {
            defaultValue = ((DefaultValue) annotation).value();
            metaData.put("defaultValue", defaultValue);
        }
    }
    return metaData;
}
Example 14
Project: osiris-master  File: FeatureResourceImpl.java View source code
@Override
@POST
@ValidationRequired(processor = RestViolationProcessor.class)
@ApiOperation(value = "Store a feature", httpMethod = "POST", response = FeatureDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Feature was stored", response = FeatureDTO.class), @ApiResponse(code = 400, message = "Latitude range out of index"), @ApiResponse(code = 400, message = "Longitude range out of index"), @ApiResponse(code = 400, message = "Geometry is invalid"), @ApiResponse(code = 400, message = "Mongo GeoJSON format is not correct"), @ApiResponse(code = 400, message = "Invalid input parameter (header)") })
public Response storeFeature(@Auth BasicAuth principal, @ApiParam(value = "Application identifier", required = true) @NotBlank @NotNull @HeaderParam("api_key") String appIdentifier, @ApiParam(required = true, value = "Feature") @Valid @NotNull FeatureDTO featureDTO) throws AssemblyException, MongoGeospatialException {
    validations.checkIsNotNullAndNotBlank(appIdentifier);
    validations.checkIsNotNull(featureDTO);
    Feature feature = featureManager.storeFeature(appIdentifier, featureAssembler.createDomainObject(featureDTO));
    FeatureDTO featureResponseDTO = featureAssembler.createDataTransferObject(feature);
    return Response.ok(featureResponseDTO).build();
}
Example 15
Project: Resteasy-master  File: SigningResource.java View source code
@DELETE
@Path("request-only")
public Response deleteRequestOnly(@Context HttpHeaders headers, @Context UriInfo uriInfo, @HeaderParam(DKIMSignature.DKIM_SIGNATURE) DKIMSignature signature) {
    Assert.assertNotNull(signature);
    Verification verification = new Verification(keys.getPublic());
    verification.setBodyHashRequired(false);
    verification.getRequiredAttributes().put("method", "GET");
    verification.getRequiredAttributes().put("uri", uriInfo.getPath());
    try {
        verification.verify(signature, headers.getRequestHeaders(), null, keys.getPublic());
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    }
    String token = signature.getAttributes().get("token");
    signature = new DKIMSignature();
    signature.setDomain("samplezone.org");
    signature.setSelector("test");
    signature.setPrivateKey(keys.getPrivate());
    signature.setBodyHashRequired(false);
    signature.getAttributes().put("token", token);
    return Response.ok().header(DKIMSignature.DKIM_SIGNATURE, signature).build();
}
Example 16
Project: swiftproxy-master  File: ContainerResource.java View source code
@PUT
public Response putContainer(@NotNull @PathParam("container") String container, @HeaderParam("X-Auth-Token") String authToken, @HeaderParam("X-Container-Read") String readACL, @HeaderParam("X-Container-write") String writeACL, @HeaderParam("X-Container-Sync-To") String syncTo, @HeaderParam("X-Container-Sync-Key") String syncKey, @HeaderParam("X-Versions-Location") String versionsLocation, @HeaderParam(HttpHeaders.CONTENT_TYPE) String contentType, @HeaderParam("X-Detect-Content-Type") boolean detectContentType, @HeaderParam(HttpHeaders.IF_NONE_MATCH) String ifNoneMatch) {
    Response.Status status;
    BlobStore store = getBlobStore(authToken).get(container);
    if (store.containerExists(container)) {
        status = Response.Status.ACCEPTED;
    } else {
        createContainer(authToken, container);
        status = Response.Status.CREATED;
    }
    return Response.status(status).build();
}
Example 17
Project: web-framework-master  File: JerseyParameterNameProvider.java View source code
/**
     * Derives member's name and type from it's annotations
     */
public static Optional<String> getParameterNameFromAnnotations(Annotation[] memberAnnotations) {
    for (Annotation a : memberAnnotations) {
        if (a instanceof QueryParam) {
            return Optional.of("query param " + ((QueryParam) a).value());
        } else if (a instanceof PathParam) {
            return Optional.of("path param " + ((PathParam) a).value());
        } else if (a instanceof HeaderParam) {
            return Optional.of("header " + ((HeaderParam) a).value());
        } else if (a instanceof CookieParam) {
            return Optional.of("cookie " + ((CookieParam) a).value());
        } else if (a instanceof FormParam) {
            return Optional.of("form field " + ((FormParam) a).value());
        } else if (a instanceof Context) {
            return Optional.of("context");
        } else if (a instanceof MatrixParam) {
            return Optional.of("matrix param " + ((MatrixParam) a).value());
        }
    }
    return Optional.empty();
}
Example 18
Project: archistar-core-master  File: FakeRoot.java View source code
@GET
@Produces("application/xml")
public String getAll(@QueryParam("delimiter") String delim, @QueryParam("prefix") String prefix, @QueryParam("max-keys") int maxKeysInt, @HeaderParam("X-Bucket") String bucket) throws ReconstructionException {
    if (bucket.isEmpty()) {
        /* list all buckets */
        return builder.stringFromDoc(builder.listBuckets(this.buckets));
    } else if (!this.buckets.containsKey(bucket)) {
        return bucketNotFound(bucket);
    } else {
        /* return content of this bucket */
        String tmp = this.buckets.get(bucket).getAll(bucket, delim, prefix, maxKeysInt);
        return tmp;
    }
}
Example 19
Project: carbon-identity-master  File: UserResource.java View source code
@GET
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(@PathParam(SCIMConstants.CommonSchemaConstants.ID) String id, @HeaderParam(SCIMConstants.ACCEPT_HEADER) String format, @HeaderParam(SCIMConstants.AUTHENTICATION_TYPE_HEADER) String authMechanism, @HeaderParam(SCIMConstants.AUTHORIZATION_HEADER) String authorization) {
    Encoder encoder = null;
    try {
        IdentitySCIMManager identitySCIMManager = IdentitySCIMManager.getInstance();
        // defaults to application/json.
        format = identifyOutputFormat(format);
        // obtain the encoder at this layer in case exceptions needs to be encoded.
        encoder = identitySCIMManager.getEncoder(SCIMConstants.identifyFormat(format));
        // obtain the user store manager
        UserManager userManager = IdentitySCIMManager.getInstance().getUserManager(authorization);
        // create charon-SCIM user endpoint and hand-over the request.
        UserResourceEndpoint userResourceEndpoint = new UserResourceEndpoint();
        SCIMResponse scimResponse = userResourceEndpoint.get(id, format, userManager);
        // appropriately.
        return new JAXRSResponseBuilder().buildResponse(scimResponse);
    } catch (CharonException e) {
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage(), e);
        }
        if (e.getCode() == -1) {
            e.setCode(ResponseCodeConstants.CODE_INTERNAL_SERVER_ERROR);
        }
        return new JAXRSResponseBuilder().buildResponse(AbstractResourceEndpoint.encodeSCIMException(encoder, e));
    } catch (FormatNotSupportedException e) {
        return new JAXRSResponseBuilder().buildResponse(AbstractResourceEndpoint.encodeSCIMException(encoder, e));
    }
}
Example 20
Project: carbon-registry-master  File: Tags.java View source code
/**
     * This method tags associated with the given resource
     *
     * @param resourcePath resource path
     * @param start        starting page number
     * @param size         number of tags to be fetched
     * @return JSON tag model eg: {"tags":[<array of tag names]}
     */
@GET
@Produces("application/json")
@ApiOperation(value = "Get all tags on a resource", httpMethod = "GET", notes = "Fetch all tags on a resource", response = TagModel.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Found the tags and returned in body"), @ApiResponse(code = 401, message = "Invalid credentials provided"), @ApiResponse(code = 404, message = "Given specific resource not found"), @ApiResponse(code = 500, message = "Internal server error occurred") })
public Response getTags(@QueryParam("path") String resourcePath, @QueryParam("start") int start, @QueryParam("size") int size, @HeaderParam("X-JWT-Assertion") String JWTToken) {
    RestAPIAuthContext authContext = RestAPISecurityUtils.getAuthContext(PrivilegedCarbonContext.getThreadLocalCarbonContext(), JWTToken);
    if (!authContext.isAuthorized()) {
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
    if (resourcePath == null || "".equals(resourcePath)) {
        //Return tagsCloud, therefore no need pagination.
        return getAllTags();
    }
    org.wso2.carbon.registry.core.Tag[] tags = new org.wso2.carbon.registry.core.Tag[0];
    try {
        Registry registry = getUserRegistry(authContext.getUserName(), authContext.getTenantId());
        if (!registry.resourceExists(resourcePath)) {
            return Response.status(Response.Status.NOT_FOUND).entity(RestAPIConstants.RESOURCE_NOT_FOUND).build();
        }
        tags = registry.getTags(resourcePath);
    } catch (RegistryException e) {
        log.error("Failed to get tags on resource " + resourcePath, e);
        Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
    }
    //Need paginate, because it return tags of a resource
    return getPaginatedResults(tags, start, size, "", "");
}
Example 21
Project: datalifecycle-master  File: PipesAdmin.java View source code
/**
     * This method return an RdfViewable, this is an RDF serviceUri with
     * associated presentational information.
     */
@GET
public RdfViewable serviceEntry(@Context final UriInfo uriInfo, @QueryParam("url") final UriRef url, @HeaderParam("user-agent") String userAgent) throws Exception {
    //this maks sure we are nt invoked with a trailing slash which would affect
    //relative resolution of links (e.g. css)
    TrailingSlash.enforcePresent(uriInfo);
    final String resourcePath = uriInfo.getAbsolutePath().toString();
    if (url != null) {
        String query = url.toString();
        log.info(query);
    }
    //The URI at which this service was accessed, this will be the 
    //central serviceUri in the response
    final UriRef serviceUri = new UriRef(resourcePath);
    //the in memory graph to which the triples for the response are added
    final MGraph responseGraph = new IndexedMGraph();
    Lock rl = getDlcGraph().getLock().readLock();
    rl.lock();
    try {
        responseGraph.addAll(getDlcGraph());
        //Add the size info of the graphs of all the datasets
        addGraphsSize(responseGraph);
    } finally {
        rl.unlock();
    }
    //This GraphNode represents the service within our result graph
    final GraphNode node = new GraphNode(serviceUri, responseGraph);
    node.addProperty(DLC.graph, DlcGraphProvider.DATA_LIFECYCLE_GRAPH_REFERENCE);
    //What we return is the GraphNode to the template with the same path and name 
    return new RdfViewable("PipesAdmin", node, PipesAdmin.class);
}
Example 22
Project: dropwizard-jedis-master  File: TeamsServiceResource.java View source code
@GET
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_HTML })
public Object getAllTeams(@HeaderParam("Accept") String mediaType) {
    List<String> teams = new ArrayList<String>();
    Jedis jedis = pool.getResource();
    try {
        List<String> teamsKeys = new ArrayList<String>(jedis.keys(KEY_SEARCH));
        for (String key : teamsKeys) {
            teams.add(nameFromTeamKey(key));
        }
        pool.returnResource(jedis);
    } catch (Exception e) {
        pool.returnBrokenResource(jedis);
        throw e;
    }
    if (mediaType.equalsIgnoreCase(MediaType.APPLICATION_JSON)) {
        return teams;
    }
    return new AllTeamsView(teams);
}
Example 23
Project: jersey-1.x-old-master  File: HeaderParamAsStringTest.java View source code
@GET
@Produces("application/list")
public String doGet(@HeaderParam("args") List args) {
    assertEquals(String.class, args.get(0).getClass());
    assertEquals("a", args.get(0));
    assertEquals(String.class, args.get(1).getClass());
    assertEquals("b", args.get(1));
    assertEquals(String.class, args.get(2).getClass());
    assertEquals("c", args.get(2));
    return "content";
}
Example 24
Project: jersey-old-master  File: HeaderParamAsStringTest.java View source code
@GET
@Produces("application/list")
public String doGet(@HeaderParam("args") List args) {
    assertEquals(String.class, args.get(0).getClass());
    assertEquals("a", args.get(0));
    assertEquals(String.class, args.get(1).getClass());
    assertEquals("b", args.get(1));
    assertEquals(String.class, args.get(2).getClass());
    assertEquals("c", args.get(2));
    return "content";
}
Example 25
Project: killbill-master  File: TransactionResource.java View source code
@TimedResource
@POST
@Path("/{transactionId:" + UUID_PATTERN + "}/")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Mark a pending payment transaction as succeeded or failed")
@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid paymentId supplied"), @ApiResponse(code = 404, message = "Account or Payment not found") })
public Response notifyStateChanged(final PaymentTransactionJson json, @PathParam("transactionId") final String transactionIdStr, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final UriInfo uriInfo, @javax.ws.rs.core.Context final HttpServletRequest request) throws PaymentApiException, AccountApiException {
    verifyNonNullOrEmpty(json, "PaymentTransactionJson body should be specified");
    verifyNonNullOrEmpty(json.getPaymentId(), "PaymentTransactionJson paymentId needs to be set", json.getStatus(), "PaymentTransactionJson status needs to be set");
    final CallContext callContext = context.createContext(createdBy, reason, comment, request);
    final UUID paymentId = UUID.fromString(json.getPaymentId());
    final Payment payment = paymentApi.getPayment(paymentId, false, false, ImmutableList.<PluginProperty>of(), callContext);
    final Account account = accountUserApi.getAccountById(payment.getAccountId(), callContext);
    final boolean success = TransactionStatus.SUCCESS.name().equals(json.getStatus());
    final Payment result = paymentApi.notifyPendingTransactionOfStateChanged(account, UUID.fromString(transactionIdStr), success, callContext);
    return uriBuilder.buildResponse(uriInfo, PaymentResource.class, "getPayment", result.getId(), request);
}
Example 26
Project: NetLicensingClient-java-master  File: SecurityTest.java View source code
@Path("get-auth-header")
@GET
public Response getAuthHeader(@HeaderParam("authorization") final String authorization) {
    final Netlicensing netlicensing = objectFactory.createNetlicensing();
    netlicensing.setInfos(objectFactory.createNetlicensingInfos());
    final Info info = objectFactory.createInfo();
    info.setValue(authorization);
    netlicensing.getInfos().getInfo().add(info);
    return Response.ok(netlicensing).build();
}
Example 27
Project: rest-client-tools-master  File: ClientMarshallerFactory.java View source code
public static Marshaller createMarshaller(Class<?> declaring, Class<?> type, Annotation[] annotations, Type genericType, AccessibleObject target, MediaType defaultConsumes, boolean ignoreBody) {
    Marshaller marshaller = null;
    QueryParam query;
    HeaderParam header;
    MatrixParam matrix;
    PathParam uriParam;
    CookieParam cookie;
    FormParam formParam;
    if ((query = FindAnnotation.findAnnotation(annotations, QueryParam.class)) != null) {
        marshaller = new QueryParamMarshaller(query.value());
    } else if ((header = FindAnnotation.findAnnotation(annotations, HeaderParam.class)) != null) {
        marshaller = new HeaderParamMarshaller(header.value());
    } else if ((cookie = FindAnnotation.findAnnotation(annotations, CookieParam.class)) != null) {
        marshaller = new CookieParamMarshaller(cookie.value());
    } else if ((uriParam = FindAnnotation.findAnnotation(annotations, PathParam.class)) != null) {
        marshaller = new PathParamMarshaller(uriParam.value());
    } else if ((matrix = FindAnnotation.findAnnotation(annotations, MatrixParam.class)) != null) {
        marshaller = new MatrixParamMarshaller(matrix.value());
    } else if ((formParam = FindAnnotation.findAnnotation(annotations, FormParam.class)) != null) {
        marshaller = new FormParamMarshaller(formParam.value());
    } else if ((FindAnnotation.findAnnotation(annotations, Context.class)) != null) {
        marshaller = new NOOPMarshaller();
    } else if (type.equals(Cookie.class)) {
        marshaller = new CookieParamMarshaller(null);
    } else if (!ignoreBody) {
        MediaType mediaType = MediaTypeHelper.getConsumes(declaring, target);
        if (mediaType == null)
            mediaType = defaultConsumes;
        if (mediaType == null) {
            throw new RuntimeException("You must define a @Consumes type on your client method or interface, or supply a default");
        }
        marshaller = new MessageBodyParameterMarshaller(mediaType, type, genericType, annotations);
    }
    return marshaller;
}
Example 28
Project: RRA-master  File: JaxRsControllerImpl.java View source code
@POST
@Path("/agent")
public Response userAgentMethod(String requestEntity, @HeaderParam("user-agent") String userAgentRequest) {
    System.out.println("isChrome " + getClientProperty().isChrome(httpHeader));
    System.out.println("isFirefox " + getClientProperty().isFirefox(httpHeader));
    System.out.println("isTablet " + getClientProperty().isTablet(httpHeader));
    System.out.println("isMobile " + getClientProperty().isMobile(httpHeader));
    System.out.println("isWebKit " + getClientProperty().isWebKit(httpHeader));
    return Response.status(200).entity(userAgentRequest).build();
}
Example 29
Project: schema-repo-master  File: RESTRepository.java View source code
/**
   * Returns all schemas in the given subject, serialized with
   * {@link org.schemarepo.RepositoryUtil#schemasToString(Iterable)}
   *
   * @param subject
   *          The name of the subject
   * @return all schemas in the subject. Return a 404 Not Found if there is no such subject
   */
@GET
@Path("{subject}/all")
public Response allSchemaEntries(@HeaderParam("Accept") String mediaType, @PathParam("subject") String subject) {
    Subject s = repo.lookup(subject);
    if (null == s) {
        throw new NotFoundException(MessageStrings.SUBJECT_DOES_NOT_EXIST_ERROR);
    }
    Renderer renderer = getRenderer(mediaType);
    return Response.ok(renderer.renderSchemas(s.allEntries()), renderer.getMediaType()).build();
}
Example 30
Project: sislegis-app-master  File: ProposicaoEndpoint.java View source code
@POST
@Path("/follow/{id:[0-9]+}")
public Response follow(@PathParam("id") Long id, @HeaderParam("Authorization") String authorization) {
    try {
        Usuario user = controleUsuarioAutenticado.carregaUsuarioAutenticado(authorization);
        proposicaoService.followProposicao(user, id);
        return Response.noContent().build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}
Example 31
Project: UniversalCustomSteps-master  File: Users.java View source code
/**
	 * Logs a user in
	 * @param user data comes from POST request body
	 * @param userAgent
	 * @return a response with a {@link Session} object
	 * @throws Exception
	 */
@POST
@Path("/login")
public synchronized Response login(User user, @HeaderParam("user-agent") String userAgent) throws Exception {
    if (user == null)
        throw new ApiException(Constants.Strings.MISSING_CONTENT_BODY, Status.NOT_ACCEPTABLE.getStatusCode());
    user.validate(new Validation(true, true, false));
    UserPassword savedUserPassword = UserPassword.fromUsername(user.getUsername());
    UserPassword originalUserPassword = new UserPassword(user.getPassword().getBytes(), savedUserPassword.salt);
    if (!savedUserPassword.equals(originalUserPassword))
        throw new ApiException(Constants.Strings.INVALID_CREDENTIALS, Status.FORBIDDEN.getStatusCode());
    Session session = new Session(savedUserPassword.userUuid, userAgent);
    session.save();
    return Response.ok(session).build();
}
Example 32
Project: airlift-master  File: MBeanServerResource.java View source code
@POST
@Path("{method}")
public Response invoke(@PathParam("method") String method, InputStream in, @HeaderParam("Authorization") String authHeader) throws Exception {
    if (credentials != null) {
        if (!credentials.authenticate(HttpMBeanServerCredentials.fromBasicAuthHeader(authHeader))) {
            return Response.status(Status.UNAUTHORIZED).entity(createExceptionResponse(new SecurityException("Invalid credentials"))).build();
        }
    }
    if (method == null) {
        return Response.status(Status.BAD_REQUEST).entity(createExceptionResponse(new NullPointerException("method is null"))).build();
    }
    Object[] args;
    try {
        args = (Object[]) new ObjectInputStream(in).readObject();
    } catch (Exception e) {
        return Response.status(Status.BAD_REQUEST).entity(createExceptionResponse(new IllegalArgumentException("Request does not contain a serialized Object[]"))).build();
    }
    try {
        Object result = null;
        if ("getMBeanInfo".equals(method)) {
            result = mbeanServer.getMBeanInfo((ObjectName) args[0]);
        } else if ("queryMBeans".equals(method)) {
            result = mbeanServer.queryMBeans((ObjectName) args[0], (QueryExp) args[1]);
        } else if ("queryNames".equals(method)) {
            result = mbeanServer.queryNames((ObjectName) args[0], (QueryExp) args[1]);
        } else if ("getAttribute".equals(method)) {
            result = mbeanServer.getAttribute((ObjectName) args[0], (String) args[1]);
        } else if ("getAttributes".equals(method)) {
            result = mbeanServer.getAttributes((ObjectName) args[0], (String[]) args[1]);
        } else if ("setAttribute".equals(method)) {
            mbeanServer.setAttribute((ObjectName) args[0], (Attribute) args[1]);
        } else if ("setAttributes".equals(method)) {
            result = mbeanServer.setAttributes((ObjectName) args[0], (AttributeList) args[1]);
        } else if ("invoke".equals(method)) {
            result = mbeanServer.invoke((ObjectName) args[0], (String) args[1], (Object[]) args[2], (String[]) args[3]);
        } else if ("getMBeanCount".equals(method)) {
            result = mbeanServer.getMBeanCount();
        } else if ("isRegistered".equals(method)) {
            result = mbeanServer.isRegistered((ObjectName) args[0]);
        } else if ("getObjectInstance".equals(method)) {
            result = mbeanServer.getObjectInstance((ObjectName) args[0]);
        } else if ("getDefaultDomain".equals(method)) {
            result = mbeanServer.getDefaultDomain();
        } else if ("getDomains".equals(method)) {
            result = mbeanServer.getDomains();
        } else if ("isInstanceOf".equals(method)) {
            result = mbeanServer.isInstanceOf((ObjectName) args[0], (String) args[1]);
        } else {
            return Response.status(Status.BAD_REQUEST).entity(createExceptionResponse(new IllegalArgumentException("Unknown method " + method))).build();
        }
        return Response.ok(createSuccessResponse(result)).build();
    } catch (Exception e) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(createExceptionResponse(e)).build();
    } catch (Error e) {
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(createExceptionResponse(new JMXServerErrorException("Internal error", e))).build();
    }
}
Example 33
Project: apis-master  File: RevokeResource.java View source code
@POST
public Response revokeAccessToken(@HeaderParam("Authorization") String authorization, final MultivaluedMap<String, String> formParameters) {
    String accessToken;
    Client client;
    AccessTokenRequest accessTokenRequest = AccessTokenRequest.fromMultiValuedFormParameters(formParameters);
    BasicAuthCredentials credentials = getClientCredentials(authorization, accessTokenRequest);
    try {
        client = validateClient(credentials);
        List<String> params = formParameters.get("token");
        accessToken = CollectionUtils.isEmpty(params) ? null : params.get(0);
    } catch (ValidationResponseException e) {
        ValidationResponse validationResponse = e.v;
        return Response.status(Status.BAD_REQUEST).entity(new ErrorResponse(validationResponse.getValue(), validationResponse.getDescription())).build();
    }
    AccessToken token = accessTokenRepository.findByTokenAndClient(accessToken, client);
    if (token == null) {
        LOG.info("Access token {} not found for client '{}'. Will return OK however.", accessToken, client.getClientId());
        return Response.ok().build();
    }
    accessTokenRepository.delete(token);
    return Response.ok().build();
}
Example 34
Project: astroboa-master  File: RepositoryLocator.java View source code
@Path("{repositoryId}")
public ResourceLocator connectToAstroboaRepository(@HeaderParam("Authorization") String authorization, @PathParam("repositoryId") String repositoryId, @Context ServletContext servletContext) {
    if (StringUtils.isBlank(repositoryId)) {
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }
    try {
        AstroboaClient astroboaClient = null;
        long start = System.currentTimeMillis();
        if (authorization != null) {
            String cacheKey = authorization + repositoryId;
            astroboaClient = AstroboaClientCache.Instance.get(cacheKey);
            if (astroboaClient == null) {
                String encodedUsernamePass = authorization.substring(5);
                String usernamePass = Base64.base64Decode(encodedUsernamePass);
                String[] usernamePassSplitted = usernamePass.split(":");
                if (usernamePassSplitted.length == 2) {
                    astroboaClient = new AstroboaClient(AstroboaClient.INTERNAL_CONNECTION);
                    AstroboaCredentials credentials = new AstroboaCredentials(usernamePassSplitted[0], usernamePassSplitted[1]);
                    astroboaClient.login(repositoryId, credentials);
                    astroboaClient = AstroboaClientCache.Instance.cache(astroboaClient, cacheKey);
                } else {
                    logger.error("provided authorization in header (BASIC AUTH) cannot be decoded to username and password. Encoded Authorization String found in header is: " + authorization);
                    throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED);
                }
            }
        } else // login as anonymous
        {
            final String anonymousCacheKey = repositoryId + IdentityPrincipal.ANONYMOUS;
            astroboaClient = AstroboaClientCache.Instance.get(anonymousCacheKey);
            if (astroboaClient == null) {
                astroboaClient = new AstroboaClient(AstroboaClient.INTERNAL_CONNECTION);
                String permanentKey = retrievePermanentKeyForAnonymousUser(repositoryId, servletContext);
                astroboaClient.loginAsAnonymous(repositoryId, permanentKey);
                astroboaClient = AstroboaClientCache.Instance.cache(astroboaClient, anonymousCacheKey);
            }
        }
        logger.debug("Retrieve/Create astroboa repository client {} in  {}", System.identityHashCode(astroboaClient), DurationFormatUtils.formatDurationHMS(System.currentTimeMillis() - start));
        return new ResourceLocator(astroboaClient);
    } catch (CmsInvalidPasswordException e) {
        logger.error("Login to Astroboa Repository was not successfull");
        throw new WebApplicationException(HttpURLConnection.HTTP_UNAUTHORIZED);
    } catch (Exception e) {
        logger.error("A problem occured while connecting repository client to Astroboa Repository", e);
        throw new WebApplicationException(HttpURLConnection.HTTP_NOT_FOUND);
    }
}
Example 35
Project: cloud-master  File: TokensResource.java View source code
@GET
@Produces({ JSON })
public Response getTokenInfo(@HeaderParam("x-auth-token") String authToken, @HeaderParam("x-subject-token") String subjectToken) throws CloudException {
    if (Strings.isNullOrEmpty(authToken) || Strings.isNullOrEmpty(subjectToken)) {
        throw new WebApplicationException(Status.BAD_REQUEST);
    }
    if (!authToken.equals(subjectToken)) {
        // For now, we only allow same-token auth
        throw new UnsupportedOperationException();
    }
    AuthenticatedUser auth = loginService.authenticate(authToken);
    if (auth == null) {
        throw new WebApplicationException(Status.UNAUTHORIZED);
    }
    TokenInfo subject = tokenService.findValidToken(subjectToken);
    if (subject == null) {
        throw new WebApplicationException(Status.NOT_FOUND);
    }
    ResponseBuilder response = Response.ok();
    response.entity(buildTokenModel(subject));
    return response.build();
}
Example 36
Project: cloud-odata-java-master  File: ODataSubLocator.java View source code
@POST
public Response handlePost(@HeaderParam("X-HTTP-Method") final String xHttpMethod) throws ODataException {
    Response response;
    if (xHttpMethod == null) {
        response = handle(ODataHttpMethod.POST);
    } else {
        /* tunneling */
        if ("MERGE".equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.MERGE);
        } else if ("PATCH".equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.PATCH);
        } else if (HttpMethod.DELETE.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.DELETE);
        } else if (HttpMethod.PUT.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.PUT);
        } else if (HttpMethod.GET.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.GET);
        } else if (HttpMethod.POST.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.POST);
        } else if (HttpMethod.HEAD.equals(xHttpMethod)) {
            response = handleHead();
        } else if (HttpMethod.OPTIONS.equals(xHttpMethod)) {
            response = handleOptions();
        } else {
            response = returnNotImplementedResponse(ODataNotImplementedException.TUNNELING);
        }
    }
    return response;
}
Example 37
Project: cxf-master  File: JAXRSClientFactoryBean.java View source code
@SuppressWarnings("unchecked")
@Override
public <T> ParamConverter<T> getConverter(Class<T> cls, Type t, Annotation[] anns) {
    if (cls == String.class && AnnotationUtils.getAnnotation(anns, HeaderParam.class) == null && AnnotationUtils.getAnnotation(anns, CookieParam.class) == null) {
        return (ParamConverter<T>) new UrlEncodingParamConverter(encodeClientParametersList);
    } else {
        return null;
    }
}
Example 38
Project: eureka-master  File: InstanceResource.java View source code
/**
     * A put request for renewing lease from a client instance.
     *
     * @param isReplication
     *            a header parameter containing information whether this is
     *            replicated from other nodes.
     * @param overriddenStatus
     *            overridden status if any.
     * @param status
     *            the {@link InstanceStatus} of the instance.
     * @param lastDirtyTimestamp
     *            last timestamp when this instance information was updated.
     * @return response indicating whether the operation was a success or
     *         failure.
     */
@PUT
public Response renewLease(@HeaderParam(PeerEurekaNode.HEADER_REPLICATION) String isReplication, @QueryParam("overriddenstatus") String overriddenStatus, @QueryParam("status") String status, @QueryParam("lastDirtyTimestamp") String lastDirtyTimestamp) {
    boolean isFromReplicaNode = "true".equals(isReplication);
    boolean isSuccess = registry.renew(app.getName(), id, isFromReplicaNode);
    // Not found in the registry, immediately ask for a register
    if (!isSuccess) {
        logger.warn("Not Found (Renew): {} - {}", app.getName(), id);
        return Response.status(Status.NOT_FOUND).build();
    }
    // Check if we need to sync based on dirty time stamp, the client
    // instance might have changed some value
    Response response = null;
    if (lastDirtyTimestamp != null && serverConfig.shouldSyncWhenTimestampDiffers()) {
        response = this.validateDirtyTimestamp(Long.valueOf(lastDirtyTimestamp), isFromReplicaNode);
        // Store the overridden status since the validation found out the node that replicates wins
        if (response.getStatus() == Response.Status.NOT_FOUND.getStatusCode() && (overriddenStatus != null) && !(InstanceStatus.UNKNOWN.name().equals(overriddenStatus)) && isFromReplicaNode) {
            registry.storeOverriddenStatusIfRequired(app.getAppName(), id, InstanceStatus.valueOf(overriddenStatus));
        }
    } else {
        response = Response.ok().build();
    }
    logger.debug("Found (Renew): {} - {}; reply status={}" + app.getName(), id, response.getStatus());
    return response;
}
Example 39
Project: gyrex-jaxrs-application-master  File: HeaderParamInjectableProvider.java View source code
public Injectable getInjectable(ComponentContext ic, HeaderParam a, Parameter c) {
    String parameterName = c.getSourceName();
    if (parameterName == null || parameterName.length() == 0) {
        // Invalid header parameter name
        return null;
    }
    MultivaluedParameterExtractor e = get(c);
    if (e == null)
        return null;
    return new HeaderParamInjectable(e);
}
Example 40
Project: io-master  File: ODataEntitiesResource.java View source code
/**
     * @param uriInfo UriInfo
     * @param accept Acceptヘッダ
     * @param format $format パラメタ
     * @param callback コール�ック
     * @param skipToken スキップトークン
     * @param q 全文検索パラメタ
     * @return JAX-RS Response
     */
@GET
public Response listEntities(@Context UriInfo uriInfo, @HeaderParam(HttpHeaders.ACCEPT) final String accept, @QueryParam("$format") String format, @QueryParam("$callback") final String callback, @QueryParam("$skiptoken") final String skipToken, @QueryParam("q") final String q) {
    // アクセス制御
    this.odataResource.checkAccessContext(this.accessContext, this.odataResource.getNecessaryReadPrivilege(getEntitySetName()));
    // リクエスト��得をProducer��頼
    EntitiesResponse resp = getEntities(uriInfo, q);
    StringWriter sw = new StringWriter();
    // $format�Acceptヘッダ�値�ら出力形�を決定
    List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
    MediaType contentType = decideOutputFormat(accept, format);
    acceptableMediaTypes.add(contentType);
    FormatWriter<EntitiesResponse> fw = DcFormatWriterFactory.getFormatWriter(EntitiesResponse.class, acceptableMediaTypes, null, callback);
    UriInfo uriInfo2 = DcCoreUtils.createUriInfo(uriInfo, 1);
    fw.write(uriInfo2, sw, resp);
    String entity = null;
    entity = sw.toString();
    // 制御コード�エスケープ処�
    entity = escapeResponsebody(entity);
    // TODO remove this hack, check whether we are Version 2.0 compatible anyway
    ODataVersion version = null;
    version = ODataVersion.V2;
    return Response.ok(entity, fw.getContentType()).header(ODataConstants.Headers.DATA_SERVICE_VERSION, version.asString).build();
}
Example 41
Project: olingo-odata2-master  File: ODataSubLocator.java View source code
@POST
public Response handlePost(@HeaderParam("X-HTTP-Method") final String xHttpMethod) throws ODataException {
    Response response;
    if (xHttpMethod == null) {
        response = handle(ODataHttpMethod.POST);
    } else {
        /* tunneling */
        if ("MERGE".equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.MERGE);
        } else if ("PATCH".equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.PATCH);
        } else if (HttpMethod.DELETE.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.DELETE);
        } else if (HttpMethod.PUT.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.PUT);
        } else if (HttpMethod.GET.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.GET);
        } else if (HttpMethod.POST.equals(xHttpMethod)) {
            response = handle(ODataHttpMethod.POST);
        } else if (HttpMethod.HEAD.equals(xHttpMethod)) {
            response = handleHead();
        } else if (HttpMethod.OPTIONS.equals(xHttpMethod)) {
            response = handleOptions();
        } else {
            response = returnNotImplementedResponse(ODataNotImplementedException.TUNNELING);
        }
    }
    return response;
}
Example 42
Project: OpenBaas-master  File: VideoResource.java View source code
// *** CREATE *** //
/**
	 * Uploads an video File.
	 * 
	 * @param request
	 * @param headers
	 * @param inputJsonObj
	 * @return
	 */
@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({ MediaType.APPLICATION_JSON })
public Response uploadVideo(@Context HttpHeaders hh, @Context UriInfo ui, @FormDataParam(Const.FILE) InputStream uploadedInputStream, @FormDataParam(Const.FILE) FormDataContentDisposition fileDetail, @HeaderParam(value = Const.LOCATION) String location, @FormDataParam(Const.MESSAGEID) String messageId) {
    Response response = null;
    if (!sessionMid.checkAppForToken(Utils.getSessionToken(hh), appId))
        return Response.status(Status.UNAUTHORIZED).entity(new Error("Action in wrong app: " + appId)).build();
    int code = Utils.treatParameters(ui, hh);
    if (code == 1) {
        String userId = sessionMid.getUserIdUsingSessionToken(Utils.getSessionToken(hh));
        Result res = mediaMid.createMedia(uploadedInputStream, fileDetail, appId, userId, ModelEnum.video, location, Metadata.getNewMetadata(location), messageId);
        if (res == null || res.getData() == null)
            response = Response.status(Status.BAD_REQUEST).entity(new Error(appId)).build();
        else
            response = Response.status(Status.OK).entity(res).build();
    } else if (code == -2) {
        response = Response.status(Status.FORBIDDEN).entity(new Error("Invalid Session Token.")).build();
    } else if (code == -1)
        response = Response.status(Status.BAD_REQUEST).entity(new Error("Error handling the request.")).build();
    return response;
}
Example 43
Project: oxAuth-master  File: RptStatusWS.java View source code
@POST
@Produces({ UmaConstants.JSON_MEDIA_TYPE })
@ApiOperation(value = "The resource server MUST determine a received RPT's status, including both whether it is active and, if so, its associated authorization data, before giving or refusing access to the client. An RPT is associated with a set of authorization data that governs whether the client is authorized for access. The token's nature and format are dictated by its profile; the profile might allow it to be self-contained, such that the resource server is able to determine its status locally, or might require or allow the resource server to make a run-time introspection request of the authorization server that issued the token.", produces = UmaConstants.JSON_MEDIA_TYPE, notes = "The endpoint MAY allow other parameters to provide further context to\n" + "   the query.  For instance, an authorization service may need to know\n" + "   the IP address of the client accessing the protected resource in\n" + "   order to determine the appropriateness of the token being presented.\n" + "\n" + "   To prevent unauthorized token scanning attacks, the endpoint MUST\n" + "   also require some form of authorization to access this endpoint, such\n" + "   as client authentication as described in OAuth 2.0 [RFC6749] or a\n" + "   separate OAuth 2.0 access token such as the bearer token described in\n" + "   OAuth 2.0 Bearer Token Usage [RFC6750].  The methods of managing and\n" + "   validating these authentication credentials are out of scope of this\n" + "   specification.\n")
@ApiResponses(value = { @ApiResponse(code = 401, message = "Unauthorized") })
public Response requestRptStatus(@HeaderParam("Authorization") String authorization, @FormParam("token") @ApiParam(value = "The string value of the token.  For access tokens,\n" + "      this is the \"access_token\" value returned from the token endpoint\n" + "      defined in OAuth 2.0 [RFC6749] section 5.1.  For refresh tokens,\n" + "      this is the \"refresh_token\" value returned from the token endpoint\n" + "      as defined in OAuth 2.0 [RFC6749] section 5.1.  Other token types\n" + "      are outside the scope of this specification.", required = true) String rptAsString, @FormParam("token_type_hint") @ApiParam(value = "A hint about the type of the token\n" + "      submitted for introspection.  The protected resource re MAY pass\n" + "      this parameter in order to help the authorization server to\n" + "      optimize the token lookup.  If the server is unable to locate the\n" + "      token using the given hint, it MUST extend its search across all\n" + "      of its supported token types.  An authorization server MAY ignore\n" + "      this parameter, particularly if it is able to detect the token\n" + "      type automatically.  Values for this field are defined in OAuth\n" + "      Token Revocation [RFC7009].", required = false) String tokenTypeHint) {
    try {
        umaValidationService.assertHasProtectionScope(authorization);
        final UmaRPT rpt = rptManager.getRPTByCode(rptAsString);
        if (rpt != null && AbstractRPTManager.isGat(rpt.getCode())) {
            return gatResponse(rpt);
        }
        if (!isValid(rpt)) {
            return Response.status(Response.Status.OK).entity(new RptIntrospectionResponse(false)).cacheControl(ServerUtil.cacheControl(true)).build();
        }
        final List<UmaPermission> permissions = buildStatusResponsePermissions(rpt);
        // active status
        final RptIntrospectionResponse statusResponse = new RptIntrospectionResponse();
        statusResponse.setActive(true);
        statusResponse.setExpiresAt(rpt.getExpirationDate());
        statusResponse.setIssuedAt(rpt.getCreationDate());
        statusResponse.setPermissions(permissions);
        // convert manually to avoid possible conflict between resteasy providers, e.g. jettison, jackson
        final String entity = ServerUtil.asJson(statusResponse);
        return Response.status(Response.Status.OK).entity(entity).cacheControl(ServerUtil.cacheControl(true)).build();
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponseFactory.getUmaJsonErrorResponse(UmaErrorResponseType.SERVER_ERROR)).build());
    }
}
Example 44
Project: presto-master  File: TaskResource.java View source code
@GET
@Path("{taskId}")
@Produces(MediaType.APPLICATION_JSON)
public void getTaskInfo(@PathParam("taskId") final TaskId taskId, @HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState, @HeaderParam(PRESTO_MAX_WAIT) Duration maxWait, @Context UriInfo uriInfo, @Suspended AsyncResponse asyncResponse) {
    requireNonNull(taskId, "taskId is null");
    if (currentState == null || maxWait == null) {
        TaskInfo taskInfo = taskManager.getTaskInfo(taskId);
        if (shouldSummarize(uriInfo)) {
            taskInfo = taskInfo.summarize();
        }
        asyncResponse.resume(taskInfo);
        return;
    }
    Duration waitTime = randomizeWaitTime(maxWait);
    ListenableFuture<TaskInfo> futureTaskInfo = addTimeout(taskManager.getTaskInfo(taskId, currentState), () -> taskManager.getTaskInfo(taskId), waitTime, timeoutExecutor);
    if (shouldSummarize(uriInfo)) {
        futureTaskInfo = Futures.transform(futureTaskInfo, TaskInfo::summarize);
    }
    // For hard timeout, add an additional time to max wait for thread scheduling contention and GC
    Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS);
    bindAsyncResponse(asyncResponse, futureTaskInfo, responseExecutor).withTimeout(timeout);
}
Example 45
Project: schema-registry-master  File: SubjectVersionsResource.java View source code
@POST
@PerformanceMetric("subjects.versions.register")
public void register(@Suspended final AsyncResponse asyncResponse, @HeaderParam("Content-Type") final String contentType, @HeaderParam("Accept") final String accept, @PathParam("subject") String subjectName, @NotNull RegisterSchemaRequest request) {
    Map<String, String> headerProperties = new HashMap<String, String>();
    headerProperties.put("Content-Type", contentType);
    headerProperties.put("Accept", accept);
    Schema schema = new Schema(subjectName, 0, 0, request.getSchema());
    int id = 0;
    try {
        id = schemaRegistry.registerOrForward(subjectName, schema, headerProperties);
    } catch (InvalidSchemaException e) {
        throw Errors.invalidAvroException("Input schema is an invalid Avro schema", e);
    } catch (SchemaRegistryTimeoutException e) {
        throw Errors.operationTimeoutException("Register operation timed out", e);
    } catch (SchemaRegistryStoreException e) {
        throw Errors.storeException("Register schema operation failed while writing" + " to the Kafka store", e);
    } catch (SchemaRegistryRequestForwardingException e) {
        throw Errors.requestForwardingFailedException("Error while forwarding register schema request" + " to the master", e);
    } catch (IncompatibleSchemaException e) {
        throw Errors.incompatibleSchemaException("Schema being registered is incompatible with an" + " earlier schema", e);
    } catch (UnknownMasterException e) {
        throw Errors.unknownMasterException("Master not known.", e);
    } catch (SchemaRegistryException e) {
        throw Errors.schemaRegistryException("Error while registering schema", e);
    }
    RegisterSchemaResponse registerSchemaResponse = new RegisterSchemaResponse();
    registerSchemaResponse.setId(id);
    asyncResponse.resume(registerSchemaResponse);
}
Example 46
Project: smart-cms-master  File: WorkspaceVariationResource.java View source code
@PUT
@Consumes(MediaType.APPLICATION_JSON)
public Response put(com.smartitengineering.cms.ws.common.domains.ResourceTemplate template, @HeaderParam(HttpHeaders.IF_MATCH) String ifMatchHeader) {
    ResponseBuilder builder;
    WorkspaceId id = workspace.getId();
    if (this.template == null) {
        final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi();
        VariationTemplate created = workspaceApi.putVariationTemplate(workspaceApi.createWorkspaceId(id.getGlobalNamespace(), id.getName()), varName, TemplateType.valueOf(template.getTemplateType()), template.getTemplate());
        if (created != null) {
            UriBuilder uriBuilder = getAbsoluteURIBuilder().path(WorkspaceResource.class).path(WorkspaceResource.PATH_VARIATIONS).path("name").path(varName);
            builder = Response.created(uriBuilder.build(id.getGlobalNamespace(), id.getName()));
        } else {
            builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
        }
    } else {
        if (StringUtils.isBlank(ifMatchHeader)) {
            return Response.status(Status.PRECONDITION_FAILED).build();
        }
        Date lastModifiedDate = this.template.getLastModifiedDate();
        EntityTag entityTag = new EntityTag(WorkspaceRepresentationResource.getETag(this.template));
        builder = getContext().getRequest().evaluatePreconditions(lastModifiedDate, entityTag);
        if (builder == null) {
            final WorkspaceAPI workspaceApi = SmartContentAPI.getInstance().getWorkspaceApi();
            VariationTemplate put = workspaceApi.putVariationTemplate(workspaceApi.createWorkspaceId(id.getGlobalNamespace(), id.getName()), varName, TemplateType.valueOf(template.getTemplateType()), template.getTemplate());
            if (put != null) {
                builder = Response.status(Status.ACCEPTED).location(getUriInfo().getRequestUri());
            } else {
                builder = Response.status(Response.Status.INTERNAL_SERVER_ERROR);
            }
        }
    }
    return builder.build();
}
Example 47
Project: smart-event-hub-master  File: ChannelHubResource.java View source code
@Broadcast
@POST
@Cluster(name = "EventHub", value = JGroupsFilter.class)
public Response broadcast(@HeaderParam("Content-type") String contentType, String message) {
    checkAuthToken();
    checkChannelExistence();
    final String eventContentType;
    //HTTP Request entity body can not be blank
    if (StringUtils.isBlank(message)) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    final boolean isHtmlPost;
    if (StringUtils.isBlank(contentType)) {
        eventContentType = MediaType.APPLICATION_OCTET_STREAM;
        isHtmlPost = false;
    } else if (contentType.equals(MediaType.APPLICATION_FORM_URLENCODED)) {
        eventContentType = MediaType.APPLICATION_OCTET_STREAM;
        isHtmlPost = true;
        try {
            //Will search for the first '=' if not found will take the whole string
            final int startIndex = message.indexOf("=") + 1;
            //Consider the first '=' as the start of a value point and take rest as value
            final String realMsg = message.substring(startIndex);
            //Decode the message to ignore the form encodings and make them human readable
            message = URLDecoder.decode(realMsg, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
    } else {
        eventContentType = contentType;
        isHtmlPost = false;
    }
    Event event = APIFactory.getEventBuilder().eventContent(APIFactory.getContent(eventContentType, IOUtils.toInputStream(message))).build();
    final Channel channel = HubPersistentStorerSPI.getInstance().getStorer().getChannel(channelName);
    event = HubPersistentStorerSPI.getInstance().getStorer().create(channel, event);
    //Add a new line at the end of the message to ensure that the message is flushed to its listeners
    message = message + "\n";
    Broadcastable broadcastable = new Broadcastable(message, broadcaster);
    ResponseBuilder builder = Response.ok(broadcastable);
    builder.location(getAbsoluteURIBuilder().path(EventResource.class).build(event.getPlaceholderId()));
    if (isHtmlPost) {
        builder.status(Response.Status.SEE_OTHER);
        builder.location(getAbsoluteURIBuilder().path(ChannelEventsResource.class).build(channelName));
    }
    return builder.build();
}
Example 48
Project: SmartHome-master  File: ThingTypeResource.java View source code
@GET
@RolesAllowed({ Role.USER })
@Path("/{thingTypeUID}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "Gets thing type by UID.", response = ThingTypeDTO.class)
@ApiResponses(value = { @ApiResponse(code = 200, message = "Thing type with provided thingTypeUID does not exist.", response = ThingTypeDTO.class), @ApiResponse(code = 404, message = "No content") })
public Response getByUID(@PathParam("thingTypeUID") @ApiParam(value = "thingTypeUID") String thingTypeUID, @HeaderParam(HttpHeaders.ACCEPT_LANGUAGE) @ApiParam(value = HttpHeaders.ACCEPT_LANGUAGE) String language) {
    Locale locale = LocaleUtil.getLocale(language);
    ThingType thingType = thingTypeRegistry.getThingType(new ThingTypeUID(thingTypeUID), locale);
    if (thingType != null) {
        return Response.ok(convertToThingTypeDTO(thingType, locale)).build();
    } else {
        return Response.noContent().build();
    }
}
Example 49
Project: spring-rest-invoker-master  File: JaxRsAnnotationMethodInspector.java View source code
/*
     * RequestMapping -> PATH, GET, POST RequestParam -> QueryParam PathVariable
     * -> PathParam RequestBody -> BeanParam RequestPart -> FormParam
     */
@Override
public UrlMapping inspect(Method method, Object[] args) {
    UrlMapping urlMapping = new UrlMapping();
    Path path = AnnotationUtils.findAnnotation(method, Path.class);
    if (path == null || path.value() == null)
        return null;
    urlMapping.setUrl(resolveExpression(path.value()));
    if (urlMapping.getUrl() == null)
        throw new MappingDeclarationException("Missing @Path on method " + method, method, path, -1);
    Set<HttpMethod> httpMethods = new HashSet<>();
    if (AnnotationUtils.findAnnotation(method, POST.class) != null)
        httpMethods.add(HttpMethod.POST);
    if (AnnotationUtils.findAnnotation(method, PUT.class) != null)
        httpMethods.add(HttpMethod.PUT);
    if (AnnotationUtils.findAnnotation(method, DELETE.class) != null)
        httpMethods.add(HttpMethod.DELETE);
    if (httpMethods.size() > 1)
        throw new MappingDeclarationException("Multiple HTTP methods specified on " + method.toGenericString(), method, null, -1);
    if (httpMethods.size() == 1)
        urlMapping.setHttpMethod(httpMethods.iterator().next());
    else
        urlMapping.setHttpMethod(HttpMethod.GET);
    Produces produces = AnnotationUtils.findAnnotation(method, Produces.class);
    if (produces != null)
        urlMapping.setProduces(produces.value());
    Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class);
    if (consumes != null)
        urlMapping.setConsumes(consumes.value());
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    if (parameterAnnotations.length != method.getParameterTypes().length)
        throw new MappingDeclarationException(String.format("Annotation mismatch: method has %d parameters but %d have been annotated on %s", parameterAnnotations.length, method.getParameterTypes().length, method.toString()), method, null, -1);
    int i = 0;
    for (Annotation[] annotations : parameterAnnotations) {
        Object value = args[i];
        i++;
        String parameterName = "";
        Type parameterType = null;
        boolean parameterFound = false;
        for (Annotation annotation : annotations) {
            if (PathParam.class.isAssignableFrom(annotation.annotationType())) {
                PathParam pv = (PathParam) annotation;
                parameterName = pv.value();
                urlMapping.addDescriptor(new MethodParameterDescriptor(Type.pathVariable, parameterName, value, method, i));
                parameterFound = true;
            }
            if (QueryParam.class.isAssignableFrom(annotation.annotationType())) {
                QueryParam pv = (QueryParam) annotation;
                parameterName = pv.value();
                urlMapping.addDescriptor(new MethodParameterDescriptor(Type.httpParameter, parameterName, value, method, i));
                parameterFound = true;
            }
            if (HeaderParam.class.isAssignableFrom(annotation.annotationType())) {
                HeaderParam pv = (HeaderParam) annotation;
                parameterName = pv.value();
                parameterFound = true;
                parameterType = Type.httpHeader;
            }
            if (BeanParam.class.isAssignableFrom(annotation.annotationType())) {
                parameterType = Type.requestBody;
                parameterFound = true;
            }
            if (FormParam.class.isAssignableFrom(annotation.annotationType())) {
                parameterType = Type.requestPart;
                parameterFound = true;
            }
            if (CookieParam.class.isAssignableFrom(annotation.annotationType())) {
                parameterType = Type.cookie;
                parameterFound = true;
                CookieParam cv = (CookieParam) annotation;
                parameterName = cv.value();
            }
        }
        if (!parameterFound)
            throw new MappingDeclarationException(String.format("Couldn't find mapping annotation on parameter %d of method %s", i, method.toGenericString()), method, null, i);
        if (parameterType != null) {
            urlMapping.addDescriptor(new MethodParameterDescriptor(parameterType, parameterName, value, method, i));
        }
    }
    return urlMapping;
}
Example 50
Project: streamflow-master  File: FileResource.java View source code
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public FileInfo createFile(@FormDataParam("file") byte[] fileContent, @FormDataParam("file") FormDataContentDisposition fileDetail, @HeaderParam("Content-type") String contentType) {
    // Validate the input parameters
    if (fileContent == null) {
        throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).entity("File content was specified in the request").build());
    }
    // Save the upload metadata for later retrieval
    FileInfo fileInfo = new FileInfo();
    fileInfo.setId(IDUtils.randomUUID());
    fileInfo.setFileName(fileDetail.getFileName());
    fileInfo.setFileSize(fileContent.length);
    fileInfo.setCreated(new Date());
    fileInfo.setModified(fileInfo.getCreated());
    fileInfo.setContentHash(DigestUtils.md5Hex(fileContent));
    try {
        // Reliably detect the mime type using Tika
        fileInfo.setFileType(detector.detect(new ByteArrayInputStream(fileContent), new Metadata()).toString());
    } catch (IOException ex) {
        fileInfo.setFileType("application/octet-stream");
    }
    // Persist the upload metadata after the file is successfully written
    fileInfo = fileService.saveFile(fileInfo, fileContent);
    return fileInfo;
}
Example 51
Project: swagger-maven-plugin-master  File: JaxrsParameterExtension.java View source code
public static SerializableParameter getParameter(Type type, SerializableParameter parameter, Annotation annotation) {
    String defaultValue = "";
    if (annotation instanceof DefaultValue) {
        DefaultValue defaultValueAnnotation = (DefaultValue) annotation;
        defaultValue = defaultValueAnnotation.value();
    }
    if (annotation instanceof QueryParam) {
        QueryParam param = (QueryParam) annotation;
        QueryParameter queryParameter = new QueryParameter().name(param.value());
        if (!defaultValue.isEmpty()) {
            queryParameter.setDefaultValue(defaultValue);
        }
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            queryParameter.setProperty(schema);
        }
        String parameterType = queryParameter.getType();
        if (parameterType == null || parameterType.equals("ref")) {
            queryParameter.setType("string");
        }
        parameter = queryParameter;
    } else if (annotation instanceof PathParam) {
        PathParam param = (PathParam) annotation;
        PathParameter pathParameter = new PathParameter().name(param.value());
        if (!defaultValue.isEmpty()) {
            pathParameter.setDefaultValue(defaultValue);
        }
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            pathParameter.setProperty(schema);
        }
        String parameterType = pathParameter.getType();
        if (parameterType == null || parameterType.equals("ref")) {
            pathParameter.setType("string");
        }
        parameter = pathParameter;
    } else if (annotation instanceof HeaderParam) {
        HeaderParam param = (HeaderParam) annotation;
        HeaderParameter headerParameter = new HeaderParameter().name(param.value());
        headerParameter.setDefaultValue(defaultValue);
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            headerParameter.setProperty(schema);
        }
        String parameterType = headerParameter.getType();
        if (parameterType == null || parameterType.equals("ref") || parameterType.equals("array")) {
            headerParameter.setType("string");
        }
        parameter = headerParameter;
    } else if (annotation instanceof CookieParam) {
        CookieParam param = (CookieParam) annotation;
        CookieParameter cookieParameter = new CookieParameter().name(param.value());
        if (!defaultValue.isEmpty()) {
            cookieParameter.setDefaultValue(defaultValue);
        }
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            cookieParameter.setProperty(schema);
        }
        String parameterType = cookieParameter.getType();
        if (parameterType == null || parameterType.equals("ref") || parameterType.equals("array")) {
            cookieParameter.setType("string");
        }
        parameter = cookieParameter;
    } else if (annotation instanceof FormParam) {
        FormParam param = (FormParam) annotation;
        FormParameter formParameter = new FormParameter().name(param.value());
        if (!defaultValue.isEmpty()) {
            formParameter.setDefaultValue(defaultValue);
        }
        Property schema = ModelConverters.getInstance().readAsProperty(type);
        if (schema != null) {
            formParameter.setProperty(schema);
        }
        String parameterType = formParameter.getType();
        if (parameterType == null || parameterType.equals("ref") || parameterType.equals("array")) {
            formParameter.setType("string");
        }
        parameter = formParameter;
    }
    //
    return parameter;
}
Example 52
Project: TextSecure-Server-master  File: AccountController.java View source code
@Timed
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("/code/{verification_code}")
public void verifyAccount(@PathParam("verification_code") String verificationCode, @HeaderParam("Authorization") String authorizationHeader, @Valid AccountAttributes accountAttributes) throws RateLimitExceededException {
    try {
        AuthorizationHeader header = AuthorizationHeader.fromFullHeader(authorizationHeader);
        String number = header.getNumber();
        String password = header.getPassword();
        rateLimiters.getVerifyLimiter().validate(number);
        Optional<String> storedVerificationCode = pendingAccounts.getCodeForNumber(number);
        if (!storedVerificationCode.isPresent() || !verificationCode.equals(storedVerificationCode.get())) {
            throw new WebApplicationException(Response.status(403).build());
        }
        if (accounts.isRelayListed(number)) {
            throw new WebApplicationException(Response.status(417).build());
        }
        createAccount(number, password, accountAttributes);
    } catch (InvalidAuthorizationHeaderException e) {
        logger.info("Bad Authorization Header", e);
        throw new WebApplicationException(Response.status(401).build());
    }
}
Example 53
Project: uma-master  File: RptStatusWS.java View source code
@POST
@Produces({ UmaConstants.JSON_MEDIA_TYPE })
@ApiOperation(value = "The resource server MUST determine a received RPT's status, including both whether it is active and, if so, its associated authorization data, before giving or refusing access to the client. An RPT is associated with a set of authorization data that governs whether the client is authorized for access. The token's nature and format are dictated by its profile; the profile might allow it to be self-contained, such that the resource server is able to determine its status locally, or might require or allow the resource server to make a run-time introspection request of the authorization server that issued the token.", produces = UmaConstants.JSON_MEDIA_TYPE, notes = "The endpoint MAY allow other parameters to provide further context to\n" + "   the query.  For instance, an authorization service may need to know\n" + "   the IP address of the client accessing the protected resource in\n" + "   order to determine the appropriateness of the token being presented.\n" + "\n" + "   To prevent unauthorized token scanning attacks, the endpoint MUST\n" + "   also require some form of authorization to access this endpoint, such\n" + "   as client authentication as described in OAuth 2.0 [RFC6749] or a\n" + "   separate OAuth 2.0 access token such as the bearer token described in\n" + "   OAuth 2.0 Bearer Token Usage [RFC6750].  The methods of managing and\n" + "   validating these authentication credentials are out of scope of this\n" + "   specification.\n")
@ApiResponses(value = { @ApiResponse(code = 401, message = "Unauthorized") })
public Response requestRptStatus(@HeaderParam("Authorization") String authorization, @FormParam("token") @ApiParam(value = "The string value of the token.  For access tokens,\n" + "      this is the \"access_token\" value returned from the token endpoint\n" + "      defined in OAuth 2.0 [RFC6749] section 5.1.  For refresh tokens,\n" + "      this is the \"refresh_token\" value returned from the token endpoint\n" + "      as defined in OAuth 2.0 [RFC6749] section 5.1.  Other token types\n" + "      are outside the scope of this specification.", required = true) String rptAsString, @FormParam("token_type_hint") @ApiParam(value = "A hint about the type of the token\n" + "      submitted for introspection.  The protected resource re MAY pass\n" + "      this parameter in order to help the authorization server to\n" + "      optimize the token lookup.  If the server is unable to locate the\n" + "      token using the given hint, it MUST extend its search across all\n" + "      of its supported token types.  An authorization server MAY ignore\n" + "      this parameter, particularly if it is able to detect the token\n" + "      type automatically.  Values for this field are defined in OAuth\n" + "      Token Revocation [RFC7009].", required = false) String tokenTypeHint) {
    try {
        umaValidationService.assertHasProtectionScope(authorization);
        final UmaRPT rpt = rptManager.getRPTByCode(rptAsString);
        if (rpt != null && AbstractRPTManager.isGat(rpt.getCode())) {
            return gatResponse(rpt);
        }
        if (!isValid(rpt)) {
            return Response.status(Response.Status.OK).entity(new RptIntrospectionResponse(false)).cacheControl(ServerUtil.cacheControl(true)).build();
        }
        final List<UmaPermission> permissions = buildStatusResponsePermissions(rpt);
        // active status
        final RptIntrospectionResponse statusResponse = new RptIntrospectionResponse();
        statusResponse.setActive(true);
        statusResponse.setExpiresAt(rpt.getExpirationDate());
        statusResponse.setIssuedAt(rpt.getCreationDate());
        statusResponse.setPermissions(permissions);
        // convert manually to avoid possible conflict between resteasy providers, e.g. jettison, jackson
        final String entity = ServerUtil.asJson(statusResponse);
        return Response.status(Response.Status.OK).entity(entity).cacheControl(ServerUtil.cacheControl(true)).build();
    } catch (Exception ex) {
        log.error("Exception happened", ex);
        if (ex instanceof WebApplicationException) {
            throw (WebApplicationException) ex;
        }
        throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorResponseFactory.getUmaJsonErrorResponse(UmaErrorResponseType.SERVER_ERROR)).build());
    }
}
Example 54
Project: XPagesExtensionLibrary-master  File: NoticeActionResource.java View source code
@PUT
public // $NON-NLS-1$
Response putNoticeAction(// $NON-NLS-1$
String requestEntity, // $NON-NLS-1$
@HeaderParam("Content-Type") String contentType, @Context UriInfo uriInfo, @PathParam(NOTICE) String id, @QueryParam(URL_PARAM_ACTION_TYPE) String type) {
    // $NON-NLS-1$
    CALENDAR_SERVICE_LOGGER.traceEntry(this, "putNoticeAction");
    CalendarService.beforeRequest(FEATURE_REST_API_CALENDAR_NOTICE, STAT_MISC);
    CalendarService.verifyDatabaseContext();
    if (type == null || type.length() == 0) {
        // $NLX-NoticeActionResource.Actiontypenotspecified-1$
        throw new WebApplicationException(CalendarService.createErrorResponse("Action type not specified.", Status.BAD_REQUEST));
    }
    int actionType = Utils.translateActionType(type);
    if (actionType == -1) {
        // $NLX-NoticeActionResource.Unknownactiontype-1$
        throw new WebApplicationException(CalendarService.createErrorResponse("Unknown action type.", Status.BAD_REQUEST));
    }
    try {
        Action action = Utils.createAction(actionType, contentType, requestEntity);
        StoreFactory.getEventStore().processNoticeAction(id, action);
    } catch (StoreException e) {
        throw new WebApplicationException(ErrorHelper.createErrorResponse("Error processing notice action.", Utils.mapStatus(e), Utils.getExtraProps(e)));
    } catch (JsonException e) {
        throw new WebApplicationException(CalendarService.createErrorResponse("Error processing notice action.", Status.BAD_REQUEST));
    } catch (ParseException e) {
        throw new WebApplicationException(CalendarService.createErrorResponse("Error processing notice action.", Status.BAD_REQUEST));
    }
    ResponseBuilder builder = Response.ok();
    Response response = builder.build();
    // $NON-NLS-1$
    CALENDAR_SERVICE_LOGGER.traceExit(this, "putNoticeAction", response);
    return response;
}
Example 55
Project: abiquo-master  File: PhysicalMachineResource.java View source code
/**
     * Start monitoring a physical machine.
     * 
     * @param physicalMachine The physical machine data.
     * @param auth The authentication details for the given physical machine.
     * @return The monitored physical machine.
     */
@POST
public PhysicalMachineDto monitor(final PhysicalMachineDto physicalMachine, @HeaderParam(AUTH_HEADER) final String auth) {
    checkSystem();
    String[] credentials = getBasicAuthCredentials(auth);
    PhysicalMachine pm;
    if (credentials.length != 0) {
        pm = vsmService.monitor(physicalMachine.getAddress(), physicalMachine.getType(), credentials[0], credentials[1]);
    } else {
        pm = vsmService.monitor(physicalMachine.getAddress(), physicalMachine.getType());
    }
    return toDto(pm);
}
Example 56
Project: activemq-artemis-master  File: QueueConsumer.java View source code
@Path("consume-next{index}")
@POST
public synchronized Response poll(@HeaderParam(Constants.WAIT_HEADER) @DefaultValue("0") long wait, @PathParam("index") long index, @Context UriInfo info) {
    ActiveMQRestLogger.LOGGER.debug("Handling POST request for \"" + info.getRequestUri() + "\"");
    if (closed) {
        UriBuilder builder = info.getBaseUriBuilder();
        builder.path(info.getMatchedURIs().get(1)).path("consume-next");
        String uri = builder.build().toString();
        return Response.status(307).location(URI.create(uri)).build();
    }
    return checkIndexAndPoll(wait, info, info.getMatchedURIs().get(1), index);
}
Example 57
Project: BitHub-master  File: GithubController.java View source code
@Timed
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/commits/")
public void handleCommits(@Auth Authentication auth, @HeaderParam("X-Forwarded-For") String clientIp, @FormParam("payload") String eventString) throws IOException, UnauthorizedHookException, TransferFailedException, CoinbaseException {
    authenticate(clientIp);
    PushEvent event = getEventFromPayload(eventString);
    if (!repositories.containsKey(event.getRepository().getUrl().toLowerCase())) {
        throw new UnauthorizedHookException("Not a valid repository: " + event.getRepository().getUrl());
    }
    if (!event.getRef().equals(MASTER_REF)) {
        logger.info("Not a push to master: " + event.getRef());
        return;
    }
    Repository repository = event.getRepository();
    String defaultMode = repositories.get(repository.getUrl().toLowerCase());
    List<Commit> commits = getQualifyingCommits(event, defaultMode);
    BigDecimal balance = coinbaseClient.getAccountBalance();
    BigDecimal exchangeRate = coinbaseClient.getExchangeRate();
    logger.info("Retrieved balance: " + balance.toPlainString());
    sendPaymentsFor(repository, commits, balance, exchangeRate);
}
Example 58
Project: cassandra-rest-master  File: DataResource.java View source code
// ================================================================================================================
// Column Family Operations
// ================================================================================================================
@GET
@Path("/{keyspace}/{columnFamily}")
@Produces({ "application/json" })
public JSONArray getColumnFamily(@PathParam("keyspace") String keyspace, @PathParam("columnFamily") String columnFamily, @QueryParam("q") String query, @HeaderParam(CONSISTENCY_LEVEL_HEADER) String consistencyLevel) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Listing column family [" + keyspace + "]:[" + columnFamily + "]");
    logger.debug("STORAGE [" + getCassandraStorage() + "]");
    logger.debug("CONFG [" + config + "]");
    return getCassandraStorage().getRows(keyspace, columnFamily, query, config.getConsistencyLevel(consistencyLevel));
}
Example 59
Project: ecms-develop-master  File: ThumbnailRESTService.java View source code
/**
   * Returns an image with an original size.
   *
   * @param repoName The repository name.
   * @param workspaceName The workspace name.
   * @param nodePath The node path.
   * @return Response data stream.
   * @throws Exception
   *
   * @anchor ThumbnailRESTService.getOriginImage
   */
@Path("/origin/{repoName}/{workspaceName}/{nodePath:.*}/")
@GET
public Response getOriginImage(@PathParam("repoName") String repoName, @PathParam("workspaceName") String workspaceName, @PathParam("nodePath") String nodePath, @HeaderParam("If-Modified-Since") String ifModifiedSince) throws Exception {
    DateFormat dateFormat = new SimpleDateFormat(IF_MODIFIED_SINCE_DATE_FORMAT);
    if (!thumbnailService_.isEnableThumbnail())
        return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build();
    Node showingNode = getShowingNode(workspaceName, getNodePath(nodePath));
    Node targetNode = getTargetNode(showingNode);
    if (targetNode.isNodeType("nt:file") || targetNode.isNodeType("nt:resource")) {
        Node content = targetNode;
        if (targetNode.isNodeType("nt:file"))
            content = targetNode.getNode("jcr:content");
        if (ifModifiedSince != null) {
            // get last-modified-since from header
            Date ifModifiedSinceDate = dateFormat.parse(ifModifiedSince);
            // get last modified date of node
            Date lastModifiedDate = content.getProperty("jcr:lastModified").getDate().getTime();
            // Check if cached resource has not been modifed, return 304 code
            if (ifModifiedSinceDate.getTime() >= lastModifiedDate.getTime()) {
                return Response.notModified().build();
            }
        }
        String mimeType = content.getProperty("jcr:mimeType").getString();
        for (ComponentPlugin plugin : thumbnailService_.getComponentPlugins()) {
            if (plugin instanceof ThumbnailPlugin) {
                ThumbnailPlugin thumbnailPlugin = (ThumbnailPlugin) plugin;
                if (thumbnailPlugin.getMimeTypes().contains(mimeType)) {
                    InputStream inputStream = content.getProperty("jcr:data").getStream();
                    return Response.ok(inputStream, "image").header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build();
                }
            }
        }
    }
    return Response.ok().header(LAST_MODIFIED_PROPERTY, dateFormat.format(new Date())).build();
}
Example 60
Project: errai-master  File: JaxrsResourceMethodParameters.java View source code
public static JaxrsResourceMethodParameters fromMethod(MetaMethod method, List<? extends Statement> parameterValues) {
    final JaxrsResourceMethodParameters params = new JaxrsResourceMethodParameters();
    int i = 0;
    for (final MetaParameter param : method.getParameters()) {
        final Statement paramValue = parameterValues.get(i++);
        Annotation a = param.getAnnotation(PathParam.class);
        if (a != null) {
            params.add(PathParam.class, ((PathParam) a).value(), paramValue);
        } else if ((a = param.getAnnotation(QueryParam.class)) != null) {
            params.add(QueryParam.class, ((QueryParam) a).value(), paramValue);
        } else if ((a = param.getAnnotation(HeaderParam.class)) != null) {
            params.add(HeaderParam.class, ((HeaderParam) a).value(), paramValue);
        } else if ((a = param.getAnnotation(MatrixParam.class)) != null) {
            params.add(MatrixParam.class, ((MatrixParam) a).value(), paramValue);
        } else if ((a = param.getAnnotation(FormParam.class)) != null) {
            params.add(FormParam.class, ((FormParam) a).value(), paramValue);
        } else if ((a = param.getAnnotation(CookieParam.class)) != null) {
            params.add(CookieParam.class, ((CookieParam) a).value(), paramValue);
        } else {
            params.setEntityParameter(paramValue, method);
        }
    }
    return params;
}
Example 61
Project: fcrepo4-master  File: FedoraVersions.java View source code
/**
     * Retrieve a version of an object.  The path structure is as follows
     * (though these URLs are returned from getVersionList and need not be
     * constructed manually):
     * /versionable-node/fcr:versions/label/path/to/any/copied/unversionable/nodes
     * @param rangeValue the range value
     * @throws IOException if IO exception occurred
     * @return the version of the object as RDF in the requested format
     */
@SuppressWarnings("resource")
@GET
@Produces({ TURTLE_WITH_CHARSET + ";qs=1.0", JSON_LD + ";qs=0.8", N3_WITH_CHARSET, N3_ALT2_WITH_CHARSET, RDF_XML, NTRIPLES, TEXT_PLAIN_WITH_CHARSET, TURTLE_X, TEXT_HTML_WITH_CHARSET, "*/*" })
public Response getVersion(@HeaderParam("Range") final String rangeValue) throws IOException {
    LOGGER.trace("Getting version profile for: {} at version: {}", path, label);
    checkCacheControlHeaders(request, servletResponse, resource(), session);
    final RdfStream rdfStream = new DefaultRdfStream(asNode(resource()));
    addResourceHttpHeaders(resource());
    return getContent(rangeValue, rdfStream);
}
Example 62
Project: feign-master  File: JAXRSContract.java View source code
@Override
protected boolean processAnnotationsOnParameter(MethodMetadata data, Annotation[] annotations, int paramIndex) {
    boolean isHttpParam = false;
    for (Annotation parameterAnnotation : annotations) {
        Class<? extends Annotation> annotationType = parameterAnnotation.annotationType();
        if (annotationType == PathParam.class) {
            String name = PathParam.class.cast(parameterAnnotation).value();
            checkState(emptyToNull(name) != null, "PathParam.value() was empty on parameter %s", paramIndex);
            nameParam(data, name, paramIndex);
            isHttpParam = true;
        } else if (annotationType == QueryParam.class) {
            String name = QueryParam.class.cast(parameterAnnotation).value();
            checkState(emptyToNull(name) != null, "QueryParam.value() was empty on parameter %s", paramIndex);
            Collection<String> query = addTemplatedParam(data.template().queries().get(name), name);
            data.template().query(name, query);
            nameParam(data, name, paramIndex);
            isHttpParam = true;
        } else if (annotationType == HeaderParam.class) {
            String name = HeaderParam.class.cast(parameterAnnotation).value();
            checkState(emptyToNull(name) != null, "HeaderParam.value() was empty on parameter %s", paramIndex);
            Collection<String> header = addTemplatedParam(data.template().headers().get(name), name);
            data.template().header(name, header);
            nameParam(data, name, paramIndex);
            isHttpParam = true;
        } else if (annotationType == FormParam.class) {
            String name = FormParam.class.cast(parameterAnnotation).value();
            checkState(emptyToNull(name) != null, "FormParam.value() was empty on parameter %s", paramIndex);
            data.formParams().add(name);
            nameParam(data, name, paramIndex);
            isHttpParam = true;
        }
    }
    return isHttpParam;
}
Example 63
Project: GamificationEngine-Kinben-master  File: OrganisationApi.java View source code
/**
	 * Creates a new organisation. The email address and password of one Account are used 
	 * to connect it with this organisation. So the email address and password are mandatory for
	 * authentication otherwise a warning with the hint for wrong credentials is returned.
	 * All further Accounts which should be associated to this organisation are added with the 
	 * method addManager. 
	 * In the response the account's password isn't returned because of security reasons.
	 *
	 * @param name 
	 * 			The name of the developer or the manager of the account.
	 * @param email
	 *           The required valid email address.
	 * @param password
	 *           Required header parameter associated with the email address.
	 * @return A Response of Organisation in JSON.
	 */
@POST
@Path("/")
@TypeHint(Organisation.class)
public Response create(@QueryParam("name") String name, @QueryParam("email") @NotNull @Email String email, @HeaderParam("password") @NotNull String password) {
    LOGGER.debug("create organisation requested");
    String encryptedPassword = SecurityTools.encryptWithSHA512(password);
    if (!accountDao.checkCredentials(email, encryptedPassword)) {
        throw new CredentialException(email);
    }
    Organisation organisation = new Organisation(name);
    organisation.addManager(accountDao.getAccount(email, encryptedPassword));
    organisation.setApiKey(SecurityTools.generateApiKey());
    LOGGER.debug("Organisation created");
    organisationDao.insertOrganisation(organisation);
    return ResponseSurrogate.created(organisation);
}
Example 64
Project: hbase-master  File: TableScanResource.java View source code
@GET
@Produces({ Constants.MIMETYPE_PROTOBUF, Constants.MIMETYPE_PROTOBUF_IETF })
public Response getProtobuf(@Context final UriInfo uriInfo, @PathParam("scanspec") final String scanSpec, @HeaderParam("Accept") final String contentType, @DefaultValue(Integer.MAX_VALUE + "") @QueryParam(Constants.SCAN_LIMIT) int userRequestedLimit, @DefaultValue("") @QueryParam(Constants.SCAN_START_ROW) String startRow, @DefaultValue("") @QueryParam(Constants.SCAN_END_ROW) String endRow, @DefaultValue("column") @QueryParam(Constants.SCAN_COLUMN) List<String> column, @DefaultValue("1") @QueryParam(Constants.SCAN_MAX_VERSIONS) int maxVersions, @DefaultValue("-1") @QueryParam(Constants.SCAN_BATCH_SIZE) int batchSize, @DefaultValue("0") @QueryParam(Constants.SCAN_START_TIME) long startTime, @DefaultValue(Long.MAX_VALUE + "") @QueryParam(Constants.SCAN_END_TIME) long endTime, @DefaultValue("true") @QueryParam(Constants.SCAN_BATCH_SIZE) boolean cacheBlocks) {
    servlet.getMetrics().incrementRequests(1);
    try {
        int fetchSize = this.servlet.getConfiguration().getInt(Constants.SCAN_FETCH_SIZE, 10);
        ProtobufStreamingUtil stream = new ProtobufStreamingUtil(this.results, contentType, userRequestedLimit, fetchSize);
        servlet.getMetrics().incrementSucessfulScanRequests(1);
        ResponseBuilder response = Response.ok(stream);
        response.header("content-type", contentType);
        return response.build();
    } catch (Exception exp) {
        servlet.getMetrics().incrementFailedScanRequests(1);
        processException(exp);
        LOG.warn(exp);
        return null;
    }
}
Example 65
Project: iot-server-appliances-master  File: DeviceControllerService.java View source code
@Path("/pushdata/{owner}/{type}/{id}/{time}/{key}/{value}")
@POST
public static // @Produces("application/xml")
String pushData(@PathParam("owner") String owner, @PathParam("type") String deviceType, @PathParam("id") String deviceId, @PathParam("time") Long time, @PathParam("key") String key, @PathParam("value") String value, @HeaderParam("description") String description, @Context HttpServletResponse response) {
    HashMap<String, String> deviceDataMap = new HashMap<String, String>();
    deviceDataMap.put("owner", owner);
    deviceDataMap.put("deviceType", deviceType);
    deviceDataMap.put("deviceId", deviceId);
    deviceDataMap.put("time", "" + time);
    deviceDataMap.put("key", key);
    deviceDataMap.put("value", value);
    deviceDataMap.put("description", description);
    //DeviceValidator deviceChecker = new DeviceValidator();
    //DeviceIdentifier dId = new DeviceIdentifier();
    //dId.setId(deviceId);
    //dId.setType(deviceType);
    //		try {
    //			boolean exists = deviceChecker.isExist(owner, dId);
    String result = null;
    //			if (exists) {
    try {
        iotDataStore.publishIoTData(deviceDataMap);
        response.setStatus(HttpStatus.SC_ACCEPTED);
        result = "Data Published Succesfully...";
    } catch (DeviceControllerServiceException e) {
        response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
        result = "Failed to push " + description + " data to dataStore at " + dataStoreConfig.getEndPoint() + ":" + dataStoreConfig.getPort();
    }
    //
    return result;
//
//		} catch (InstantiationException e) {
//			response.setStatus(500);
//			return null;
//		} catch (IllegalAccessException e) {
//			response.setStatus(500);
//			return null;
//		} catch (ConfigurationException e) {
//			response.setStatus(500);
//			return null;
//		} catch (DeviceCloudException e) {
//			response.setStatus(500);
//			return null;
//		}
}
Example 66
Project: jersey-master  File: ItemStoreResource.java View source code
/**
     * Connect or re-connect to SSE event stream.
     *
     * @param lastEventId Value of custom SSE HTTP <tt>{@value SseFeature#LAST_EVENT_ID_HEADER}</tt> header.
     *                    Defaults to {@code -1} if not set.
     * @return new SSE event output stream representing the (re-)established SSE client connection.
     * @throws InternalServerErrorException in case replaying missed events to the reconnected output stream fails.
     * @throws ServiceUnavailableException  in case the reconnect delay is set to a positive value.
     */
@GET
@Path("events")
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput itemEvents(@HeaderParam(SseFeature.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastEventId) {
    final EventOutput eventOutput = new EventOutput();
    if (lastEventId >= 0) {
        LOGGER.info("Received last event id :" + lastEventId);
        // decide the reconnect handling strategy based on current reconnect delay value.
        final long delay = reconnectDelay;
        if (delay > 0) {
            LOGGER.info("Non-zero reconnect delay [" + delay + "] - responding with HTTP 503.");
            throw new ServiceUnavailableException(delay);
        } else {
            LOGGER.info("Zero reconnect delay - reconnecting.");
            replayMissedEvents(lastEventId, eventOutput);
        }
    }
    if (!broadcaster.add(eventOutput)) {
        LOGGER.severe("!!! Unable to add new event output to the broadcaster !!!");
        // let's try to force a 5s delayed client reconnect attempt
        throw new ServiceUnavailableException(5L);
    }
    return eventOutput;
}
Example 67
Project: keycloak-master  File: ClientsManagementService.java View source code
/**
     * URL invoked by adapter to register new client cluster node. Each application cluster node will invoke this URL once it joins cluster
     *
     * @param authorizationHeader
     * @param formData
     * @return
     */
@Path("register-node")
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response registerNode(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader, final MultivaluedMap<String, String> formData) {
    if (!checkSsl()) {
        throw new ForbiddenException("HTTPS required");
    }
    event.event(EventType.REGISTER_NODE);
    if (!realm.isEnabled()) {
        event.error(Errors.REALM_DISABLED);
        throw new UnauthorizedException("Realm not enabled");
    }
    ClientModel client = authorizeClient();
    String nodeHost = getClientClusterHost(formData);
    event.client(client).detail(Details.NODE_HOST, nodeHost);
    logger.debugf("Registering cluster host '%s' for client '%s'", nodeHost, client.getClientId());
    client.registerNode(nodeHost, Time.currentTime());
    event.success();
    return Response.noContent().build();
}
Example 68
Project: killbill-meter-plugin-master  File: MeterResource.java View source code
@POST
@Path("/{source:" + STRING_PATTERN + "}/{categoryName:" + STRING_PATTERN + "}/{metricName:" + STRING_PATTERN + "}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response recordUsage(@PathParam("source") final String source, @PathParam("categoryName") final String categoryName, @PathParam("metricName") final String metricName, @QueryParam(QUERY_METER_WITH_CATEGORY_AGGREGATE) @DefaultValue("false") final Boolean withAggregate, @QueryParam(QUERY_METER_TIMESTAMP) final String timestampString, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final HttpServletRequest request) {
    final CallContext callContext = createContext(createdBy, reason, comment, request);
    final DateTime timestamp;
    if (timestampString == null) {
        timestamp = clock.getUTCNow();
    } else {
        timestamp = DATE_TIME_FORMATTER.parseDateTime(timestampString);
    }
    if (withAggregate) {
        meterApi.incrementUsageAndAggregate(source, categoryName, metricName, timestamp, callContext);
    } else {
        meterApi.incrementUsage(source, categoryName, metricName, timestamp, callContext);
    }
    return Response.ok().build();
}
Example 69
Project: linshare-core-master  File: UploadRequestRestServiceImpl.java View source code
@GET
@Path("/{uuid}")
@ApiOperation(value = "Find an upload request.", response = UploadRequestDto.class)
@ApiResponses({ @ApiResponse(code = 403, message = "Authentication failed.") })
@Override
public Response find(@PathParam(value = "uuid") String uuid, @HeaderParam("linshare-uploadrequest-password") String password) throws BusinessException {
    logger.debug("uuid : " + uuid);
    logger.debug("password : " + password);
    UploadRequestDto data = uploadRequestUrlFacade.find(uuid, password);
    ResponseBuilder response = Response.ok(data);
    // Fixing IE cache issue.
    CacheControl cc = new CacheControl();
    cc.setNoCache(true);
    response.cacheControl(cc);
    return response.build();
}
Example 70
Project: MaritimeCloudPortalTestbed-master  File: UserResource.java View source code
// -------------------------------------------------------
// -------------------------------------------------------
// Commands
// -------------------------------------------------------
// -------------------------------------------------------
@POST
@Consumes(APPLICATION_JSON_CQRS_COMMAND)
@Produces(MediaType.APPLICATION_JSON)
public //@Path("register")
void registerUserPostCommand(@HeaderParam("Content-type") String contentType, @QueryParam("command") @DefaultValue("") String queryCommandName, String commandJSON) {
    LOG.info("User POST command");
    if (identityIsEmpty(commandJSON, contentType)) {
        LOG.info("Empty userId -> AUTO creating UUID. Got:");
        LOG.info("JSON: " + commandJSON);
        commandJSON = overwriteIdentity(commandJSON, "userId", UUID.randomUUID().toString());
    }
    sendAndWait(contentType, queryCommandName, commandJSON, RegisterUser.class);
}
Example 71
Project: MIFOSX-master  File: ImagesApiResource.java View source code
/**
     * Upload images through multi-part form upload
     */
@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Produces({ MediaType.APPLICATION_JSON })
public String addNewClientImage(@PathParam("entity") final String entityName, @PathParam("entityId") final Long entityId, @HeaderParam("Content-Length") final Long fileSize, @FormDataParam("file") final InputStream inputStream, @FormDataParam("file") final FormDataContentDisposition fileDetails, @FormDataParam("file") final FormDataBodyPart bodyPart) {
    validateEntityTypeforImage(entityName);
    // TODO: vishwas might need more advances validation (like reading magic
    // number) for handling malicious clients
    // and clients not setting mime type
    ContentRepositoryUtils.validateClientImageNotEmpty(fileDetails.getFileName());
    ContentRepositoryUtils.validateImageMimeType(bodyPart.getMediaType().toString());
    final CommandProcessingResult result = this.imageWritePlatformService.saveOrUpdateImage(entityName, entityId, fileDetails.getFileName(), inputStream, fileSize);
    return this.toApiJsonSerializer.serialize(result);
}
Example 72
Project: nuxeo-filesystem-connectors-master  File: VirtualFolderResource.java View source code
@PROPFIND
public Response propfind(@Context UriInfo uriInfo, @HeaderParam("depth") String depth) {
    if (depth == null) {
        depth = "1";
    }
    Date lastModified = new Date();
    Date creationDate = new Date();
    @SuppressWarnings("deprecation") final net.java.dev.webdav.jaxrs.xml.elements.Response response = new net.java.dev.webdav.jaxrs.xml.elements.Response(new HRef(uriInfo.getRequestUri()), null, null, null, new PropStat(new Prop(new DisplayName("nuxeo"), /*
                                                                                                                      * @
                                                                                                                      * TODO
                                                                                                                      * :
                                                                                                                      * fix
                                                                                                                      * this
                                                                                                                      * .
                                                                                                                      * Hardcoded
                                                                                                                      * root
                                                                                                                      * name
                                                                                                                      */
    new LockDiscovery(), new SupportedLock(), new IsFolder("t"), new IsCollection(Integer.valueOf(1)), new IsHidden(Integer.valueOf(0)), new GetContentType("application/octet-stream"), new GetContentLength(0), new CreationDate(creationDate), new GetLastModified(lastModified), COLLECTION), new Status(OK)));
    if (depth.equals("0")) {
        return Response.status(207).entity(new MultiStatus(response)).build();
    }
    List<net.java.dev.webdav.jaxrs.xml.elements.Response> responses = new ArrayList<net.java.dev.webdav.jaxrs.xml.elements.Response>();
    responses.add(response);
    for (String name : rootFolderNames) {
        lastModified = new Date();
        creationDate = new Date();
        PropStatBuilderExt props = new PropStatBuilderExt();
        props.lastModified(lastModified).creationDate(creationDate).displayName(name).status(OK);
        props.isCollection();
        PropStat found = props.build();
        net.java.dev.webdav.jaxrs.xml.elements.Response childResponse;
        URI childUri = uriInfo.getRequestUriBuilder().path(name).build();
        childResponse = new net.java.dev.webdav.jaxrs.xml.elements.Response(new HRef(childUri), null, null, null, found);
        responses.add(childResponse);
    }
    MultiStatus st = new MultiStatus(responses.toArray(new net.java.dev.webdav.jaxrs.xml.elements.Response[responses.size()]));
    return Response.status(207).entity(st).build();
}
Example 73
Project: opencast-master  File: AbstractAssetManagerRestEndpoint.java View source code
@GET
@Path("assets/{mediaPackageID}/{mediaPackageElementID}/{version}/{filenameIgnore}")
@RestQuery(name = "getAsset", description = "Get an asset", returnDescription = "The file", pathParameters = { @RestParameter(name = "mediaPackageID", description = "the media package identifier", isRequired = true, type = STRING), @RestParameter(name = "mediaPackageElementID", description = "the media package element identifier", isRequired = true, type = STRING), @RestParameter(name = "version", description = "the media package version", isRequired = true, type = STRING), @RestParameter(name = "filenameIgnore", description = "a descriptive filename which will be ignored though", isRequired = false, type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "File returned"), @RestResponse(responseCode = SC_NOT_FOUND, description = "Not found") })
public Response getAsset(@PathParam("mediaPackageID") final String mediaPackageID, @PathParam("mediaPackageElementID") final String mediaPackageElementID, @PathParam("version") final String version, @HeaderParam("If-None-Match") final String ifNoneMatch) {
    return handleException(new P1Lazy<Response>() {

        @Override
        public Response get1() {
            if (StringUtils.isNotBlank(ifNoneMatch)) {
                return Response.notModified().build();
            }
            for (final Version v : getAssetManager().toVersion(version)) {
                for (Asset asset : getAssetManager().getAsset(v, mediaPackageID, mediaPackageElementID)) {
                    final String fileName = mediaPackageElementID.concat(".").concat(asset.getMimeType().bind(suffix).getOr("unknown"));
                    asset.getMimeType().map(MimeTypeUtil.Fns.toString);
                    // Write the file contents back
                    return ok(asset.getInputStream(), Option.fromOpt(asset.getMimeType().map(MimeTypeUtil.Fns.toString)), asset.getSize() > 0 ? Option.some(asset.getSize()) : Option.<Long>none(), Option.some(fileName));
                }
                // none
                return notFound();
            }
            // cannot parse version
            return badRequest("malformed version");
        }
    });
}
Example 74
Project: phresco-master  File: PhrescoService.java View source code
@POST
@Produces("application/zip")
@Consumes(MediaType.APPLICATION_JSON)
public StreamingOutput createProject(ProjectInfo projectInfo) throws PhrescoException, IOException {
    //	    ,@HeaderParam(Constants.AUTH_TOKEN) String token
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method PhrescoService.createProject(ProjectInfo projectInfo)");
    }
    String token = "";
    System.out.println("createProject in PhrescoService::token:::" + token);
    authUtil = AuthenticationUtil.getInstance();
    //		if(StringUtils.isEmpty(token) || !authUtil.isValidToken(token)) {
    //			 S_LOGGER.error("Invalid Token");
    //			 throw new UnauthorizedException("Invalid Token or Token Expired");
    //		}
    String projectPathStr = "";
    File projectPath = null;
    try {
        if (isDebugEnabled) {
            S_LOGGER.debug("createProject() ProjectInfo=" + projectInfo.getCode());
        }
        ProjectService projectService = ProjectServiceFactory.getNewProjectService(projectInfo);
        projectPath = projectService.createProject(projectInfo);
        projectPathStr = projectPath.getPath();
        if (isDebugEnabled) {
            S_LOGGER.debug("Project Path = " + projectPathStr);
        }
        ArchiveUtil.createArchive(projectPathStr, projectPathStr + ".zip", ArchiveType.ZIP);
        //			FileUtil.delete(projectPath);
        return new ServiceOutput(projectPathStr);
    } catch (Exception pe) {
        S_LOGGER.error("Error During createProject(projectInfo)", pe);
        throw new PhrescoException(pe);
    }
}
Example 75
Project: Prendamigo-master  File: DefectResource.java View source code
/**
     * Updates defect.
     * <p>
     * The defect is updated only if the If-Match header is present and
     * evaluation of precondition succeeds. This is done to ensure the OCC.
     */
@PUT
@Path(DEFECT_URL)
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response updateDefect(@Context Request request, @PathParam(DEFECT) String defectId, @HeaderParam(HttpHeaders.IF_MATCH) String ifMatchHeader, DefectBean updatedBean) throws IOException {
    if (ifMatchHeader == null) {
        // IF-MATCH header wasn't sent, cannot validate the precondition
        throw new WebApplicationException(Status.BAD_REQUEST);
    }
    // obtain data object from the memory store
    DefectBean bean = store.getDefect(defectId);
    if (bean == null) {
        // not found, return 404
        throw new WebApplicationException(Status.NOT_FOUND);
    }
    // create defect's etag
    EntityTag defectBeanEtag = new EntityTag(String.valueOf(bean.hashCode()));
    ResponseBuilder preconditions = request.evaluatePreconditions(defectBeanEtag);
    if (preconditions != null) {
        return preconditions.build();
    }
    updatedBean.setId(defectId);
    // update defect legacy bean to the memory store
    store.putDefect(defectId, updatedBean);
    Response response = Response.ok(updatedBean).tag(new EntityTag(String.valueOf(updatedBean.hashCode()))).build();
    return response;
}
Example 76
Project: PressGangCCMSREST-master  File: WebDavResource.java View source code
@GET
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public javax.ws.rs.core.Response get(@Context final UriInfo uriInfo, @Context final HttpServletRequest req, @HeaderParam(WebDavConstants.X_FORWARD_FOR_HEADER) final String xForwardForHeader) {
    final ByteArrayReturnValue stringValueReturn = InternalResource.get(compatibilityManager, WebDavUtils.getRemoteAddress(req, xForwardForHeader), uriInfo);
    if (stringValueReturn.getStatusCode() != javax.ws.rs.core.Response.Status.OK.getStatusCode()) {
        return javax.ws.rs.core.Response.status(stringValueReturn.getStatusCode()).build();
    }
    return javax.ws.rs.core.Response.ok().entity(stringValueReturn.getValue()).build();
}
Example 77
Project: Reminders-master  File: Reminders.java View source code
@PUT
@Path("{reminderid}/image")
@Consumes("image/jpeg")
public void setImage(@PathParam("listid") long listId, @PathParam("reminderid") long reminderId, @HeaderParam("Content-Length") long fileSize, InputStream in) throws IOException {
    Reminder reminder = em.find(Reminder.class, reminderId);
    if (reminder == null || reminder.getList().getId() != listId) {
        throw new NotFoundException();
    }
    // Only admins can update another user's images.
    if (!context.getUserPrincipal().getName().equals(reminder.getList().getOwner().getUsername()) && !context.isUserInRole(Role.ADMINISTRATOR.name())) {
        throw new ForbiddenException();
    }
    // Make sure the file is not larger than the maximum allowed size.
    if (fileSize > 1024 * 1024 * MAX_IMAGE_SIZE_IN_MB) {
        throw new BadRequestException("REMINDER_IMAGE");
    }
    // Save the image. By default, {reminderid}.jpg is used as the filename.
    Files.copy(in, IMAGES_BASE_DIR.resolve(reminder.getId() + ".jpg"), StandardCopyOption.REPLACE_EXISTING);
    reminder.setImage(reminder.getId() + ".jpg");
}
Example 78
Project: restlet-framework-java-master  File: WrapperUtil.java View source code
/**
     * Checks, if the annotations are valid for a runtime environment handled
     * constructor.
     * 
     * @param parameterAnnotations
     * @param parameterType
     * @return
     */
private static boolean checkParameterAnnotation(Annotation[] parameterAnnotations, Class<?> parameterType) {
    if (parameterAnnotations.length == 0) {
        return false;
    }
    for (final Annotation annotation : parameterAnnotations) {
        final Class<? extends Annotation> annotationType = annotation.annotationType();
        if (annotationType.equals(HeaderParam.class)) {
            continue;
        } else if (annotationType.equals(PathParam.class)) {
            continue;
        } else if (annotationType.equals(Context.class)) {
            if (parameterType.equals(UriInfo.class)) {
                continue;
            }
            if (parameterType.equals(Request.class)) {
                continue;
            }
            if (parameterType.equals(HttpHeaders.class)) {
                continue;
            }
            if (parameterType.equals(SecurityContext.class)) {
                continue;
            }
            return false;
        } else if (annotationType.equals(MatrixParam.class)) {
            continue;
        } else if (annotationType.equals(QueryParam.class)) {
            continue;
        }
        return false;
    }
    return true;
}
Example 79
Project: Signal-Server-master  File: AccountController.java View source code
@Timed
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Path("/code/{verification_code}")
public void verifyAccount(@PathParam("verification_code") String verificationCode, @HeaderParam("Authorization") String authorizationHeader, @HeaderParam("X-Signal-Agent") String userAgent, @Valid AccountAttributes accountAttributes) throws RateLimitExceededException {
    try {
        AuthorizationHeader header = AuthorizationHeader.fromFullHeader(authorizationHeader);
        String number = header.getNumber();
        String password = header.getPassword();
        rateLimiters.getVerifyLimiter().validate(number);
        Optional<StoredVerificationCode> storedVerificationCode = pendingAccounts.getCodeForNumber(number);
        if (!storedVerificationCode.isPresent() || !storedVerificationCode.get().isValid(verificationCode)) {
            throw new WebApplicationException(Response.status(403).build());
        }
        if (accounts.isRelayListed(number)) {
            throw new WebApplicationException(Response.status(417).build());
        }
        createAccount(number, password, userAgent, accountAttributes);
    } catch (InvalidAuthorizationHeaderException e) {
        logger.info("Bad Authorization Header", e);
        throw new WebApplicationException(Response.status(401).build());
    }
}
Example 80
Project: smart-generator-engine-master  File: ReportConfigResource.java View source code
@POST
@Path("/update")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updatePost(@HeaderParam("Content-type") String contentType, String message) {
    ResponseBuilder responseBuilder = Response.ok();
    if (StringUtils.isBlank(message)) {
        responseBuilder = Response.status(Status.BAD_REQUEST);
        responseBuilder.build();
    }
    try {
        //Will search for the first '=' if not found will take the whole string
        //message.indexOf("=") + 1;
        final int startIndex = 0;
        //Consider the first '=' as the start of a value point and take rest as value
        final String realMsg = message.substring(startIndex);
        //Decode the message to ignore the form encodings and make them human readable
        message = URLDecoder.decode(realMsg, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        System.out.println(ex);
    }
    return responseBuilder.build();
}
Example 81
Project: smart-user-master  File: ProfileResource.java View source code
@POST
@Path("/update")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response updatePost(@HeaderParam("Content-type") String contentType, String message) {
    ResponseBuilder responseBuilder = Response.status(Status.SERVICE_UNAVAILABLE);
    if (StringUtils.isBlank(message)) {
        responseBuilder = Response.status(Status.BAD_REQUEST);
        responseBuilder.build();
    }
    final boolean isHtmlPost;
    if (StringUtils.isBlank(contentType)) {
        contentType = MediaType.APPLICATION_OCTET_STREAM;
        isHtmlPost = false;
    } else if (contentType.equals(MediaType.APPLICATION_FORM_URLENCODED)) {
        contentType = MediaType.APPLICATION_OCTET_STREAM;
        isHtmlPost = true;
        try {
            //Will search for the first '=' if not found will take the whole string
            //message.indexOf("=") + 1;
            final int startIndex = 0;
            //Consider the first '=' as the start of a value point and take rest as value
            final String realMsg = message.substring(startIndex);
            //Decode the message to ignore the form encodings and make them human readable
            message = URLDecoder.decode(realMsg, "UTF-8");
        } catch (UnsupportedEncodingException ex) {
        }
    } else {
        isHtmlPost = false;
    }
    if (isHtmlPost) {
        Person newPerson = getProfileFromContent(message);
        try {
            Services.getInstance().getPersonService().update(newPerson);
            responseBuilder = Response.ok(getProfileFeed());
        } catch (Exception ex) {
            responseBuilder = Response.status(Status.INTERNAL_SERVER_ERROR);
        }
    }
    return responseBuilder.build();
}
Example 82
Project: swagger-core-master  File: DefaultParameterExtension.java View source code
@Override
public List<Parameter> extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Iterator<SwaggerExtension> chain) {
    if (shouldIgnoreType(type, typesToSkip)) {
        return new ArrayList<Parameter>();
    }
    List<Parameter> parameters = new ArrayList<Parameter>();
    Parameter parameter = null;
    for (Annotation annotation : annotations) {
        if (annotation instanceof QueryParam) {
            QueryParam param = (QueryParam) annotation;
            QueryParameter qp = new QueryParameter().name(param.value());
            Property schema = createProperty(type);
            if (schema != null) {
                qp.setProperty(schema);
            }
            parameter = qp;
        } else if (annotation instanceof PathParam) {
            PathParam param = (PathParam) annotation;
            PathParameter pp = new PathParameter().name(param.value());
            Property schema = createProperty(type);
            if (schema != null) {
                pp.setProperty(schema);
            }
            parameter = pp;
        } else if (annotation instanceof HeaderParam) {
            HeaderParam param = (HeaderParam) annotation;
            HeaderParameter hp = new HeaderParameter().name(param.value());
            Property schema = createProperty(type);
            if (schema != null) {
                hp.setProperty(schema);
            }
            parameter = hp;
        } else if (annotation instanceof CookieParam) {
            CookieParam param = (CookieParam) annotation;
            CookieParameter cp = new CookieParameter().name(param.value());
            Property schema = createProperty(type);
            if (schema != null) {
                cp.setProperty(schema);
            }
            parameter = cp;
        } else if (annotation instanceof FormParam) {
            FormParam param = (FormParam) annotation;
            FormParameter fp = new FormParameter().name(param.value());
            Property schema = createProperty(type);
            if (schema != null) {
                fp.setProperty(schema);
            }
            parameter = fp;
        } else {
            handleAdditionalAnnotation(parameters, annotation, type, typesToSkip);
        }
    }
    if (parameter != null) {
        parameters.add(parameter);
    }
    return parameters;
}
Example 83
Project: vitam-master  File: PerformanceResource.java View source code
/**
     * @param model
     * @return
     * @throws InterruptedException
     * @throws FileNotFoundException
     */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response launchPerformanceTest(@HeaderParam(GlobalDataRest.X_TENANT_ID) int tenantId, PerformanceModel model) throws InterruptedException, FileNotFoundException {
    if (performanceService.inProgress()) {
        return Response.accepted().build();
    }
    ParametersChecker.checkParameter("SIP path is a mandatory parameter", model.getFileName());
    if (!performanceService.sipExist(model.getFileName())) {
        LOGGER.error(String.format("SIP path invalid: %s", model.getFileName()));
        return Response.status(Response.Status.PRECONDITION_FAILED).entity("SIP path invalid").build();
    }
    if (model.getNumberOfIngest() == 0) {
        LOGGER.error("number of ingest must be greater than 0");
        return Response.status(Response.Status.PRECONDITION_FAILED).entity("number of ingest must be greater than 0").build();
    }
    if (model.getParallelIngest() == 0) {
        LOGGER.error("number of parallel ingest must be greater than 0");
        return Response.status(Response.Status.PRECONDITION_FAILED).entity("number of parallel ingest must be greater than 0").build();
    }
    String fileName = format("report_%s.csv", LocalDateTime.now().format(DATE_TIME_FORMATTER));
    performanceTestLauncher.submit(() -> {
        try {
            performanceService.launchPerformanceTest(model, fileName, tenantId);
        } catch (IOException e) {
            LOGGER.error("unable to launch performance test", e);
        }
    });
    return Response.accepted(fileName).build();
}
Example 84
Project: Wink-master  File: DefectResource.java View source code
/**
     * Updates defect.
     * <p>
     * The defect is updated only if the If-Match header is present and
     * evaluation of precondition succeeds. This is done to ensure the OCC.
     */
@PUT
@Path(DEFECT_URL)
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response updateDefect(@Context Request request, @PathParam(DEFECT) String defectId, @HeaderParam(HttpHeaders.IF_MATCH) String ifMatchHeader, DefectBean updatedBean) throws IOException {
    if (ifMatchHeader == null) {
        // IF-MATCH header wasn't sent, cannot validate the precondition
        throw new WebApplicationException(Status.BAD_REQUEST);
    }
    // obtain data object from the memory store
    DefectBean bean = store.getDefect(defectId);
    if (bean == null) {
        // not found, return 404
        throw new WebApplicationException(Status.NOT_FOUND);
    }
    // create defect's etag
    EntityTag defectBeanEtag = new EntityTag(String.valueOf(bean.hashCode()));
    ResponseBuilder preconditions = request.evaluatePreconditions(defectBeanEtag);
    if (preconditions != null) {
        return preconditions.build();
    }
    updatedBean.setId(defectId);
    // update defect legacy bean to the memory store
    store.putDefect(defectId, updatedBean);
    Response response = Response.ok(updatedBean).tag(new EntityTag(String.valueOf(updatedBean.hashCode()))).build();
    return response;
}
Example 85
Project: YiDB-master  File: BranchResource.java View source code
@GET
public CMSResponse getMainBranches(@Context UriInfo uriInfo, @HeaderParam("X-CMS-PRIORITY") final String priority, @HeaderParam("X-CMS-CONSISTENCY") final String consistPolicy, @PathParam("reponame") String reponame, @Context HttpServletRequest request) {
    CMSPriority p = CMSResourceUtils.parsePriority(priority);
    CMSResponse response = new CMSResponse();
    ConsistentPolicy policy = CMSResourceUtils.parsePolicy(cmsServer, consistPolicy);
    try {
        EntityContext context = createContext(uriInfo, request, policy);
        List<IBranch> branches = cmsServer.getMainBranches(p, reponame, context);
        if (branches == null) {
            branches = Collections.emptyList();
        }
        response.addProperty("count", branches.size());
        response.addResult(branches);
        return response;
    } catch (Throwable e) {
        logger.error("exception while list branches on repository " + reponame, e);
        convertExceptionAndReThrow(e);
        return null;
    }
}
Example 86
Project: zen-project-master  File: HyperApiWsSkelton.java View source code
private Object[] createArgs(Obj uriParams, HttpEntity entity, Class<?> api2, Method method) throws IOException {
    List<NameValuePair> formParams = Collections.emptyList();
    if (entity != null) {
        formParams = HTTP.parseEntityWithDefaultUtf8(entity);
    }
    Class<?>[] parameterTypes = method.getParameterTypes();
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    Object[] args = new Object[parameterTypes.length];
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> parameterType = parameterTypes[i];
        Annotation[] annotations = parameterAnnotations[i];
        AnnotatedType p = new AnnotatedType(parameterType, annotations);
        boolean annotationFound = false;
        for (Annotation annotation : annotations) {
            if (annotation instanceof HeaderParam) {
            // TODO
            } else if (annotation instanceof PathParam) {
                annotationFound = true;
                Object o = JPATH.getPathSafe(uriParams, ((PathParam) annotation).value());
                args[i] = decast(o, parameterType);
                break;
            } else if (annotation instanceof QueryParam) {
                annotationFound = true;
                Object o = JPATH.getPathSafe(uriParams, ((QueryParam) annotation).value());
                args[i] = decast(o, parameterType);
                break;
            } else if (annotation instanceof FormParam) {
                annotationFound = true;
                if (Obj.class.equals(parameterType)) {
                    args[i] = HTTP.toStru(formParams).asObj();
                } else if (parameterType.isInterface() && ObjWrapper.class.isAssignableFrom(parameterType)) {
                    args[i] = WF.wrap(HTTP.toStru(formParams).asObj(), parameterType);
                } else {
                    Object o = getFormParams(formParams, ((FormParam) annotation).value());
                    args[i] = decast(o, parameterType);
                }
                break;
            }
        }
        if (!annotationFound) {
            if (entity == null) {
                args[i] = null;
            } else /* else if(parameterType.isInterface() && ObjWrapper.class.isAssignableFrom(parameterType)) {
					args[i] = WF.wrap((ObjWrapper)entityCodec.decode(entity, p), parameterType);
				}*/
            {
                args[i] = entityCodec.decode(entity, p);
            }
        }
    }
    return args;
}
Example 87
Project: alexandria-master  File: WebAnnotationsEndpoint.java View source code
@POST
@Consumes(JSONLD_MEDIATYPE)
@Produces(JSONLD_MEDIATYPE)
public //
Response addWebAnnotation(//
@HeaderParam("Accept") String acceptHeader, //
WebAnnotationPrototype prototype) {
    String expectedProfile = extractProfile(acceptHeader);
    prototype.setCreated(Instant.now().toString());
    WebAnnotation webAnnotation = webAnnotationService.validateAndStore(prototype);
    String profiledWebAnnotation = profile(webAnnotation.json(), expectedProfile);
    return //
    Response.created(webAnnotationService.webAnnotationURI(webAnnotation.getId())).link(RESOURCE_TYPE_URI, //
    "type").link(ANNOTATION_TYPE_URI, //
    "type").tag(//
    webAnnotation.eTag()).allow(//
    ALLOWED_METHODS).entity(//
    profiledWebAnnotation).build();
}
Example 88
Project: candlepin-master  File: ResourceLocatorMap.java View source code
/**
     * Log what resources have been detected and warn about missing media types.
     *
     * Not having a @Produces annotation on a method can have subtle effects on the way Resteasy
     * resolves which method to dispatch a request to.
     *
     * Resource resolution order is detailed in the JAX-RS 2.0 specification in section 3.7.2.
     * Consider the following
     *
     *   @PUT
     *   @Path("/foo")
     *   public String methodOne() {
     *       ...
     *   }
     *
     *   @PUT
     *   @Path("/{id}")
     *   @Produces(MediaType.APPLICATION_JSON)
     *   public String methodTwo(@PathParam("id") String id) {
     *       ....
     *   }
     *
     *   With a cursory reading of the specification, it appears that a request to
     *
     *   PUT /foo
     *
     *   should result in methodOne being selected since methodOne's Path has more
     *   literal characters than methodTwo.  However, methodTwo has a specific media
     *   type defined and methodOne does not (thus using the wildcard type as a default),
     *   methodTwo is actually the resource selected.
     *
     *   The same rules apply for @Consumes annotations.
     */
protected void logLocators() {
    StringBuffer registered = new StringBuffer("Registered the following RESTful methods:\n");
    StringBuffer missingProduces = new StringBuffer();
    StringBuffer missingConsumes = new StringBuffer();
    for (Method m : keySet()) {
        String name = m.getDeclaringClass() + "." + m.getName();
        registered.append("\t" + name + "\n");
        if (!m.isAnnotationPresent(Produces.class)) {
            missingProduces.append("\t" + name + "\n");
        }
        if (m.isAnnotationPresent(GET.class) || m.isAnnotationPresent(HEAD.class) || m.isAnnotationPresent(DELETE.class) || m.isAnnotationPresent(Deprecated.class)) {
            /* Technically GET, HEAD, and DELETE are allowed to have bodies (and therefore would
                 * need a Consumes annotation, but the HTTP 1.1 spec states in section 4.3 that any
                 * such body should be ignored.  See http://stackoverflow.com/a/983458/6124862
                 *
                 * Therefore, we won't print warnings on unannotated GET, HEAD, and DELETE methods.
                 *
                 * Deprecated methods are not expected to be updated.
                 */
            continue;
        }
        if (!m.isAnnotationPresent(Consumes.class)) {
            missingConsumes.append("\t" + name + "\n");
        } else {
            /* The purpose of all the ridiculousness below is to find methods that
                 * bind objects from the HTTP request body but that are marked as consuming
                 * the star slash star wildcard mediatype.  Candlepin only consumes JSON
                 * at the moment but even if that changes we still want to be explicit
                 * about what we accept.
                 */
            Consumes consumes = m.getAnnotation(Consumes.class);
            List<String> mediaTypes = Arrays.asList(consumes.value());
            if (mediaTypes.contains(MediaType.WILDCARD)) {
                Annotation[][] allParamAnnotations = m.getParameterAnnotations();
                boolean bindsBody = false;
                for (Annotation[] paramAnnotations : allParamAnnotations) {
                    boolean boundObjectFromBody = true;
                    for (Annotation a : paramAnnotations) {
                        Class<? extends Annotation> clazz = a.annotationType();
                        if (QueryParam.class.isAssignableFrom(clazz) || PathParam.class.isAssignableFrom(clazz) || MatrixParam.class.isAssignableFrom(clazz) || HeaderParam.class.isAssignableFrom(clazz) || FormParam.class.isAssignableFrom(clazz) || CookieParam.class.isAssignableFrom(clazz)) {
                            boundObjectFromBody = false;
                            continue;
                        }
                    }
                    bindsBody = bindsBody || boundObjectFromBody;
                }
                if (bindsBody) {
                    log.warn("{} consumes a wildcard media type but binds an object from" + " the request body.  Define specific media types consumed instead.", name);
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.trace(registered.toString());
    }
    if (missingProduces.length() != 0) {
        log.warn("The following methods are missing a Produces annotation:\n{}", missingProduces);
    }
    if (missingConsumes.length() != 0) {
        log.warn("The following methods are missing a Consumes annotation:\n{}", missingConsumes);
    }
}
Example 89
Project: resource-manager-master  File: StudioRest.java View source code
@Override
public ArrayList<String> getClasses(@HeaderParam("sessionid") String sessionId) throws NotConnectedRestException {
    String userName = getUserName(sessionId);
    File classesDir = new File(getFileStorageSupport().getWorkflowsDir(userName), "classes");
    ArrayList<String> classes = new ArrayList<>();
    if (classesDir.exists()) {
        File[] jars = classesDir.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".jar");
            }
        });
        for (File jar : jars) {
            try {
                JarFile jarFile = new JarFile(jar.getAbsolutePath());
                Enumeration allEntries = jarFile.entries();
                while (allEntries.hasMoreElements()) {
                    JarEntry entry = (JarEntry) allEntries.nextElement();
                    String name = entry.getName();
                    if (name.endsWith(".class")) {
                        String noExt = name.substring(0, name.length() - ".class".length());
                        classes.add(noExt.replaceAll("/", "."));
                    }
                }
            } catch (IOException e) {
                logger.warn("Could not read jar file " + jar, e);
            }
        }
    }
    return classes;
}
Example 90
Project: scheduling-master  File: StudioRest.java View source code
@Override
public ArrayList<String> getClasses(@HeaderParam("sessionid") String sessionId) throws NotConnectedRestException {
    String userName = getUserName(sessionId);
    File classesDir = new File(getFileStorageSupport().getWorkflowsDir(userName), "classes");
    ArrayList<String> classes = new ArrayList<>();
    if (classesDir.exists()) {
        File[] jars = classesDir.listFiles(new FilenameFilter() {

            public boolean accept(File dir, String name) {
                return name.toLowerCase().endsWith(".jar");
            }
        });
        for (File jar : jars) {
            try {
                JarFile jarFile = new JarFile(jar.getAbsolutePath());
                Enumeration allEntries = jarFile.entries();
                while (allEntries.hasMoreElements()) {
                    JarEntry entry = (JarEntry) allEntries.nextElement();
                    String name = entry.getName();
                    if (name.endsWith(".class")) {
                        String noExt = name.substring(0, name.length() - ".class".length());
                        classes.add(noExt.replaceAll("/", "."));
                    }
                }
            } catch (IOException e) {
                logger.warn("Could not read jar file " + jar, e);
            }
        }
    }
    return classes;
}
Example 91
Project: sinkit-core-master  File: ProtostreamREST.java View source code
/**
     * @returns huge byte array Protocol Buffer with custom list records
     */
@GET
@Path("/protostream/customlist")
@Produces({ "application/x-protobuf" })
public Response getProtostreamCustomList(@HeaderParam(CLIENT_ID_HEADER_PARAM) Integer clientId) {
    if (SINKIT_CUSTOMLIST_PROTOSTREAM_GENERATOR_D_H_M_S == null) {
        return Response.status(Response.Status.NOT_FOUND).header(X_ERROR, "This is a wrong node. Protostream generator is not started.").build();
    }
    if (clientId == null || clientId < 0) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).header(X_ERROR, CLIENT_ID_HEADER_PARAM + " seems to be invalid or missing").build();
    }
    final File customListBinary = new File(customListFilePath + clientId);
    final File customlistBinaryMD5 = new File(customListFileMd5 + clientId);
    if (customListBinary.exists() && customlistBinaryMD5.exists()) {
        InputStream is;
        String md5sum;
        try {
            is = new FileInputStream(customListBinary);
            md5sum = new String(Files.readAllBytes(customlistBinaryMD5.toPath()), StandardCharsets.UTF_8);
        } catch (FileNotFoundException e) {
            log.log(Level.SEVERE, customListFilePath + clientId + " not found.");
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).header(X_ERROR, customListFilePath + clientId + " not found.").build();
        } catch (IOException e) {
            log.log(Level.SEVERE, customListFileMd5 + clientId + " not found.");
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).header(X_ERROR, customListFileMd5 + clientId + " not found.").build();
        }
        return Response.ok().entity(is).header(X_FILE_LENGTH, String.valueOf(customListBinary.length())).header(X_FILE_MD5, md5sum).build();
    } else {
        // If any other file is generated, it means the generator cycle already passed, but there are no data for this particular client ID
        try (DirectoryStream<java.nio.file.Path> someFiles = Files.newDirectoryStream(Paths.get(GENERATED_PROTOFILES_DIRECTORY), "ioclist.bin*")) {
            if (someFiles.iterator().hasNext()) {
                customListBinary.createNewFile();
                // The desired behaviour is to return an empty file
                return Response.ok().entity(new FileInputStream(customListBinary)).header(X_FILE_LENGTH, "0").header(X_FILE_MD5, "").build();
            }
        } catch (IOException e) {
            return Response.status(TRY_LATER).header(X_ERROR, "Try later, please.").build();
        }
        return Response.status(TRY_LATER).header(X_ERROR, "Try later, please.").build();
    }
}
Example 92
Project: summaServer-master  File: JerseyService.java View source code
/**
	 * 
	 * 
	 * @param message
	 * @param inputMime, curl standard is application/x-www-form-urlencoded
	 * @param outputMime, standard is everything
	 /** @return
	 *
	 */
@POST
public Response getPost(String message, @HeaderParam("Content-Type") String inputMime, @HeaderParam("Accept") String outputMime) {
    // get formats for MIME types
    RDFFormat inputFormat = Rio.getParserFormatForMIMEType(inputMime);
    RDFFormat outputFormat = Rio.getParserFormatForMIMEType(outputMime.split(",")[0]);
    if (inputFormat == null) {
    // TODO
    // method which detects the format
    // if Format could not be detected leave method and return error 
    }
    if (outputFormat == null) {
        outputFormat = RDFFormat.TURTLE;
    }
    try {
        Model model = Rio.parse(new StringReader(message), "", inputFormat);
        ValueFactory f = ValueFactoryImpl.getInstance();
        String entity = model.filter(null, f.createURI(ENTITY), null).objectURI().stringValue();
        Integer topK = Integer.parseInt(model.filter(null, f.createURI(TOP_K), null).objectValue().stringValue());
        Model maxHopsMod = model.filter(null, f.createURI(MAX_HOPS), null);
        Integer maxHops = null;
        if (!maxHopsMod.isEmpty()) {
            maxHops = Integer.parseInt(maxHopsMod.objectValue().stringValue());
        }
        String language = null;
        Model languageMod = model.filter(null, f.createURI(LANGUAGE), null);
        if (!languageMod.isEmpty()) {
            language = languageMod.objectValue().stringValue();
        }
        Model m = model.filter(null, f.createURI(FIXED_PROPERTY), null);
        Set<Value> objects = m.objects();
        Iterator<Value> val = objects.iterator();
        String[] fixedProperties = new String[objects.size()];
        for (int i = 0; i < fixedProperties.length; i++) {
            fixedProperties[i] = val.next().stringValue();
        }
        return executeQuery(entity, topK, maxHops, fixedProperties, language, outputFormat);
    } catch (RDFParseException e) {
        e.printStackTrace();
    } catch (UnsupportedRDFormatException e) {
        e.printStackTrace();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 93
Project: tuscany-sca-2.x-master  File: RESTBindingInvoker.java View source code
public Message invoke(Message msg) {
    Object entity = null;
    Object[] args = msg.getBody();
    URI uri = URI.create(binding.getURI());
    UriBuilder uriBuilder = UriBuilder.fromUri(uri);
    Method method = ((JavaOperation) operation).getJavaMethod();
    if (method.isAnnotationPresent(Path.class)) {
        // Only for resource method
        uriBuilder.path(method);
    }
    if (!JAXRSHelper.isResourceMethod(method)) {
        // This is RPC over GET
        uriBuilder.replaceQueryParam("method", method.getName());
    }
    Map<String, Object> pathParams = new HashMap<String, Object>();
    Map<String, Object> matrixParams = new HashMap<String, Object>();
    Map<String, Object> queryParams = new HashMap<String, Object>();
    Map<String, Object> headerParams = new HashMap<String, Object>();
    Map<String, Object> formParams = new HashMap<String, Object>();
    Map<String, Object> cookieParams = new HashMap<String, Object>();
    for (int i = 0; i < method.getParameterTypes().length; i++) {
        boolean isEntity = true;
        Annotation[] annotations = method.getParameterAnnotations()[i];
        PathParam pathParam = getAnnotation(annotations, PathParam.class);
        if (pathParam != null) {
            isEntity = false;
            pathParams.put(pathParam.value(), args[i]);
        }
        MatrixParam matrixParam = getAnnotation(annotations, MatrixParam.class);
        if (matrixParam != null) {
            isEntity = false;
            matrixParams.put(matrixParam.value(), args[i]);
        }
        QueryParam queryParam = getAnnotation(annotations, QueryParam.class);
        if (queryParam != null) {
            isEntity = false;
            queryParams.put(queryParam.value(), args[i]);
        }
        HeaderParam headerParam = getAnnotation(annotations, HeaderParam.class);
        if (headerParam != null) {
            isEntity = false;
            headerParams.put(headerParam.value(), args[i]);
        }
        FormParam formParam = getAnnotation(annotations, FormParam.class);
        if (formParam != null) {
            isEntity = false;
            formParams.put(formParam.value(), args[i]);
        }
        CookieParam cookieParam = getAnnotation(annotations, CookieParam.class);
        if (cookieParam != null) {
            isEntity = false;
            cookieParams.put(cookieParam.value(), args[i]);
        }
        if (isEntity) {
            entity = args[i];
        }
    }
    for (Map.Entry<String, Object> p : queryParams.entrySet()) {
        uriBuilder.replaceQueryParam(p.getKey(), p.getValue());
    }
    for (Map.Entry<String, Object> p : matrixParams.entrySet()) {
        uriBuilder.replaceMatrixParam(p.getKey(), p.getValue());
    }
    uri = uriBuilder.buildFromMap(pathParams);
    Resource resource = restClient.resource(uri);
    for (Map.Entry<String, Object> p : headerParams.entrySet()) {
        resource.header(p.getKey(), String.valueOf(p.getValue()));
    }
    for (Map.Entry<String, Object> p : cookieParams.entrySet()) {
        Cookie cookie = new Cookie(p.getKey(), String.valueOf(p.getValue()));
        resource.cookie(cookie);
    }
    resource.contentType(getContentType());
    resource.accept(getAccepts());
    //handles declarative headers configured on the composite
    for (HTTPHeader header : binding.getHttpHeaders()) {
        //treat special headers that need to be calculated
        if (header.getName().equalsIgnoreCase("Expires")) {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(new Date());
            calendar.add(Calendar.HOUR, Integer.parseInt(header.getValue()));
            resource.header("Expires", HTTPCacheContext.RFC822DateFormat.format(calendar.getTime()));
        } else {
            //default behaviour to pass the header value to HTTP response
            resource.header(header.getName(), header.getValue());
        }
    }
    Object result = resource.invoke(httpMethod, responseType, entity);
    msg.setBody(result);
    return msg;
}
Example 94
Project: typescript-generator-master  File: JaxrsApplicationParser.java View source code
private static MethodParameterModel getEntityParameter(Method method) {
    final List<Parameter> parameters = Parameter.ofMethod(method);
    for (Parameter parameter : parameters) {
        if (!hasAnyAnnotation(parameter, Arrays.asList(MatrixParam.class, QueryParam.class, PathParam.class, CookieParam.class, HeaderParam.class, Context.class, FormParam.class))) {
            return new MethodParameterModel(parameter.getName(), parameter.getParameterizedType());
        }
    }
    return null;
}
Example 95
Project: aerogear-unifiedpush-server-master  File: InstallationRegistrationEndpoint.java View source code
/**
     * RESTful API for Device registration.
     * The Endpoint is protected using <code>HTTP Basic</code> (credentials <code>VariantID:secret</code>).
     *
     * <pre>
     * curl -u "variantID:secret"
     *   -v -H "Accept: application/json" -H "Content-type: application/json" -H "aerogear-push-id: someid"
     *   -X POST
     *   -d '{
     *     "deviceToken" : "someTokenString",
     *     "deviceType" : "iPad",
     *     "operatingSystem" : "iOS",
     *     "osVersion" : "6.1.2",
     *     "alias" : "someUsername or email adress...",
     *     "categories" : ["football", "sport"]
     *   }'
     *   https://SERVER:PORT/context/rest/registry/device
     * </pre>
     *
     * Details about JSON format can be found HERE!
     *
     * @param oldToken  The previously registered deviceToken or an empty String.  Provided by the header x-ag-old-token.
     * @param entity    {@link Installation} for Device registration
     * @param request   the request object
     * @return          registered {@link Installation}
     *
     * @requestheader x-ag-old-token the old push service dependant token (ie InstanceID in FCM). If present these tokens will be forcefully unregistered before the new token is registered.
     * 
     * @responseheader Access-Control-Allow-Origin      With host in your "Origin" header
     * @responseheader Access-Control-Allow-Credentials true
     * @responseheader WWW-Authenticate Basic realm="AeroGear UnifiedPush Server" (only for 401 response)
     *
     * @statuscode 200 Successful storage of the device metadata
     * @statuscode 400 The format of the client request was incorrect (e.g. missing required values)
     * @statuscode 401 The request requires authentication
     */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ReturnType("org.jboss.aerogear.unifiedpush.api.Installation")
public Response registerInstallation(@DefaultValue("") @HeaderParam("x-ag-old-token") final String oldToken, Installation entity, @Context HttpServletRequest request) {
    // find the matching variation:
    final Variant variant = loadVariantWhenAuthorized(request);
    if (variant == null) {
        return create401Response(request);
    }
    // Poor up-front validation for required token
    final String deviceToken = entity.getDeviceToken();
    if (deviceToken == null || !DeviceTokenValidator.isValidDeviceTokenForVariant(deviceToken, variant.getType())) {
        logger.trace(String.format("Invalid device token was delivered: %s for variant type: %s", deviceToken, variant.getType()));
        return appendAllowOriginHeader(Response.status(Status.BAD_REQUEST), request);
    }
    // The 'mobile application' on the device/client was launched.
    // If the installation is already in the DB, let's update the metadata,
    // otherwise we register a new installation:
    logger.trace("Mobile Application on device was launched");
    //The token has changed, remove the old one
    if (!oldToken.isEmpty() && !oldToken.equals(entity.getDeviceToken())) {
        logger.info(String.format("Deleting old device token %s", oldToken));
        clientInstallationService.removeInstallationForVariantByDeviceToken(variant.getVariantID(), oldToken);
    }
    // async:
    clientInstallationService.addInstallation(variant, entity);
    return appendAllowOriginHeader(Response.ok(entity), request);
}
Example 96
Project: alchemy-rest-client-generator-master  File: AlchemyRestClientFactory.java View source code
/*
         * (non-Javadoc)
         * @see javassist.util.proxy.MethodHandler#invoke(java.lang.Object,
         * java.lang.reflect.Method, java.lang.reflect.Method,
         * java.lang.Object[])
         */
@Override
public Object invoke(final Object self, final Method thisMethod, final Method proceed, final Object[] arguments) throws Throwable {
    final RestMethodMetadata methodMetaData = restInterfaceMetadata.getMethodMetaData().get(thisMethod);
    if (methodMetaData == null) {
        throw new NotRestMethodException(thisMethod);
    }
    final String path = getPath(methodMetaData, arguments);
    log.debug("Invoking rest service at {}", path);
    final Client client = clientProvider.get();
    WebTarget webTarget = client.target(path);
    Entity<?> entity = null;
    final Annotation[][] parameterAnnotations = methodMetaData.getParameterAnnotations();
    final String bodyParameterMediaType = methodMetaData.getConsumed().isEmpty() ? null : methodMetaData.getConsumed().get(0);
    // set query params
    for (int i = 0; i < arguments.length; i++) {
        final Object argument = arguments[i];
        if (parameterAnnotations.length <= i) {
            // body parameter without annotation
            entity = toEntity(argument, bodyParameterMediaType);
            continue;
        }
        final Annotation[] annotations = parameterAnnotations[i];
        if (annotations == null || annotations.length == 0) {
            // body parameter without annotation
            entity = toEntity(argument, bodyParameterMediaType);
            continue;
        }
        for (final Annotation annotation : annotations) {
            if (annotation instanceof QueryParam) {
                final String key = ((QueryParam) annotation).value();
                final String value = ObjectUtils.toString(argument);
                webTarget = webTarget.queryParam(key, value);
            }
        }
    }
    // create the request builder
    Builder webRequestBuilder = webTarget.request();
    webRequestBuilder.accept(methodMetaData.getProduced().toArray(new String[0]));
    webRequestBuilder = webRequestBuilder.accept(methodMetaData.getConsumed().toArray(new String[0]));
    if (builderFilter != null) {
        builderFilter.apply(webRequestBuilder);
    }
    // for form params
    Form formParams = null;
    // process cookie and header params
    for (int i = 0; i < arguments.length; i++) {
        if (i >= parameterAnnotations.length) {
            continue;
        }
        final Annotation[] annotations = parameterAnnotations[i];
        final Object argument = arguments[i];
        for (final Annotation annotation : annotations) {
            if (annotation instanceof CookieParam) {
                // add cookie to the request
                Cookie cookie = null;
                if (argument instanceof Cookie) {
                    cookie = (Cookie) argument;
                } else {
                    cookie = new Cookie(((CookieParam) annotation).value(), ObjectUtils.toString(argument));
                }
                webRequestBuilder = webRequestBuilder.cookie(cookie);
            } else if (annotation instanceof HeaderParam) {
                // add header param
                final String key = ((HeaderParam) annotation).value();
                final String value = ObjectUtils.toString(argument);
                webRequestBuilder = webRequestBuilder.header(key, value);
            } else if (annotation instanceof FormParam) {
                if (formParams == null) {
                    formParams = new javax.ws.rs.core.Form();
                }
                formParams.param(((FormParam) annotation).value(), ObjectUtils.toString(argument));
            }
        }
    }
    if (formParams != null) {
        // annotation
        assert entity == null;
        // for form parameters the method should be post
        assert HttpMethod.POST.equals(methodMetaData.getHttpMethod());
        entity = toEntity(formParams, MediaType.APPLICATION_FORM_URLENCODED);
    }
    final FormDataMultiPart formDataMultiPart = processFormDataParams(arguments, parameterAnnotations);
    if (formDataMultiPart != null) {
        // annotation
        assert entity == null;
        // for form parameters the method should be post
        assert HttpMethod.POST.equals(methodMetaData.getHttpMethod());
        entity = toEntity(formDataMultiPart, formDataMultiPart.getMediaType().toString());
    }
    // Get the return type.
    @SuppressWarnings("rawtypes") final GenericType<?> returnType = new GenericType(thisMethod.getGenericReturnType()) {
    };
    try {
        Object retval = null;
        final String httpMethod = methodMetaData.getHttpMethod();
        if (HttpMethod.GET.equals(httpMethod)) {
            retval = webRequestBuilder.get(returnType);
        } else if (HttpMethod.PUT.equals(httpMethod)) {
            retval = webRequestBuilder.put(entity, returnType);
        } else if (HttpMethod.POST.equals(httpMethod)) {
            retval = webRequestBuilder.post(entity, returnType);
        } else if (HttpMethod.DELETE.equals(httpMethod)) {
            retval = webRequestBuilder.delete(returnType);
        }
        return retval;
    } catch (final InternalServerErrorException e) {
        throw responseToThrowableMapper.apply(e.getResponse());
    }
}
Example 97
Project: BETaaS_Platform-Tools-master  File: ExternalAPIImpl.java View source code
@GET
@Path("/data/{appID}/{serviceID}")
@Consumes("application/xml; charset=UTF-8")
public String getThingServiceData(@PathParam("appID") String appID, @PathParam("serviceID") String serviceID, @HeaderParam("token") String token) {
    mLogger.info("Called getThingServiceData(" + appID + ", " + serviceID + ")");
    if ((token == null) || (token.length() == 0)) {
        mLogger.warn("Token not specified");
    }
    if ((appID == null) || (serviceID == null)) {
        mLogger.error("Wrong appID/serviceID");
        return "";
    }
    // Get the GW Id from the service ID
    int pos = serviceID.indexOf("::");
    if (pos < 0) {
        mLogger.error("Cannot extract GW identifier from serviceID");
        return "";
    }
    String gwId = serviceID.substring(0, pos);
    if (gwId.equals(ServiceManager.getInstance().getGWId())) {
        // It is a service allocated in this GW
        ApplicationRegistry applicationReg = ServiceManager.getInstance().getAppRegistry();
        if (applicationReg.getApp(appID, true) == null) {
            mLogger.error("Received getThingServiceData request from an unregistered application");
            return "";
        }
        RequestManager reqMng = new RequestManager();
        return reqMng.getThingServiceData(serviceID, true, token);
    } else {
        ServiceManagerExternalIF extSM = mDiscovery.retrieveSM(gwId);
        if (extSM != null) {
            mLogger.info("Calling remote getThingServiceData");
            return extSM.getThingServiceData(appID, serviceID, token);
        } else {
            mLogger.error("Cannot get remote SM with GWId=" + gwId);
            return "";
        }
    }
}
Example 98
Project: cdap-master  File: DatasetTypeHandler.java View source code
@PUT
@Path("/data/modules/{name}")
public BodyConsumer addModule(HttpRequest request, HttpResponder responder, @PathParam("namespace-id") String namespaceId, @PathParam("name") final String name, @HeaderParam(HEADER_CLASS_NAME) final String className) throws Exception {
    Id.Namespace namespace = Id.Namespace.from(namespaceId);
    if (Id.Namespace.SYSTEM.equals(namespace)) {
        responder.sendString(HttpResponseStatus.FORBIDDEN, String.format("Cannot add module to '%s' namespace.", namespaceId));
        return null;
    }
    // Throws NamespaceNotFoundException if the namespace does not exist
    ensureNamespaceExists(namespace);
    // verify namespace directory exists
    final Location namespaceHomeLocation = namespacedLocationFactory.get(namespace);
    if (!namespaceHomeLocation.exists()) {
        String msg = String.format("Home directory %s for namespace %s not found", namespaceHomeLocation, namespaceId);
        LOG.error(msg);
        responder.sendString(HttpResponseStatus.NOT_FOUND, msg);
        return null;
    }
    // Store uploaded content to a local temp file
    String namespacesDir = cConf.get(Constants.Namespace.NAMESPACES_DIR);
    File localDataDir = new File(cConf.get(Constants.CFG_LOCAL_DATA_DIR));
    File namespaceBase = new File(localDataDir, namespacesDir);
    File tempDir = new File(new File(namespaceBase, namespaceId), cConf.get(Constants.AppFabric.TEMP_DIR)).getAbsoluteFile();
    if (!DirUtils.mkdirs(tempDir)) {
        throw new IOException("Could not create temporary directory at: " + tempDir);
    }
    final Id.DatasetModule datasetModuleId = Id.DatasetModule.from(namespace, name);
    return new AbstractBodyConsumer(File.createTempFile("dataset-", ".jar", tempDir)) {

        @Override
        protected void onFinish(HttpResponder responder, File uploadedFile) throws Exception {
            if (className == null) {
                // We have to delay until body upload is completed due to the fact that not all client is
                // requesting with "Expect: 100-continue" header and the client library we have cannot handle
                // connection close, and yet be able to read response reliably.
                // In longer term we should fix the client, as well as the netty-http server. However, since
                // this handler will be gone in near future, it's ok to have this workaround.
                responder.sendString(HttpResponseStatus.BAD_REQUEST, "Required header 'class-name' is absent.");
                return;
            }
            LOG.info("Adding module {}, class name: {}", datasetModuleId, className);
            String dataFabricDir = cConf.get(Constants.Dataset.Manager.OUTPUT_DIR);
            Location archiveDir = namespaceHomeLocation.append(dataFabricDir).append(name).append(Constants.ARCHIVE_DIR);
            String archiveName = name + ".jar";
            Location archive = archiveDir.append(archiveName);
            // Copy uploaded content to a temporary location
            Location tmpLocation = archive.getTempFile(".tmp");
            try {
                conflictIfModuleExists(datasetModuleId);
                Locations.mkdirsIfNotExists(archiveDir);
                LOG.debug("Copy from {} to {}", uploadedFile, tmpLocation);
                Files.copy(uploadedFile, Locations.newOutputSupplier(tmpLocation));
                // Check if the module exists one more time to minimize the window of possible conflict
                conflictIfModuleExists(datasetModuleId);
                // Finally, move archive to final location
                LOG.debug("Storing module {} jar at {}", datasetModuleId, archive);
                if (tmpLocation.renameTo(archive) == null) {
                    throw new IOException(String.format("Could not move archive from location: %s, to location: %s", tmpLocation, archive));
                }
                manager.addModule(datasetModuleId, className, archive);
                // todo: response with DatasetModuleMeta of just added module (and log this info)
                LOG.info("Added module {}", datasetModuleId);
                responder.sendStatus(HttpResponseStatus.OK);
            } catch (Exception e) {
                try {
                    tmpLocation.delete();
                } catch (IOException ex) {
                    LOG.warn("Failed to cleanup temporary location {}", tmpLocation);
                }
                if (e instanceof DatasetModuleConflictException) {
                    responder.sendString(HttpResponseStatus.CONFLICT, e.getMessage());
                } else {
                    LOG.error("Failed to add module {}", name, e);
                    throw e;
                }
            }
        }
    };
}
Example 99
Project: EasySOA-Incubation-master  File: WebResourceFactory.java View source code
@Override
@SuppressWarnings("unchecked")
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    // get the interface describing the resource
    Class<?> proxyIfc = proxy.getClass().getInterfaces()[0];
    // response type
    Class<?> responseType = method.getReturnType();
    // determine method name
    String httpMethod = getHttpMethodName(method);
    if (httpMethod == null) {
        for (Annotation ann : method.getAnnotations()) {
            httpMethod = getHttpMethodName(ann.annotationType());
            if (httpMethod != null) {
                break;
            }
        }
    }
    // create a new UriBuilder appending the @Path attached to the method
    WebResource newTarget;
    Path p = method.getAnnotation(Path.class);
    if (p != null && !p.value().contains("{")) {
        newTarget = addPathFromAnnotation(method, target);
    } else {
        newTarget = target;
    }
    if (httpMethod == null) {
        if (newTarget == target) {
            // no path annotation on the method -> fail
            throw new UnsupportedOperationException("Not a resource method.");
        } else if (!responseType.isInterface()) {
            // not interface - can't help here
            throw new UnsupportedOperationException("Return type not an interface");
        }
    }
    // process method params (build maps of (Path|Form|Cookie|Matrix|Header..)Params
    // and extract entity type
    MultivaluedMap<String, String> headers = new MultivaluedMapImpl();
    headers.putAll(this.headers);
    LinkedList<Cookie> cookies = new LinkedList<Cookie>(this.cookies);
    Form form = new Form();
    form.putAll(this.form);
    Annotation[][] paramAnns = method.getParameterAnnotations();
    Object entity = null;
    Type entityType = null;
    for (int i = 0; i < paramAnns.length; i++) {
        Map<Class<?>, Annotation> anns = new HashMap<Class<?>, Annotation>();
        for (Annotation ann : paramAnns[i]) {
            anns.put(ann.annotationType(), ann);
        }
        Annotation ann;
        Object value = args[i];
        if (anns.isEmpty()) {
            entityType = method.getGenericParameterTypes()[i];
            entity = value;
        } else {
            if (value == null && (ann = anns.get(DefaultValue.class)) != null) {
                value = ((DefaultValue) ann).value();
            }
            if (value != null) {
                if ((ann = anns.get(PathParam.class)) != null) {
                    // XXX
                    newTarget = newTarget.path((String) value);
                //newTarget = newTarget.pathParam(((PathParam) ann).value(), (String) value);
                } else if ((ann = anns.get((QueryParam.class))) != null) {
                    newTarget = newTarget.queryParam(((QueryParam) ann).value(), (String) value);
                } else if ((ann = anns.get((HeaderParam.class))) != null) {
                    headers.put(((HeaderParam) ann).value(), (List<String>) value);
                } else if ((ann = anns.get((CookieParam.class))) != null) {
                    String name = ((CookieParam) ann).value();
                    Cookie c;
                    if (!(value instanceof Cookie)) {
                        c = new Cookie(name, value.toString());
                    } else {
                        c = (Cookie) value;
                        if (!name.equals(((Cookie) value).getName())) {
                            // is this the right thing to do? or should I fail? or ignore the difference?
                            c = new Cookie(name, c.getValue(), c.getPath(), c.getDomain(), c.getVersion());
                        }
                    }
                    cookies.add(c);
                } else if ((ann = anns.get((MatrixParam.class))) != null) {
                    throw new UnsupportedOperationException();
                //newTarget = newTarget.matrixParam(((MatrixParam) ann).value(), value);
                } else if ((ann = anns.get((FormParam.class))) != null) {
                    form.add(((FormParam) ann).value(), value.toString());
                }
            }
        }
    }
    if (httpMethod == null) {
        // the method is a subresource locator
        return WebResourceFactory.newResource(responseType, newTarget, true, headers, cookies, form);
    }
    // accepted media types
    Produces produces = method.getAnnotation(Produces.class);
    if (produces == null) {
        produces = proxyIfc.getAnnotation(Produces.class);
    }
    String[] accepts = produces == null ? null : produces.value();
    // determine content type
    String contentType = null;
    if (entity != null) {
        Consumes consumes = method.getAnnotation(Consumes.class);
        if (consumes == null) {
            consumes = proxyIfc.getAnnotation(Consumes.class);
        }
        if (consumes != null && consumes.value().length > 0) {
            // TODO: should consider q/qs instead of picking the first one
            contentType = consumes.value()[0];
        }
    }
    Builder b;
    if (accepts != null) {
        b = newTarget.accept(accepts);
    } else {
        b = newTarget.getRequestBuilder();
    }
    // apply header params and cookies
    for (Cookie c : cookies) {
        b = b.cookie(c);
    }
    // TODO: change this to b.headers(headers) once we switch to the latest JAX-RS API
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (Object value : header.getValue()) {
            b = b.header(header.getKey(), value);
        }
    }
    Object result;
    if (entity == null && !form.isEmpty()) {
        entity = form;
        contentType = MediaType.APPLICATION_FORM_URLENCODED;
    } else {
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }
        if (!form.isEmpty()) {
            if (entity instanceof Form) {
                ((Form) entity).putAll(form);
            } else {
            // TODO: should at least log some warning here
            }
        }
    }
    GenericType<?> responseGenericType = new GenericType<Object>(method.getGenericReturnType());
    if (entity != null) {
        if (entityType instanceof ParameterizedType) {
            entity = new GenericEntity<Object>(entity, entityType);
        }
        b.entity(entity, contentType);
        result = b.method(httpMethod, responseGenericType);
    } else {
        result = b.method(httpMethod, responseGenericType);
    }
    return result;
}
Example 100
Project: elasticinbox-master  File: SingleMessageResource.java View source code
/**
	 * Get original message contents
	 * 
	 * @param account
	 * @param messageId
	 * @return
	 */
@GET
@Path("raw")
@Produces(MediaType.TEXT_PLAIN)
public Response getRawMessage(@HeaderParam(HttpHeaders.ACCEPT_ENCODING) String acceptEncoding, @PathParam("user") final String user, @PathParam("domain") final String domain, @PathParam("messageid") final UUID messageId) {
    Mailbox mailbox = new Mailbox(user, domain);
    Response response;
    try {
        BlobDataSource blobDS = messageDAO.getRaw(mailbox, messageId);
        if (acceptEncoding != null && acceptEncoding.contains("deflate") && blobDS.isCompressed()) {
            response = Response.ok(blobDS.getInputStream(), MediaType.TEXT_PLAIN).header(HttpHeaders.CONTENT_ENCODING, "deflate").build();
        } else {
            response = Response.ok(blobDS.getUncompressedInputStream(), MediaType.TEXT_PLAIN).build();
        }
    } catch (IllegalArgumentException iae) {
        throw new BadRequestException(iae.getMessage());
    } catch (Exception e) {
        logger.warn("Internal Server Error: ", e);
        throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
    }
    return response;
}
Example 101
Project: Europeana-Cloud-master  File: FileResource.java View source code
/**
     * Returns file content. Basic support for HTTP "Range" header is
     * implemented for retrieving only a part of content .
     * (Description of Range header can be found in Hypertext Transfer Protocol
     * HTTP/1.1, <a
     * href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35">section
     * 14.35 Range</a>). For instance:
     * <ul>
     * <li><b>Range: bytes=10-15</b> - retrieve bytes from 10 to 15 of content
     * <li><b>Range: bytes=10-</b> - skip 10 first bytes of content
     * </ul>
     *
     * <strong>Read permissions required.</strong>
     * @summary get file contents from a representation version
     * @param globalId cloud id of the record (required).
     * @param schema schema of representation (required).
     * @param version a specific version of the representation(required).
     * @param fileName the name of the file(required).
     * @param range range of bytes to return (optional)
     * @return file content
     * @throws RepresentationNotExistsException
     * representation does not exist in the specified version.
     * @throws RepresentationNotExistsException representation does not exist in
     * the specified version.
     * @throws WrongContentRangeException wrong value in "Range" header
     * @throws FileNotExistsException representation version does not have file
     * with the specified name.
     */
@GET
@PreAuthorize("hasPermission(#globalId.concat('/').concat(#schema).concat('/').concat(#version)," + " 'eu.europeana.cloud.common.model.Representation', read)")
public Response getFile(@PathParam(P_CLOUDID) final String globalId, @PathParam(P_REPRESENTATIONNAME) final String schema, @PathParam(P_VER) final String version, @PathParam(P_FILENAME) final String fileName, @HeaderParam(HEADER_RANGE) String range) throws RepresentationNotExistsException, FileNotExistsException, WrongContentRangeException {
    // extract range
    final ContentRange contentRange;
    if (range == null) {
        contentRange = new ContentRange(-1L, -1L);
    } else {
        contentRange = ContentRange.parse(range);
    }
    // get file md5 if complete file is requested
    String md5 = null;
    String fileMimeType = null;
    Response.Status status;
    if (contentRange.isSpecified()) {
        status = Response.Status.PARTIAL_CONTENT;
    } else {
        status = Response.Status.OK;
        final File requestedFile = recordService.getFile(globalId, schema, version, fileName);
        md5 = requestedFile.getMd5();
        if (StringUtils.isNotBlank(requestedFile.getMimeType())) {
            fileMimeType = requestedFile.getMimeType();
        }
    }
    // stream output
    StreamingOutput output = new StreamingOutput() {

        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            try {
                recordService.getContent(globalId, schema, version, fileName, contentRange.start, contentRange.end, output);
            } catch (RepresentationNotExistsException ex) {
                throw new WebApplicationException(new UnitedExceptionMapper().toResponse(ex));
            } catch (FileNotExistsException ex) {
                throw new WebApplicationException(new UnitedExceptionMapper().toResponse(ex));
            } catch (WrongContentRangeException ex) {
                throw new WebApplicationException(new UnitedExceptionMapper().toResponse(ex));
            }
        }
    };
    return Response.status(status).entity(output).type(fileMimeType).tag(md5).build();
}