javax.ws.rs.core.Response.ResponseBuilder Java Examples

The following examples show how to use javax.ws.rs.core.Response.ResponseBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShowConfigurationStatus.java    From iaf with Apache License 2.0 6 votes vote down vote up
@GET
@RolesAllowed({"IbisObserver", "IbisDataAdmin", "IbisAdmin", "IbisTester"})
@Path("/adapters/{name}/flow")
@Produces(MediaType.TEXT_PLAIN)
public Response getAdapterFlow(@PathParam("name") String adapterName, @QueryParam("dot") boolean dot) throws ApiException {
	Adapter adapter = getAdapter(adapterName);

	FlowDiagramManager flowDiagramManager = getFlowDiagramManager();

	try {
		ResponseBuilder response = Response.status(Response.Status.OK);
		if(dot) {
			response.entity(flowDiagramManager.generateDot(adapter)).type(MediaType.TEXT_PLAIN);
		} else {
			response.entity(flowDiagramManager.get(adapter)).type("image/svg+xml");
		}
		return response.build();
	} catch (SAXException | TransformerException | IOException e) {
		throw new ApiException(e);
	}
}
 
Example #2
Source File: MessageODataResource.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * 受信/送信メッセージEntityを作成する.
 * @param uriInfo URL情報
 * @param reader リクエストボディ
 * @return response情報
 */
protected Response createMessage(UriInfo uriInfo,
        Reader reader) {

    // response用URLに__ctlを追加する
    UriInfo resUriInfo = DcCoreUtils.createUriInfo(uriInfo, 2, "__ctl");

    // Entityの作成を Producerに依頼
    OEntityWrapper oew = getOEntityWrapper(reader, odataResource, CtlSchema.getEdmDataServicesForMessage().build());
    EntityResponse res = getOdataProducer().createEntity(getEntitySetName(), oew);

    // レスポンスボディを生成する
    OEntity ent = res.getEntity();
    MediaType outputFormat = MediaType.APPLICATION_JSON_TYPE;
    List<MediaType> contentTypes = new ArrayList<MediaType>();
    contentTypes.add(MediaType.APPLICATION_JSON_TYPE);
    String key = AbstractODataResource.replaceDummyKeyToNull(ent.getEntityKey().toKeyString());
    String responseStr = renderEntityResponse(resUriInfo, res, "json", contentTypes);

    // 制御コードのエスケープ処理
    responseStr = escapeResponsebody(responseStr);

    ResponseBuilder rb = getPostResponseBuilder(ent, outputFormat, responseStr, resUriInfo, key);
    return rb.build();
}
 
Example #3
Source File: RequestImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
private ResponseBuilder evaluateIfNotModifiedSince(Date lastModified) {
    List<String> ifNotModifiedSince = headers.getRequestHeader(HttpHeaders.IF_UNMODIFIED_SINCE);

    if (ifNotModifiedSince == null || ifNotModifiedSince.isEmpty()) {
        return null;
    }

    SimpleDateFormat dateFormat = HttpUtils.getHttpDateFormat();

    dateFormat.setLenient(false);
    Date dateSince = null;
    try {
        dateSince = dateFormat.parse(ifNotModifiedSince.get(0));
    } catch (ParseException ex) {
        // invalid header value, request should continue
        return Response.status(Response.Status.PRECONDITION_FAILED);
    }

    if (dateSince.before(lastModified)) {
        return Response.status(Response.Status.PRECONDITION_FAILED);
    }

    return null;
}
 
Example #4
Source File: ResteasyViolationExceptionMapper.java    From quarkus with Apache License 2.0 6 votes vote down vote up
protected Response buildViolationReportResponse(ResteasyViolationException exception, Status status) {
    ResponseBuilder builder = Response.status(status);
    builder.header(Validation.VALIDATION_HEADER, "true");

    // Check standard media types.
    MediaType mediaType = getAcceptMediaType(exception.getAccept());
    if (mediaType != null) {
        builder.type(mediaType);
        builder.entity(new ViolationReport(exception));
        return builder.build();
    }

    // Default media type.
    builder.type(MediaType.TEXT_PLAIN);
    builder.entity(exception.toString());
    return builder.build();
}
 
Example #5
Source File: FramedResource.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
private ResponseBuilder getBuilder(final String jsonEntity, final Date lastMod, final boolean includeEtag, final Request request) {
	String etagSource = DominoUtils.md5(jsonEntity);
	EntityTag etag = new EntityTag(etagSource);
	ResponseBuilder berg = null;
	if (request != null) {
		berg = request.evaluatePreconditions(etag);
	}
	if (berg == null) {
		// System.out.println("TEMP DEBUG creating a new builder");
		berg = Response.ok();
		if (includeEtag) {
			berg.tag(etag);
		}
		berg.type(MediaType.APPLICATION_JSON_TYPE);
		berg.entity(jsonEntity);
		berg.lastModified(lastMod);
		CacheControl cc = new CacheControl();
		cc.setMustRevalidate(true);
		cc.setPrivate(true);
		cc.setMaxAge(86400);
		cc.setNoTransform(true);
		berg.cacheControl(cc);
	}
	return berg;
}
 
Example #6
Source File: BulkExtractTest.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailedEvaluatePreconditions() throws Exception {
    injector.setOauthAuthenticationWithEducationRole();
    mockApplicationEntity();
    mockBulkExtractEntity(null);

    HttpRequestContext context = new HttpRequestContextAdapter() {
        @Override
        public ResponseBuilder evaluatePreconditions(Date lastModified, EntityTag eTag) {
            return Responses.preconditionFailed();
        }
    };

    Response res = bulkExtract.getEdOrgExtractResponse(context, null, null);
    assertEquals(412, res.getStatus());
}
 
Example #7
Source File: EventResource.java    From XPagesExtensionLibrary with Apache License 2.0 6 votes vote down vote up
@Path(PATH_PARAM_INSTANCE + "/action") // $NON-NLS-1$
@PUT
public Response putEventInstanceAction(String requestEntity, @HeaderParam("Content-Type") String contentType, // $NON-NLS-1$
        @Context UriInfo uriInfo, @PathParam(EVENT) String id, 
        @PathParam(INSTANCE) String instanceId,  @QueryParam(URL_PARAM_RECURRENCERANGE) String range,
        @QueryParam(URL_PARAM_ACTION_TYPE) String type) {
    
    CALENDAR_SERVICE_LOGGER.traceEntry(this, "putEventActionInstance"); // $NON-NLS-1$
    CalendarService.beforeRequest(FEATURE_REST_API_CALENDAR_EVENT, STAT_MISC);

    CalendarService.verifyDatabaseContext();

    EventActionResource.putEventActionInternal(requestEntity, contentType, id, instanceId, range, type);

    ResponseBuilder builder = Response.ok();
    Response response = builder.build();

    CALENDAR_SERVICE_LOGGER.traceExit(this, "putEventActionInstance", response); // $NON-NLS-1$
    return response;
}
 
Example #8
Source File: SecurityManagerAssociatingFilter.java    From aries-jax-rs-whiteboard with Apache License 2.0 6 votes vote down vote up
private Response authenticate(UriInfo info, String user, String password) {
    
    _LOG.debug("Received a login request for user {}", user);
    
    Subject currentUser = SecurityUtils.getSubject();
    
    ResponseBuilder rb;
    
    if (!currentUser.isAuthenticated()) {
        _LOG.debug("Authenticating user {}", user);
        UsernamePasswordToken token = new UsernamePasswordToken(user, password);
        token.setRememberMe(true);
        currentUser.login(token);
        
        rb = Response.ok()
                .cookie(new NewCookie(SESSION_COOKIE_NAME, currentUser.getSession().getId().toString(), 
                        info.getBaseUri().getPath(), null, -1, null, -1, null, false, true));
    } else {
        _LOG.debug("The login request for user {} was already authenticated as user {}", user, currentUser.getPrincipal());
        rb = Response.status(Status.CONFLICT);
    }
    return rb.build();
}
 
Example #9
Source File: AbstractODataResource.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * POST用のレスポンスビルダーを作成する.
 * @param ent OEntity
 * @param outputFormat Content-Type
 * @param responseStr レスポンスボディ
 * @param resUriInfo レスポンスのUriInfo
 * @param key レスポンスのエンティティキー
 * @return レスポンスビルダー
 */
protected ResponseBuilder getPostResponseBuilder(
        OEntity ent,
        MediaType outputFormat,
        String responseStr,
        UriInfo resUriInfo,
        String key) {
    ResponseBuilder rb = Response.status(HttpStatus.SC_CREATED).entity(responseStr).type(outputFormat)
            .header(HttpHeaders.LOCATION, resUriInfo.getBaseUri().toASCIIString()
                    + getEntitySetName() + key)
            .header(ODataConstants.Headers.DATA_SERVICE_VERSION, ODataVersion.V2.asString);

    // 応答にETAGを付与
    if (ent instanceof OEntityWrapper) {
        OEntityWrapper oew2 = (OEntityWrapper) ent;
        String etag = oew2.getEtag();
        if (etag != null) {
            rb = rb.header(HttpHeaders.ETAG, "W/\"" + etag + "\"");
        }
    }
    return rb;
}
 
Example #10
Source File: BaseController.java    From govpay with GNU General Public License v3.0 6 votes vote down vote up
private Response handleUnprocessableEntityException(UriInfo uriInfo, HttpHeaders httpHeaders, String methodName, UnprocessableEntityException e, String transactionId) {
	this.log.info("Errore ("+e.getClass().getSimpleName()+") durante "+methodName+": "+ e.getMessage());
	
	FaultBean respKo = new FaultBean();
	respKo.setCategoria(CategoriaEnum.RICHIESTA);
	respKo.setCodice("SEMANTICA");
	respKo.setDescrizione("Richiesta non valida");
	respKo.setDettaglio(e.getDetails());

	String respJson = this.getRespJson(respKo);
	ResponseBuilder responseBuilder = Response.status(e.getTransportErrorCode()).type(MediaType.APPLICATION_JSON).entity(respJson);
	if(e.getTransportErrorCode() > 499)
		this.handleEventoFail(responseBuilder, transactionId, respKo.getCodice(), respKo.getDettaglio());
	else 
		this.handleEventoKo(responseBuilder, transactionId, respKo.getCodice(), respKo.getDettaglio());
	
	return handleResponseKo(responseBuilder, transactionId).build();
}
 
Example #11
Source File: BaseController.java    From govpay with GNU General Public License v3.0 6 votes vote down vote up
private Response handleUnprocessableEntityException(UriInfo uriInfo, HttpHeaders httpHeaders, String methodName, UnprocessableEntityException e, String transactionId) {
	this.log.info("Errore ("+e.getClass().getSimpleName()+") durante "+methodName+": "+ e.getMessage());
	
	FaultBean respKo = new FaultBean();
	respKo.setCategoria(CategoriaEnum.RICHIESTA);
	respKo.setCodice("SEMANTICA");
	respKo.setDescrizione("Richiesta non valida");
	respKo.setDettaglio(e.getDetails());

	String respJson = this.getRespJson(respKo);
	ResponseBuilder responseBuilder = Response.status(e.getTransportErrorCode()).type(MediaType.APPLICATION_JSON).entity(respJson);
	if(e.getTransportErrorCode() > 499)
		this.handleEventoFail(responseBuilder, transactionId, respKo.getCodice(), respKo.getDettaglio());
	else 
		this.handleEventoKo(responseBuilder, transactionId, respKo.getCodice(), respKo.getDettaglio());
	
	return handleResponseKo(responseBuilder, transactionId).build();
}
 
Example #12
Source File: GossipValidateErrorProvider.java    From gossip with MIT License 6 votes vote down vote up
private Response buildViolationReportResponse(ResteasyViolationException exception) {
    ResponseBuilder builder = Response.status(BAD_REQUEST);
    builder.header(VALIDATION_HEADER, "true");
    builder.type(APPLICATION_JSON_TYPE);

    List<ResteasyConstraintViolation> violations = exception.getViolations();

    if (violations.isEmpty()) {
        builder.entity(new ValidateErrorResponse(exception.toString()));
    } else {
        if (log.isDebugEnabled()) {
            try {
                log.debug(objectMapper.writeValueAsString(violations));
            } catch (JsonProcessingException e) {
                log.debug("", e); // Useless, just make sonar and compiler happy w(゚Д゚)w
            }
        }
        builder.entity(new ValidateErrorResponse(violations));
    }

    return builder.build();
}
 
Example #13
Source File: BasicClient.java    From secure-data-service with Apache License 2.0 6 votes vote down vote up
@Override
public Response getHomeResource(Entity home) throws URISyntaxException, MessageProcessingException, IOException {

    URL url = URLBuilder.create(restClient.getBaseURL()).addPath(PathConstants.HOME).build();

    Response response = restClient.getRequest(url);
    if (response.getStatus() == Response.Status.OK.getStatusCode()) {
        try {
            JsonNode element = mapper.readValue(response.readEntity(String.class), JsonNode.class);
            Map<String, List<Link>> links = mapper.readValue(element,
                    new TypeReference<Map<String, List<BasicLink>>>() {
                    });
            home.getData().putAll(links);
        } catch (JsonParseException e) {
            // invalid Json, or non-Json response?
            ResponseBuilder builder = Response.fromResponse(response);
            builder.status(Response.Status.INTERNAL_SERVER_ERROR);
            return builder.build();
        }
    }
    return response;
}
 
Example #14
Source File: DesignsResource.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Generates the project and returns the result as a streaming response.
 * @param settings
 * @param generator
 */
private Response asResponse(JaxRsProjectSettings settings, final OpenApi2JaxRs generator) {
    StreamingOutput stream = new StreamingOutput() {
        @Override
        public void write(OutputStream output) throws IOException, WebApplicationException {
            generator.generate(output);
        }
    };
    
    String fname = settings.artifactId + ".zip";
    ResponseBuilder builder = Response.ok().entity(stream)
            .header("Content-Disposition", "attachment; filename=\"" + fname + "\"")
            .header("Content-Type", "application/zip");

    return builder.build();
}
 
Example #15
Source File: TokenEndPointResource.java    From io with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Response responseAuthSuccess(final IAccessToken accessToken, final IRefreshToken refreshToken) {
    JSONObject resp = new JSONObject();
    resp.put(OAuth2Helper.Key.ACCESS_TOKEN, accessToken.toTokenString());
    resp.put(OAuth2Helper.Key.EXPIRES_IN, accessToken.expiresIn());
    if (refreshToken != null) {
        resp.put(OAuth2Helper.Key.REFRESH_TOKEN, refreshToken.toTokenString());
        resp.put(OAuth2Helper.Key.REFRESH_TOKEN_EXPIRES_IN, refreshToken.refreshExpiresIn());
    }
    resp.put(OAuth2Helper.Key.TOKEN_TYPE, OAuth2Helper.Scheme.BEARER);
    ResponseBuilder rb = Response.ok().type(MediaType.APPLICATION_JSON_TYPE);
    if (accessToken.getTarget() != null) {
        resp.put(OAuth2Helper.Key.TARGET, accessToken.getTarget());
        rb.header(HttpHeaders.LOCATION, accessToken.getTarget() + "__auth");
    }

    if (issueCookie) {
        String tokenString = accessToken.toTokenString();
        // dc_cookie_peerとして、ランダムなUUIDを設定する
        String dcCookiePeer = UUID.randomUUID().toString();
        String cookieValue = dcCookiePeer + "\t" + tokenString;
        // ヘッダに返却するdc_cookie値は、暗号化する
        String encodedCookieValue = LocalToken.encode(cookieValue,
                UnitLocalUnitUserToken.getIvBytes(AccessContext.getCookieCryptKey(requestURIInfo.getBaseUri())));
        // Cookieのバージョン(0)を指定
        int version = 0;
        String path = getCookiePath();

        // Cookieを作成し、レスポンスヘッダに返却する
        Cookie cookie = new Cookie("dc_cookie", encodedCookieValue, path, requestURIInfo.getBaseUri().getHost(),
                version);
        rb.cookie(new NewCookie(cookie, "", -1, DcCoreConfig.isHttps()));
        // レスポンスボディの"dc_cookie_peer"を返却する
        resp.put("dc_cookie_peer", dcCookiePeer);
    }
    return rb.entity(resp.toJSONString()).build();
}
 
Example #16
Source File: ConanResourceITSupport.java    From nexus-repository-conan with Eclipse Public License 1.0 5 votes vote down vote up
private Response execute(HttpEntityEnclosingRequestBase request) throws Exception {
  try (CloseableHttpResponse response = clientBuilder().build().execute(request)) {
    ResponseBuilder responseBuilder = Response.status(response.getStatusLine().getStatusCode());
    Arrays.stream(response.getAllHeaders()).forEach(h -> responseBuilder.header(h.getName(), h.getValue()));

    HttpEntity entity = response.getEntity();
    if (entity != null) {
      responseBuilder.entity(new ByteArrayInputStream(IOUtils.toByteArray(entity.getContent())));
    }
    return responseBuilder.build();
  }
}
 
Example #17
Source File: RuleResource.java    From nifi with Apache License 2.0 5 votes vote down vote up
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path("/rules/{id}")
public Response getRule(
        @PathParam("id") final String ruleId,
        @QueryParam("processorId") final String processorId,
        @DefaultValue("false") @QueryParam("verbose") final Boolean verbose) {

    // get the web context
    final NiFiWebConfigurationContext configurationContext = (NiFiWebConfigurationContext) servletContext.getAttribute("nifi-web-configuration-context");

    // build the web context config
    final NiFiWebRequestContext requestContext = getRequestContext(processorId);

    // load the criteria and get the rule
    final Criteria criteria = getCriteria(configurationContext, requestContext);
    final Rule rule = criteria.getRule(ruleId);

    if (rule == null) {
        throw new NotFoundException();
    }

    // convert to a dto
    final RuleDTO ruleDto = DtoFactory.createRuleDTO(rule);

    // prune if appropriate
    if (!verbose) {
        ruleDto.setConditions(null);
        ruleDto.setActions(null);
    }

    // create the response entity
    final RuleEntity responseEntity = new RuleEntity();
    responseEntity.setProcessorId(processorId);
    responseEntity.setRule(ruleDto);

    // generate the response
    final ResponseBuilder response = Response.ok(responseEntity);
    return noCache(response).build();
}
 
Example #18
Source File: DocumentResource.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@GET
@Path("/{label}/usertemplate")
public Response getDocumentTemplateCheckUser(@PathParam("label") String label) {
	AnalyticalModelDocumentManagementAPI documentManager = new AnalyticalModelDocumentManagementAPI(getUserProfile());
	BIObject document = documentManager.getDocument(label);
	if (document == null)
		throw new SpagoBIRuntimeException("Document with label [" + label + "] doesn't exist");

	// check if owner of document or administrator

	if (!document.getTenant().equals(getUserProfile().getOrganization())
			|| (!UserUtilities.isAdministrator(getUserProfile()) && !document.getCreationUser().equals(getUserProfile().getUserId()))) {
		throw new SpagoBIRuntimeException(
				"User [" + getUserProfile().getUserName() + "] has no rights to see template of document with label [" + label + "]");
	}

	ResponseBuilder rb;
	ObjTemplate template = document.getActiveTemplate();

	// The template has not been found
	if (template == null)
		throw new SpagoBIRuntimeException("Document with label [" + label + "] doesn't contain a template");
	try {
		rb = Response.ok(template.getContent());
	} catch (Exception e) {
		logger.error("Error while getting document template", e);
		throw new SpagoBIRuntimeException("Error while getting document template", e);
	}

	rb.header("Content-Disposition", "attachment; filename=" + document.getActiveTemplate().getName());
	return rb.build();
}
 
Example #19
Source File: BaseController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
protected ResponseBuilder handleResponseOk(ResponseBuilder responseBuilder, String transactionId) {
	this.handleEventoOk(responseBuilder, transactionId);
	if(transactionId != null)
		return responseBuilder.header(this.transactionIdHeaderName, transactionId);
	else 
		return responseBuilder;
}
 
Example #20
Source File: DcResponse.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * レスポンス生成.
 * @return レスポンス
 */
public Response build() {
    ResponseBuilder builder = Response.status(this.status);
    for (Map.Entry<String, String> header : this.headers.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }

    builder.entity(this.streaming);
    return builder.build();
}
 
Example #21
Source File: DossierDocumentManagementImpl.java    From opencps-v2 with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Response printDossierDocument(HttpServletRequest request, HttpHeaders header, Company company,
		Locale locale, User user, ServiceContext serviceContext, String id) {

	BackendAuth auth = new BackendAuthImpl();
	long dossierId = GetterUtil.getLong(id);

	try {

		if (!auth.isAuth(serviceContext)) {
			throw new UnauthenticationException();
		}

		List<DossierDocument> dossierDocList = DossierDocumentLocalServiceUtil.getDossierDocumentList(dossierId, 0, 5);
		DossierDocument dossierDoc = null;
		if (dossierDocList  != null && dossierDocList.size() > 0) {
			dossierDoc = dossierDocList.get(0);
			if (dossierDoc != null) {
				long docFileId = dossierDoc.getDocumentFileId();
				if (docFileId > 0) {
					FileEntry fileEntry = DLAppLocalServiceUtil.getFileEntry(docFileId);

					File file = DLFileEntryLocalServiceUtil.getFile(fileEntry.getFileEntryId(),
							fileEntry.getVersion(), true);

					ResponseBuilder responseBuilder = Response.ok((Object) file);

					responseBuilder.header("Content-Disposition",
							"attachment; filename=\"" + fileEntry.getFileName() + "\"");
					responseBuilder.header("Content-Type", fileEntry.getMimeType());

					return responseBuilder.build();
				}
			}
		}
	} catch (Exception e) {
		return BusinessExceptionImpl.processException(e);
	}
	return Response.status(HttpURLConnection.HTTP_NO_CONTENT).build();
}
 
Example #22
Source File: BaseController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
protected ResponseBuilder handleEventoFail(ResponseBuilder responseBuilder, String transactionId, String sottotipoEsito, String dettaglioEsito) {
	GpContext ctx = (GpContext) ContextThreadLocal.get().getApplicationContext();
	ctx.getEventoCtx().setEsito(Esito.FAIL);
	if(transactionId != null)
		ctx.getEventoCtx().setIdTransazione(transactionId);
	ctx.getEventoCtx().setDescrizioneEsito(dettaglioEsito);
	
	if(sottotipoEsito != null)
		ctx.getEventoCtx().setSottotipoEsito(sottotipoEsito);
	
	return responseBuilder;
}
 
Example #23
Source File: FramedCollectionResource.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
private ResponseBuilder getBuilder(final String jsonEntity, final Date lastMod, final boolean includeEtag, final Request request) {
	String etagSource = DominoUtils.md5(jsonEntity);
	EntityTag etag = new EntityTag(etagSource);
	ResponseBuilder berg = null;
	if (request != null) {
		berg = request.evaluatePreconditions(etag);
	}

	if (berg == null) {
		berg = Response.ok();
		if (includeEtag) {
			berg.tag(etag);
		}
		berg.type(MediaType.APPLICATION_JSON_TYPE).entity(jsonEntity);
		berg.lastModified(lastMod);
		CacheControl cc = new CacheControl();
		cc.setMustRevalidate(true);
		cc.setPrivate(true);
		cc.setMaxAge(86400);
		cc.setNoTransform(true);
		berg.cacheControl(cc);
	} else {
		// System.out.println("TEMP DEBUG got a hit for etag " +
		// etagSource);
	}
	return berg;
}
 
Example #24
Source File: InfoResource.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response performRequest(@Context final UriInfo uriInfo, @PathParam(Routes.NAMESPACE) final String namespace)
		throws JsonException, IOException {
	String jsonEntity = null;
	ResponseBuilder builder = Response.ok();
	ParamMap pm = Parameters.toParamMap(uriInfo);
	StringWriter sw = new StringWriter();
	DFramedTransactionalGraph<?> graph = this.getGraph(namespace);
	JsonGraphWriter writer = new JsonGraphWriter(sw, graph, pm, false, true, false);
	// writer.outObject(null);
	List<String> items = pm.get(Parameters.ITEM);
	if (items != null && items.size() > 0) {
		IGraphFactory factory = this.getService().getFactory(namespace);
		if (factory != null) {
			for (String item : items) {
				Object curResult = factory.processRequest(namespace, item, uriInfo.getQueryParameters());
				writer.outObject(curResult);
			}
		} else {
			System.err.println("No Factory found for namespace: " + namespace);
		}
	}
	jsonEntity = sw.toString();
	builder.type(MediaType.APPLICATION_JSON_TYPE).entity(jsonEntity);
	Response response = builder.build();
	return response;

}
 
Example #25
Source File: UnauthenticatedExceptionMapper.java    From onedev with MIT License 5 votes vote down vote up
@Override
  public Response toResponse(UnauthenticatedException exception) {
ResponseBuilder builder = Response.status(Response.Status.UNAUTHORIZED);
builder.header("WWW-Authenticate", HttpServletRequest.BASIC_AUTH + " realm=\"" + appName + "\"");
  	if (exception.getMessage() != null)
  		builder = builder.entity(exception.getMessage()).type("text/plain");
  	
  	return builder.build();
  }
 
Example #26
Source File: UnauthorizedExceptionMapper.java    From onedev with MIT License 5 votes vote down vote up
@Override
  public Response toResponse(UnauthorizedException exception) {
ResponseBuilder builder;
if (!SecurityUtils.getSubject().isAuthenticated()) {
	builder = Response.status(Response.Status.UNAUTHORIZED);
	builder.header("WWW-Authenticate", HttpServletRequest.BASIC_AUTH + " realm=\"" + appName + "\"");
} else {
	builder = Response.status(Response.Status.FORBIDDEN);
}
  	if (exception.getMessage() != null)
  		builder = builder.entity(exception.getMessage()).type("text/plain");
  	
  	return builder.build();
  }
 
Example #27
Source File: VersionResource.java    From pxf with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the PXF protocol version used currently.
 *
 * @return response with the PXF protocol version
 */
@GET
@Produces("application/json")
public Response getProtocolVersion() {

    ResponseBuilder b = Response.ok();
    b.entity("{ \"version\": \"" + Version.PXF_PROTOCOL_VERSION + "\"}");
    b.type(MediaType.APPLICATION_JSON_TYPE);
    return b.build();
}
 
Example #28
Source File: ApiException.java    From iaf with Apache License 2.0 5 votes vote down vote up
private static Response formatException(String message, Status status, String mediaType) {
	ResponseBuilder response = Response.status(status).type(mediaType);

	if(message != null) {
		message = message.replace("\"", "\\\"").replace("\n", " ").replace(System.getProperty("line.separator"), " ");

		response.entity(("{\"status\":\"error\", \"error\":\"" + message + "\"}"));
	}
	return response.build();
}
 
Example #29
Source File: RequestHandlerImpl.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Create error response with specified status and body message.
 *
 * @param status
 *         response status
 * @param message
 *         response message
 * @return response
 */
private Response createErrorResponse(int status, String message) {
    ResponseBuilder responseBuilder = Response.status(status);
    responseBuilder.entity(message).type(MediaType.TEXT_PLAIN);
    String jaxrsHeader = getJaxrsHeader(status);
    if (jaxrsHeader != null) {
        responseBuilder.header(ExtHttpHeaders.JAXRS_BODY_PROVIDED, jaxrsHeader);
    }
    return responseBuilder.build();
}
 
Example #30
Source File: AuthzTest.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 認証に成功している場合チェックがtrueを返すこと.
 */
@Test
public void 認証に成功している場合チェックがtrueを返すこと() {
    ResponseBuilder rb = Response.status(Status.FOUND)
            .type(MediaType.APPLICATION_JSON_TYPE);
    rb.header(HttpHeaders.LOCATION, UrlUtils.cellRoot("authz") + "#"
            + OAuth2Helper.Key.ACCESS_TOKEN + "=tokenstr&"
            + OAuth2Helper.Key.TOKEN_TYPE + "="
            + OAuth2Helper.Scheme.BEARER
            + "&" + OAuth2Helper.Key.EXPIRES_IN + "=9999&"
            + OAuth2Helper.Key.STATE + "=State");
    Response res = rb.entity("").build();
    AuthzEndPointResourceMock authz = new AuthzEndPointResourceMock(null, null);
    assertTrue(authz.isSuccessAuthorization(res));
}