Java Code Examples for javax.ws.rs.core.Response.Status#OK

The following examples show how to use javax.ws.rs.core.Response.Status#OK . 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: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void givenAValidRequestWhenRetrievingAListOfCustomersWithPaginationParamsThenRetrieveThoseCustomers()
		throws JsonProcessingException {
	final String expectedPath = new StringBuilder().append(FORWARD_SLASH).append(ShopifySdk.VERSION_2020_01)
			.append(FORWARD_SLASH).append("customers").toString();
	final ShopifyCustomer shopifyCustomer = buildShopifyCustomer();
	final List<ShopifyCustomer> shopifyCustomers = new LinkedList<>();
	shopifyCustomers.add(shopifyCustomer);
	final ShopifyCustomersRoot shopifyCustomersRoot = new ShopifyCustomersRoot();
	shopifyCustomersRoot.setCustomers(shopifyCustomers);
	final String expectedResponseBodyString = getJsonString(ShopifyCustomersRoot.class, shopifyCustomersRoot);

	final Status expectedStatus = Status.OK;
	final int expectedStatusCode = expectedStatus.getStatusCode();

	driver.addExpectation(
			onRequestTo(expectedPath).withHeader("X-Shopify-Access-Token", accessToken).withMethod(Method.GET)
					.withParam(ShopifySdk.LIMIT_QUERY_PARAMETER, 50),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));
	final ShopifyGetCustomersRequest shopifyGetCustomersRequest = ShopifyGetCustomersRequest.newBuilder().build();

	final ShopifyPage<ShopifyCustomer> actualCustomersPage = shopifySdk.getCustomers(shopifyGetCustomersRequest);

	assertCustomers(actualCustomersPage);
}
 
Example 2
Source File: DefaultDisseminationHandler.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
public static Response getResponse(RemoteObject remote, String dsId) throws DigitalObjectException {
    // This should limit fedora calls to 1.
    // XXX It works around FedoraClient.FedoraClient.getDatastreamDissemination that hides HTTP headers of the response.
    // Unfortunattely fedora does not return modification date as HTTP header
    // In case of large images it could be faster to ask datastream for modification date first.
    String pid = remote.getPid();
    String path = String.format("objects/%s/datastreams/%s/content", pid, dsId);
    ClientResponse response = remote.getClient().resource().path(path).get(ClientResponse.class);
    if (Status.fromStatusCode(response.getStatus()) != Status.OK) {
        throw new DigitalObjectNotFoundException(pid, null, dsId, response.getEntity(String.class), null);
    }
    MultivaluedMap<String, String> headers = response.getHeaders();
    String filename = headers.getFirst("Content-Disposition");
    filename = filename != null ? filename : "inline; filename=" + pid + '-' + dsId;
    return Response.ok(response.getEntity(InputStream.class), headers.getFirst("Content-Type"))
            .header("Content-Disposition", filename)
            .build();
}
 
Example 3
Source File: FilesUtils.java    From at.info-knowledge-base with MIT License 6 votes vote down vote up
public static Status unZipItems(final String filePath, final String outputFolder) {
    Status response;

    if (getExtension(filePath).equals("zip")) {
        try {
            new ZipFile(filePath).extractAll(outputFolder);
            IO_LOGGER.info("All files have been successfully extracted!");
            response = Status.OK;
        } catch (ZipException e) {
            IO_LOGGER.severe("Unable extract files from " + filePath + ": " + e.getMessage());
            response = Status.INTERNAL_SERVER_ERROR;
        }
    } else {
        response = Status.NOT_FOUND;
    }

    return response;
}
 
Example 4
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void givenSomeValidRequestWhenGettingProductCount() throws JsonProcessingException {
	final Count count = new Count();
	count.setCount(231);
	final String expectedResponseBodyString = getJsonString(Count.class, count);

	final String expectedImagePath = new StringBuilder().append(FORWARD_SLASH).append(ShopifySdk.PRODUCTS)
			.append(FORWARD_SLASH).append(ShopifySdk.COUNT).toString();

	final Status expectedStatus = Status.OK;
	final int expectedStatusCode = expectedStatus.getStatusCode();
	driver.addExpectation(
			onRequestTo(expectedImagePath).withHeader(ShopifySdk.ACCESS_TOKEN_HEADER, accessToken)
					.withMethod(Method.GET),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));

	final int actualProductCount = shopifySdk.getProductCount();
	assertEquals(231, actualProductCount);

}
 
Example 5
Source File: BookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Descriptions({
    @Description(value = "Update the books collection", target = DocTarget.METHOD),
    @Description(value = "Requested Book", target = DocTarget.RETURN),
    @Description(value = "Request", target = DocTarget.REQUEST),
    @Description(value = "Response", target = DocTarget.RESPONSE),
    @Description(value = "Resource books/{bookid}", target = DocTarget.RESOURCE)
})
@ResponseStatus({Status.CREATED, Status.OK })
//CHECKSTYLE:OFF
@POST
@Path("books/{bookid}")
public Book addBook(@Description("book id") //NOPMD
                    @PathParam("id") int id,
                    @PathParam("bookid") int bookId,
                    @MatrixParam("mid") @DefaultValue("mid > 5") String matrixId,
                    @Description("header param")
                    @HeaderParam("hid") int headerId,
                    @CookieParam("cid") int cookieId,
                    @QueryParam("provider.bar") int queryParam,
                    @QueryParam("bookstate") BookEnum state,
                    @QueryParam("orderstatus") BookOrderEnum status,
                    @QueryParam("a") List<String> queryList,
                    @Context HttpHeaders headers,
                    @Description("InputBook")
                    @XMLName(value = "{http://books}thesuperbook2")
                    Book2 b) {
    return new Book(1);
}
 
Example 6
Source File: BundleResource.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public Response createFromArchive(byte[] zipInput, Boolean force) {
    if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.ROOT, null)) {
        throw WebResourceUtils.forbidden("User '%s' is not authorized to add catalog items",
            Entitlements.getEntitlementContext().user());
    }
    if (force==null) force = false;

    ReferenceWithError<OsgiBundleInstallationResult> result = ((ManagementContextInternal)mgmt()).getOsgiManager().get()
        .install(null, new ByteArrayInputStream(zipInput), true, true, force);

    if (result.hasError()) {
        // (rollback already done as part of install, if necessary)
        if (log.isTraceEnabled()) {
            log.trace("Unable to create from archive, returning 400: "+result.getError().getMessage(), result.getError());
        }
        return ApiError.builder().errorCode(Status.BAD_REQUEST).message(result.getWithoutError().getMessage())
            .data(TypeTransformer.bundleInstallationResult(result.getWithoutError(), mgmt(), brooklyn(), ui)).build().asJsonResponse();
    }

    BundleInstallationRestResult resultR = TypeTransformer.bundleInstallationResult(result.get(), mgmt(), brooklyn(), ui);
    Status status;
    switch (result.get().getCode()) {
        case IGNORING_BUNDLE_AREADY_INSTALLED:
        case IGNORING_BUNDLE_FORCIBLY_REMOVED:
            status = Status.OK;
            break;
        default:
            // already checked that it was not an error; anything else means we created it.
            status = Status.CREATED;
            break;
    }
    return Response.status(status).entity(resultR).build();
}
 
Example 7
Source File: IncassiController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response incassiIdDominioPOST(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idDominio, java.io.InputStream is) {
  	String methodName = "incassiIdDominioPOST"; 
String transactionId = ContextThreadLocal.get().getTransactionId();
this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 
try(ByteArrayOutputStream baos = new ByteArrayOutputStream();){
	// salvo il json ricevuto
	IOUtils.copy(is, baos);
	
	// autorizzazione sulla API
	this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.API_RAGIONERIA), Arrays.asList(Diritti.SCRITTURA));

	ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
	validatoreId.validaIdDominio("idDominio", idDominio);
	
	IncassoPost incasso = JSONSerializable.parse(baos.toString(), IncassoPost.class);
	incasso.validate();
	
	RichiestaIncassoDTO richiestaIncassoDTO = IncassiConverter.toRichiestaIncassoDTO(incasso, idDominio, user);
	
	IncassiDAO incassiDAO = new IncassiDAO();
	
	RichiestaIncassoDTOResponse richiestaIncassoDTOResponse = incassiDAO.richiestaIncasso(richiestaIncassoDTO);
	
	Incasso incassoExt = IncassiConverter.toRsModel(richiestaIncassoDTOResponse.getIncasso());
	
	Status responseStatus = richiestaIncassoDTOResponse.isCreated() ?  Status.CREATED : Status.OK;
	
	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
	return this.handleResponseOk(Response.status(responseStatus).entity(incassoExt.toJSON(null)),transactionId).build();
}catch (Exception e) {
	return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
} finally {
	this.log(ContextThreadLocal.get());
}
  }
 
Example 8
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void givenASinceIdWhenRetrievingCustomersThenRetrieveJustThoseCustomers() throws JsonProcessingException {
	final String sinceId = "since-id";
	final String expectedPath = new StringBuilder().append(FORWARD_SLASH).append(ShopifySdk.VERSION_2020_01)
			.append(FORWARD_SLASH).append("customers").toString();
	final ShopifyCustomer shopifyCustomer = buildShopifyCustomer();
	final List<ShopifyCustomer> shopifyCustomers = new LinkedList<>();
	shopifyCustomers.add(shopifyCustomer);
	final ShopifyCustomersRoot shopifyCustomersRoot = new ShopifyCustomersRoot();
	shopifyCustomersRoot.setCustomers(shopifyCustomers);
	final String expectedResponseBodyString = getJsonString(ShopifyCustomersRoot.class, shopifyCustomersRoot);

	final Status expectedStatus = Status.OK;
	final int expectedStatusCode = expectedStatus.getStatusCode();

	driver.addExpectation(
			onRequestTo(expectedPath).withHeader("X-Shopify-Access-Token", accessToken).withMethod(Method.GET)
					.withParam(ShopifySdk.SINCE_ID_QUERY_PARAMETER, sinceId)
					.withParam(ShopifySdk.LIMIT_QUERY_PARAMETER, 50),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));

	final ShopifyGetCustomersRequest shopifyGetCustomersRequest = ShopifyGetCustomersRequest.newBuilder()
			.withSinceId(sinceId).build();

	final ShopifyPage<ShopifyCustomer> actualCustomersPage = shopifySdk.getCustomers(shopifyGetCustomersRequest);

	assertCustomers(actualCustomersPage);
}
 
Example 9
Source File: EntrateController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addEntrata(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idEntrata, java.io.InputStream is) {
  	String methodName = "addEntrata";  
String transactionId = ContextThreadLocal.get().getTransactionId();
this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 
try(ByteArrayOutputStream baos= new ByteArrayOutputStream();){
	// salvo il json ricevuto
	IOUtils.copy(is, baos);
	
	// autorizzazione sulla API
	this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.OPERATORE, TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.ANAGRAFICA_CREDITORE), Arrays.asList(Diritti.SCRITTURA));
	
	String jsonRequest = baos.toString();
	TipoEntrataPost entrataRequest= JSONSerializable.parse(jsonRequest, TipoEntrataPost.class);
	
	ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
	validatoreId.validaIdEntrata("idEntrata", idEntrata);
	
	entrataRequest.validate();
	
	PutEntrataDTO putIntermediarioDTO = EntrateConverter.getPutEntrataDTO(entrataRequest, idEntrata, user);
	
	EntrateDAO intermediariDAO = new EntrateDAO(false);
	
	PutEntrataDTOResponse putIntermediarioDTOResponse = intermediariDAO.createOrUpdateEntrata(putIntermediarioDTO);
	
	Status responseStatus = putIntermediarioDTOResponse.isCreated() ?  Status.CREATED : Status.OK;
	
	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
	return this.handleResponseOk(Response.status(responseStatus),transactionId).build();
}catch (Exception e) {
	return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
} finally {
	this.log(ContextThreadLocal.get());
}
  }
 
Example 10
Source File: DominiController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addUnitaOperativa(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idDominio, String idUnitaOperativa, java.io.InputStream is) {
	String methodName = "addUnitaOperativa";  
	String transactionId = ContextThreadLocal.get().getTransactionId();
	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 
	try(ByteArrayOutputStream baos= new ByteArrayOutputStream();){
		// salvo il json ricevuto
		IOUtils.copy(is, baos);

		// autorizzazione sulla API
		this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.OPERATORE, TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.ANAGRAFICA_CREDITORE), Arrays.asList(Diritti.SCRITTURA));

		String jsonRequest = baos.toString();
		UnitaOperativaPost unitaOperativaRequest= JSONSerializable.parse(jsonRequest, UnitaOperativaPost.class);

		ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
		validatoreId.validaIdDominio("idDominio", idDominio);
		validatoreId.validaIdUO("idUnitaOperativa", idUnitaOperativa);

		unitaOperativaRequest.validate();

		PutUnitaOperativaDTO putUnitaOperativaDTO = DominiConverter.getPutUnitaOperativaDTO(unitaOperativaRequest, idDominio, idUnitaOperativa, user);

		DominiDAO dominiDAO = new DominiDAO(false);

		PutUnitaOperativaDTOResponse putUnitaOperativaDTOResponse = dominiDAO.createOrUpdateUnitaOperativa(putUnitaOperativaDTO);

		Status responseStatus = putUnitaOperativaDTOResponse.isCreated() ?  Status.CREATED : Status.OK;

		this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
		return this.handleResponseOk(Response.status(responseStatus),transactionId).build();
	}catch (Exception e) {
		return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
	} finally {
		this.log(ContextThreadLocal.get());
	}
}
 
Example 11
Source File: RuoliController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addRuolo(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idRuolo, java.io.InputStream is) {
  	String methodName = "addRuolo";  
String transactionId = ContextThreadLocal.get().getTransactionId();
this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 
try (ByteArrayOutputStream baos= new ByteArrayOutputStream();){
	// salvo il json ricevuto
	IOUtils.copy(is, baos);
	
	// autorizzazione sulla API
	this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.OPERATORE, TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.ANAGRAFICA_RUOLI), Arrays.asList(Diritti.SCRITTURA));
	
	ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
	validatoreId.validaIdRuolo("idRuolo", idRuolo);
	
	String jsonRequest = baos.toString();

	RuoloPost ruoloPost = RuoloPost.parse(jsonRequest);
	ruoloPost.validate();
	
	List<AclPost> listaAcl = ruoloPost.getAcl();
	
	PutRuoloDTO putRuoloDTO = RuoliConverter.getPutRuoloDTO(listaAcl, idRuolo, user); 
	
	RuoliDAO applicazioniDAO = new RuoliDAO(false);
	
	PutRuoloDTOResponse putApplicazioneDTOResponse = applicazioniDAO.createOrUpdate(putRuoloDTO);
	
	Status responseStatus = putApplicazioneDTOResponse.isCreated() ?  Status.CREATED : Status.OK;
	
	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
	return this.handleResponseOk(Response.status(responseStatus),transactionId).build();
}catch (Exception e) {
	return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
} finally {
	this.log(ContextThreadLocal.get());
}
  }
 
Example 12
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void givenShopWithNoOrdersAndSomeMininumCreationDateAndPage1And80PageSizeWhenRetrievingOrdersThenReturnNoOrders()
		throws JsonProcessingException {
	final String expectedPath = new StringBuilder().append(FORWARD_SLASH).append(ShopifySdk.VERSION_2020_01)
			.append(FORWARD_SLASH).append(ShopifySdk.ORDERS).toString();

	final ShopifyOrdersRoot shopifyOrdersRoot = new ShopifyOrdersRoot();

	final String expectedResponseBodyString = getJsonString(ShopifyOrdersRoot.class, shopifyOrdersRoot);

	final Status expectedStatus = Status.OK;
	final int expectedStatusCode = expectedStatus.getStatusCode();
	final int pageSize = 80;
	final DateTime minimumCreationDateTime = SOME_DATE_TIME;
	driver.addExpectation(
			onRequestTo(expectedPath).withHeader(ShopifySdk.ACCESS_TOKEN_HEADER, accessToken)
					.withParam(ShopifySdk.STATUS_QUERY_PARAMETER, ShopifySdk.ANY_STATUSES)
					.withParam(ShopifySdk.LIMIT_QUERY_PARAMETER, pageSize)
					.withParam(ShopifySdk.CREATED_AT_MIN_QUERY_PARAMETER, minimumCreationDateTime.toString())
					.withMethod(Method.GET),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));

	final ShopifyPage<ShopifyOrder> actualShopifyOrdersPage = shopifySdk.getOrders(minimumCreationDateTime,
			pageSize);

	assertEquals(0, actualShopifyOrdersPage.size());
}
 
Example 13
Source File: DominiController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addDominio(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idDominio, java.io.InputStream is) {
	String methodName = "addDominio";  
	String transactionId = ContextThreadLocal.get().getTransactionId();
	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 
	try(ByteArrayOutputStream baos= new ByteArrayOutputStream();){
		// salvo il json ricevuto
		IOUtils.copy(is, baos);

		// autorizzazione sulla API
		this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.OPERATORE, TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.ANAGRAFICA_CREDITORE), Arrays.asList(Diritti.SCRITTURA));

		String jsonRequest = baos.toString();
		DominioPost dominioRequest= JSONSerializable.parse(jsonRequest, DominioPost.class);

		ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
		validatoreId.validaIdDominio("idDominio", idDominio);

		dominioRequest.validate();

		PutDominioDTO putDominioDTO = DominiConverter.getPutDominioDTO(dominioRequest, idDominio, user); 

		new DominioValidator(putDominioDTO.getDominio()).validazioneSemantica();

		DominiDAO dominiDAO = new DominiDAO(false);

		PutDominioDTOResponse putDominioDTOResponse = dominiDAO.createOrUpdate(putDominioDTO);

		Status responseStatus = putDominioDTOResponse.isCreated() ?  Status.CREATED : Status.OK;

		this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
		return this.handleResponseOk(Response.status(responseStatus),transactionId).build();
	}catch (Exception e) {
		return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
	} finally {
		this.log(ContextThreadLocal.get());
	}
}
 
Example 14
Source File: JRestlessHandlerContainer.java    From jrestless with Apache License 2.0 5 votes vote down vote up
public JRestlessContainerResponse(@Nonnull JRestlessResponseWriter responseWriter) {
	requireNonNull(responseWriter, "responseWriter may not be null");

	this.entityOutputStream = requireNonNull(responseWriter.getEntityOutputStream());
	this.closed = new AtomicBoolean(false);
	this.responseWriter = responseWriter;
	this.headers = new MultivaluedHashMap<>();
	this.statusType = Status.OK;
}
 
Example 15
Source File: IssueTypeToHttpStatusMapper.java    From FHIR with Apache License 2.0 4 votes vote down vote up
private static Status issueTypeToResponseCode(IssueType.ValueSet value) {
    switch (value) {
    case INFORMATIONAL:
        return Status.OK;
    case FORBIDDEN:
    case SUPPRESSED:
    case SECURITY:
    case THROTTLED:     // Consider HTTP 429?
        return Status.FORBIDDEN;
    case PROCESSING:
    case BUSINESS_RULE: // Consider HTTP 422?
    case CODE_INVALID:  // Consider HTTP 422?
    case EXTENSION:     // Consider HTTP 422?
    case INVALID:       // Consider HTTP 422?
    case INVARIANT:     // Consider HTTP 422?
    case REQUIRED:      // Consider HTTP 422?
    case STRUCTURE:     // Consider HTTP 422?
    case VALUE:         // Consider HTTP 422?
    case TOO_COSTLY:    // Consider HTTP 403?
    case DUPLICATE:     // Consider HTTP 409?
        return Status.BAD_REQUEST;
    case DELETED:
        return Status.GONE;
    case CONFLICT:
        return Status.CONFLICT;
    case MULTIPLE_MATCHES:
        return Status.PRECONDITION_FAILED;
    case EXPIRED:
    case LOGIN:
    case UNKNOWN:
        return Status.UNAUTHORIZED;
    case NOT_FOUND:
    case NOT_SUPPORTED:
        return Status.NOT_FOUND;
    case TOO_LONG:
        return Status.REQUEST_ENTITY_TOO_LARGE;
    case EXCEPTION:
    case LOCK_ERROR:
    case NO_STORE:
    case TIMEOUT:
    case TRANSIENT:
    case INCOMPLETE:
    default:
        return Status.INTERNAL_SERVER_ERROR;
    }
}
 
Example 16
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void givenSomeValidAccessTokenAndSubdomainAndSomeRecurringChargeIdRequestWhenActivatingRecurringApplicationChargeThenActivateRecurringApplicationCharge()
		throws Exception {

	final String expectedGetPath = new StringBuilder().append(FORWARD_SLASH)
			.append(ShopifySdk.RECURRING_APPLICATION_CHARGES).append(FORWARD_SLASH).append("Some-Charge_id")
			.toString();

	final ShopifyRecurringApplicationCharge shopifyRecurringApplicationCharge = new ShopifyRecurringApplicationCharge();
	shopifyRecurringApplicationCharge.setActivatedOn("2018-01-01");
	shopifyRecurringApplicationCharge.setBillingOn("2019-01-01");
	shopifyRecurringApplicationCharge.setConfirmationUrl("https://www.google.com/1");
	shopifyRecurringApplicationCharge.setCreatedAt("2018-01-01");
	shopifyRecurringApplicationCharge.setCappedAmount(BigDecimal.valueOf(41.42));
	shopifyRecurringApplicationCharge.setReturnUrl("https://www.google.com/2");
	shopifyRecurringApplicationCharge.setName("Some Name");
	shopifyRecurringApplicationCharge.setPrice(BigDecimal.valueOf(41.42));
	shopifyRecurringApplicationCharge.setApiClientId("787428734234");
	shopifyRecurringApplicationCharge.setTerms("some terms");
	shopifyRecurringApplicationCharge.setTrialDays(720);
	shopifyRecurringApplicationCharge.setTrialEndsOn("2020-01-01");
	shopifyRecurringApplicationCharge.setTest(true);
	shopifyRecurringApplicationCharge.setStatus("active");

	final ShopifyRecurringApplicationChargeRoot shopifyRecurringApplicationChargeRoot = new ShopifyRecurringApplicationChargeRoot();
	shopifyRecurringApplicationChargeRoot.setRecurringApplicationCharge(shopifyRecurringApplicationCharge);
	final String expectedResponseBodyString = getJsonString(ShopifyRecurringApplicationChargeRoot.class,
			shopifyRecurringApplicationChargeRoot);

	final Status expectedStatus = Status.OK;
	final int expectedStatusCode = expectedStatus.getStatusCode();
	driver.addExpectation(
			onRequestTo(expectedGetPath).withHeader("X-Shopify-Access-Token", accessToken).withMethod(Method.GET),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));

	final JsonBodyCapture actualActivateRequestBody = new JsonBodyCapture();
	final String expectedActivatePath = new StringBuilder().append(FORWARD_SLASH)
			.append(ShopifySdk.RECURRING_APPLICATION_CHARGES).append(FORWARD_SLASH).append("Some-Charge_id")
			.append(FORWARD_SLASH).append(ShopifySdk.ACTIVATE).toString();

	final Status expectedActivateStatus = Status.OK;
	final int expectedActivateStatusCode = expectedActivateStatus.getStatusCode();
	driver.addExpectation(
			onRequestTo(expectedActivatePath).withHeader("X-Shopify-Access-Token", accessToken)
					.withMethod(Method.POST).capturingBodyIn(actualActivateRequestBody),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON)
					.withStatus(expectedActivateStatusCode));

	final ShopifyRecurringApplicationCharge actualShopifyRecurringApplicationCharge = shopifySdk
			.activateRecurringApplicationCharge("Some-Charge_id");

	assertEquals(shopifyRecurringApplicationCharge.getName(),
			actualActivateRequestBody.getContent().get("name").asText());
	assertEquals(shopifyRecurringApplicationCharge.getTerms(),
			actualActivateRequestBody.getContent().get("terms").asText());
	assertEquals(0, shopifyRecurringApplicationCharge.getPrice()
			.compareTo(actualActivateRequestBody.getContent().get("price").decimalValue()));
	assertEquals(0, shopifyRecurringApplicationCharge.getCappedAmount()
			.compareTo(actualActivateRequestBody.getContent().get("capped_amount").decimalValue()));
	assertEquals(shopifyRecurringApplicationCharge.getReturnUrl(),
			actualActivateRequestBody.getContent().get("return_url").asText());
	assertEquals(shopifyRecurringApplicationCharge.getTrialDays(),
			actualActivateRequestBody.getContent().get("trial_days").asInt());
	assertEquals(shopifyRecurringApplicationCharge.isTest(),
			actualActivateRequestBody.getContent().get("test").asBoolean());

	assertEquals(shopifyRecurringApplicationCharge.getId(), actualShopifyRecurringApplicationCharge.getId());
	assertEquals(shopifyRecurringApplicationCharge.getActivatedOn(),
			actualShopifyRecurringApplicationCharge.getActivatedOn());
	assertEquals(shopifyRecurringApplicationCharge.getApiClientId(),
			actualShopifyRecurringApplicationCharge.getApiClientId());
	assertEquals(shopifyRecurringApplicationCharge.getBillingOn(),
			actualShopifyRecurringApplicationCharge.getBillingOn());
	assertEquals(shopifyRecurringApplicationCharge.getCancelledOn(),
			actualShopifyRecurringApplicationCharge.getCancelledOn());
	assertEquals(shopifyRecurringApplicationCharge.getCappedAmount(),
			actualShopifyRecurringApplicationCharge.getCappedAmount());
	assertEquals(shopifyRecurringApplicationCharge.getConfirmationUrl(),
			actualShopifyRecurringApplicationCharge.getConfirmationUrl());
	assertEquals(shopifyRecurringApplicationCharge.getCreatedAt(),
			actualShopifyRecurringApplicationCharge.getCreatedAt());
	assertEquals(shopifyRecurringApplicationCharge.getName(), actualShopifyRecurringApplicationCharge.getName());
	assertEquals(shopifyRecurringApplicationCharge.getPrice(), actualShopifyRecurringApplicationCharge.getPrice());
	assertEquals(shopifyRecurringApplicationCharge.getReturnUrl(),
			actualShopifyRecurringApplicationCharge.getReturnUrl());
	assertEquals(shopifyRecurringApplicationCharge.getStatus(),
			actualShopifyRecurringApplicationCharge.getStatus());
	assertEquals(shopifyRecurringApplicationCharge.getTerms(), actualShopifyRecurringApplicationCharge.getTerms());
	assertEquals(shopifyRecurringApplicationCharge.getTrialDays(),
			actualShopifyRecurringApplicationCharge.getTrialDays());
	assertEquals(shopifyRecurringApplicationCharge.getTrialEndsOn(),
			actualShopifyRecurringApplicationCharge.getTrialEndsOn());
	assertEquals(shopifyRecurringApplicationCharge.getUpdatedOn(),
			actualShopifyRecurringApplicationCharge.getUpdatedOn());
}
 
Example 17
Source File: BackchannelAuthenticationCompleteHandlerSpiImpl.java    From java-oauth-server with Apache License 2.0 4 votes vote down vote up
@Override
public void sendNotification(BackchannelAuthenticationCompleteResponse info)
{
    // The URL of the consumption device's notification endpoint.
    URI clientNotificationEndpointUri = info.getClientNotificationEndpoint();

    // The token that is needed for client authentication at the consumption
    // device's notification endpoint.
    String notificationToken = info.getClientNotificationToken();

    // The notification content (JSON) to send to the consumption device.
    String notificationContent = info.getResponseContent();

    // Send the notification to the consumption device's notification endpoint.
    Response response =
            doSendNotification(clientNotificationEndpointUri, notificationToken, notificationContent);

    // The status of the response from the consumption device.
    Status status = Status.fromStatusCode(response.getStatusInfo().getStatusCode());

    // TODO: CIBA specification does not specify how to deal with responses
    // returned from the consumption device in case of error push notification.
    // Then, even in case of error push notification, the current implementation
    // treats the responses as in the case of successful push notification.

    // Check if the "HTTP 200 OK" or "HTTP 204 No Content".
    if (status == Status.OK || status == Status.NO_CONTENT)
    {
        // In this case, the request was successfully processed by the consumption
        // device since the specification says as follows.
        //
        //   CIBA Core spec, 10.2. Ping Callback and 10.3. Push Callback
        //     For valid requests, the Client Notification Endpoint SHOULD
        //     respond with an HTTP 204 No Content.  The OP SHOULD also accept
        //     HTTP 200 OK and any body in the response SHOULD be ignored.
        //
        return;
    }

    if (status.getFamily() == Status.Family.REDIRECTION)
    {
        // HTTP 3xx code. This case must be ignored since the specification
        // says as follows.
        //
        //   CIBA Core spec, 10.2. Ping Callback, 10.3. Push Callback
        //     The Client MUST NOT return an HTTP 3xx code.  The OP MUST
        //     NOT follow redirects.
        //
        return;
    }
}
 
Example 18
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void givenSomeValidAccessTokenAndSubdomainAndProductIdWhenGettingProductThenGetProduct()
		throws JsonProcessingException {

	final ShopifyProductRoot shopifyProductRoot = new ShopifyProductRoot();
	final ShopifyProduct shopifyProduct = new ShopifyProduct();
	shopifyProduct.setId("123");

	final Image image = new Image();
	image.setName("Some image 1");
	image.setPosition(0);
	image.setProductId("123");
	image.setSource("http://channelape.com/1.png");
	shopifyProduct.setImages(Arrays.asList(image));
	shopifyProduct.setProductType("Shoes");
	shopifyProduct.setBodyHtml("Some Description");
	shopifyProduct.setTags(new HashSet<>(Arrays.asList("Shoes", "Apparel")));
	shopifyProduct.setPublished(true);
	shopifyProduct.setTitle("Some Title");
	shopifyProduct.setVendor("Some Vendor");
	shopifyProduct.setPublishedAt("2018-01-01T00:00:00");
	shopifyProduct.setMetafieldsGlobalDescriptionTag("Some tags");
	shopifyProduct.setMetafieldsGlobalTitleTag("some title tags");

	final ShopifyVariant shopifyVariant = new ShopifyVariant();
	shopifyVariant.setId("999");
	shopifyVariant.setBarcode("XYZ-123");
	shopifyVariant.setSku("ABC-123");
	shopifyVariant.setImageId("1");
	shopifyVariant.setPrice(BigDecimal.valueOf(42.11));
	shopifyVariant.setGrams(12);
	shopifyVariant.setAvailable(3L);
	shopifyVariant.setRequiresShipping(true);
	shopifyVariant.setTaxable(true);
	shopifyVariant.setOption1("Red");
	shopifyVariant.setOption2("Blue");
	shopifyVariant.setOption3("GREEN");
	shopifyProduct.setVariants(Arrays.asList(shopifyVariant));
	shopifyProductRoot.setProduct(shopifyProduct);

	final String expectedPath = new StringBuilder().append(FORWARD_SLASH).append(ShopifySdk.PRODUCTS)
			.append(FORWARD_SLASH).append("123").toString();

	final String expectedResponseBodyString = getJsonString(ShopifyProductRoot.class, shopifyProductRoot);

	final Status expectedStatus = Status.OK;
	final int expectedStatusCode = expectedStatus.getStatusCode();
	driver.addExpectation(
			onRequestTo(expectedPath).withHeader(ShopifySdk.ACCESS_TOKEN_HEADER, accessToken)
					.withMethod(Method.GET),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));

	final ShopifyProduct actualShopifyProduct = shopifySdk.getProduct("123");
	assertNotNull(actualShopifyProduct);
	assertEquals(shopifyProduct.getId(), actualShopifyProduct.getId());
	assertEquals(shopifyProduct.getBodyHtml(), actualShopifyProduct.getBodyHtml());
	assertEquals(shopifyProduct.getImage(), actualShopifyProduct.getImage());
	assertEquals(shopifyProduct.getImages().get(0).getId(), actualShopifyProduct.getImages().get(0).getId());
	assertEquals(shopifyProduct.getImages().get(0).getName(), actualShopifyProduct.getImages().get(0).getName());
	assertEquals(shopifyProduct.getImages().get(0).getPosition(),
			actualShopifyProduct.getImages().get(0).getPosition());
	assertEquals(shopifyProduct.getImages().get(0).getSource(),
			actualShopifyProduct.getImages().get(0).getSource());
	assertEquals(shopifyProduct.getMetafieldsGlobalDescriptionTag(),
			actualShopifyProduct.getMetafieldsGlobalDescriptionTag());
	assertEquals(shopifyProduct.getProductType(), actualShopifyProduct.getProductType());
	assertEquals(shopifyProduct.getPublishedAt(), actualShopifyProduct.getPublishedAt());
	assertTrue(shopifyProduct.getTags().containsAll(actualShopifyProduct.getTags()));
	assertEquals(shopifyProduct.getTitle(), actualShopifyProduct.getTitle());
	assertEquals(shopifyProduct.getVariants().get(0).getId(), actualShopifyProduct.getVariants().get(0).getId());

	assertEquals(shopifyProduct.getVariants().get(0).getOption1(),
			actualShopifyProduct.getVariants().get(0).getOption1());
	assertEquals(shopifyProduct.getVariants().get(0).getOption2(),
			actualShopifyProduct.getVariants().get(0).getOption2());
	assertEquals(shopifyProduct.getVariants().get(0).getOption3(),
			actualShopifyProduct.getVariants().get(0).getOption3());

}
 
Example 19
Source File: PendenzeController.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
public Response addPendenzaPOST(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idDominio, String idTipoPendenza, java.io.InputStream is, String idUnitaOperativa, Boolean stampaAvviso, Boolean avvisaturaDigitale, ModalitaAvvisaturaDigitale modalitaAvvisaturaDigitale) {
	String methodName = "addPendenzaPOST";  
	String transactionId = ContextThreadLocal.get().getTransactionId();
	this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_IN_CORSO, methodName)); 

	try(ByteArrayOutputStream baos= new ByteArrayOutputStream();){

		((GpContext) (ContextThreadLocal.get()).getApplicationContext()).getEventoCtx().setCodDominio(idDominio);
		// autorizzazione sulla API
		this.isAuthorized(user, Arrays.asList(TIPO_UTENZA.OPERATORE, TIPO_UTENZA.APPLICAZIONE), Arrays.asList(Servizio.PENDENZE), Arrays.asList(Diritti.SCRITTURA));

		ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
		validatoreId.validaIdDominio("idDominio", idDominio);
		validatoreId.validaIdTipoVersamento("idTipoPendenza", idTipoPendenza);
		if(idUnitaOperativa != null)
			validatoreId.validaIdUO("idUnitaOperativa", idUnitaOperativa);

		// controllo che il dominio e tipo versamento siano autorizzati
		if(idUnitaOperativa != null) {
			if(!AuthorizationManager.isTipoVersamentoUOAuthorized(user, idDominio, idUnitaOperativa, idTipoPendenza)) {
				throw AuthorizationManager.toNotAuthorizedException(user, idDominio, idUnitaOperativa, idTipoPendenza);
			}
		} else {
			if(!AuthorizationManager.isTipoVersamentoDominioAuthorized(user, idDominio, idTipoPendenza)) {
				throw AuthorizationManager.toNotAuthorizedException(user, idDominio, idTipoPendenza);
			}
		}

		// salvo il json ricevuto
		IOUtils.copy(is, baos);	
		String jsonRequest = baos.toString();

		PendenzeDAO pendenzeDAO = new PendenzeDAO(); 

		PutPendenzaDTO putVersamentoDTO = new PutPendenzaDTO(user);
		putVersamentoDTO.setStampaAvviso(stampaAvviso);
		putVersamentoDTO.setAvvisaturaDigitale(avvisaturaDigitale);
		ModoAvvisatura avvisaturaModalita = null;
		if(modalitaAvvisaturaDigitale != null) {
			avvisaturaModalita = modalitaAvvisaturaDigitale.equals(ModalitaAvvisaturaDigitale.ASINCRONA) ? ModoAvvisatura.ASICNRONA : ModoAvvisatura.SINCRONA;
		}
		putVersamentoDTO.setAvvisaturaModalita(avvisaturaModalita);
		putVersamentoDTO.setCustomReq(jsonRequest);
		putVersamentoDTO.setCodDominio(idDominio);
		putVersamentoDTO.setCodTipoVersamento(idTipoPendenza);
		putVersamentoDTO.setCodUo(idUnitaOperativa);
		putVersamentoDTO.setHeaders(this.getHeaders(getRequest()));
		putVersamentoDTO.setPathParameters(uriInfo.getPathParameters());
		putVersamentoDTO.setQueryParameters(uriInfo.getQueryParameters());

		PutPendenzaDTOResponse createOrUpdate = pendenzeDAO.createOrUpdateCustom(putVersamentoDTO);

		PendenzaCreata pc = new PendenzaCreata();
		pc.setIdDominio(createOrUpdate.getDominio().getCodDominio());
		pc.setNumeroAvviso(createOrUpdate.getVersamento().getNumeroAvviso());
		pc.pdf(createOrUpdate.getPdf());
		pc.setIdA2A(createOrUpdate.getVersamento().getApplicazione(null).getCodApplicazione());
		pc.setIdPendenza(createOrUpdate.getVersamento().getCodVersamentoEnte());
		if(createOrUpdate.getUo()!= null && !it.govpay.model.Dominio.EC.equals(createOrUpdate.getUo().getCodUo()))
			pc.setIdUnitaOperativa(createOrUpdate.getUo().getCodUo());
		Status responseStatus = createOrUpdate.isCreated() ?  Status.CREATED : Status.OK;
		this.log.debug(MessageFormat.format(BaseController.LOG_MSG_ESECUZIONE_METODO_COMPLETATA, methodName)); 
		return this.handleResponseOk(Response.status(responseStatus).entity(pc.toJSON(null)),transactionId).build();

	}catch (Exception e) {
		return this.handleException(uriInfo, httpHeaders, methodName, e, transactionId);
	} finally {
		this.log(ContextThreadLocal.get());
	}
}
 
Example 20
Source File: StatisticsResource.java    From sailfish-core with Apache License 2.0 2 votes vote down vote up
@GET
   @Path("register_tag")
   @Produces(MediaType.APPLICATION_XML)
public Response registerTag(@QueryParam("name") String tagName, 
		@QueryParam("group") String groupName) {
	
	XmlResponse xmlResponse = new XmlResponse();
	Status status = Status.OK;
	
	TagGroup loadedGroup = null;
	
	String actionsPerformed = "";
	
	try {
		
		StatisticsService service = getStatisticsService();
		
		if(StringUtils.isEmpty(tagName)) {
			
			throw new IllegalArgumentException("name parameter is mandatory");
			
		}
		
		if(isConnectedToDb()) {
			
			// verify group exists
			
			if(groupName != null) {
				
				loadedGroup = loadGroupByName(groupName);
				
				if(loadedGroup == null) {
					throw new IllegalArgumentException("Group [" + groupName + "] does not exists");
				}
				
			}
			
			Tag tag = loadTagByName(tagName);
			
			if(tag == null) { // need to add
				
				tag = new Tag();
				
				tag.setName(tagName);
				
				tag.setGroup(loadedGroup);
				
				service.getStorage().add(tag);
				
				actionsPerformed += "Added; ";
				
			} else { // Move to specified group if neccusarry
				
				if(tag.getGroup() == null || !tag.getGroup().equals(loadedGroup)) {
					
					tag.setGroup(loadedGroup);
					
					service.getStorage().update(tag);
					
					actionsPerformed += "Group set;";
					
				}
				
			}
			
			xmlResponse.setMessage(actionsPerformed + "Success;");
			
		} else {
			
			xmlResponse.setMessage("Disconnected from statistics DB");
			status = Status.BAD_REQUEST;
			
		}
	
	} catch(Exception e) {
		
		logger.error(e.getMessage(), e);
		
		xmlResponse.setMessage(e.getMessage());
		if(e.getCause() != null) {
			xmlResponse.setRootCause(e.getCause().toString());
		}
		status = Status.BAD_REQUEST;
		
	}
	
	return Response.
               status(status).
               entity(xmlResponse).
               build();
	
}