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

The following examples show how to use javax.ws.rs.core.Response.Status#CREATED . 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: RiconciliazioniController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addRiconciliazione(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idDominio, java.io.InputStream is) {
  	String methodName = "addRiconciliazione"; 
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);
	
	NuovaRiconciliazione incasso = JSONSerializable.parse(baos.toString(), NuovaRiconciliazione.class);
	incasso.validate();
	
	RichiestaIncassoDTO richiestaIncassoDTO = RiconciliazioniConverter.toRichiestaIncassoDTO(incasso, idDominio, user);
	
	IncassiDAO incassiDAO = new IncassiDAO();
	
	RichiestaIncassoDTOResponse richiestaIncassoDTOResponse = incassiDAO.richiestaIncasso(richiestaIncassoDTO);
	
	Riconciliazione incassoExt = RiconciliazioniConverter.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 2
Source File: TipiPendenzaController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addTipoPendenza(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idTipoPendenza, java.io.InputStream is) {
  	String methodName = "addTipoPendenza";  
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();
	TipoPendenzaPost tipoPendenzaRequest= JSONSerializable.parse(jsonRequest, TipoPendenzaPost.class);
	
	ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
	validatoreId.validaIdTipoVersamento("idTipoPendenza", idTipoPendenza);
	
	tipoPendenzaRequest.validate();
	
	PutTipoPendenzaDTO putIntermediarioDTO = TipiPendenzaConverter.getPutTipoPendenzaDTO(tipoPendenzaRequest, idTipoPendenza, user);
	
	TipoPendenzaDAO intermediariDAO = new TipoPendenzaDAO(false);
	
	PutTipoPendenzaDTOResponse putIntermediarioDTOResponse = intermediariDAO.createOrUpdateTipoPendenza(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 3
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 4
Source File: IntermediariController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addIntermediario(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idIntermediario, java.io.InputStream is) {
  	String methodName = "addIntermediario";  
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_PAGOPA), Arrays.asList(Diritti.SCRITTURA));
				
	String jsonRequest = baos.toString();
	IntermediarioPost intermediarioRequest= JSONSerializable.parse(jsonRequest, IntermediarioPost.class);
	
	ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
	validatoreId.validaIdIntermediario("idIntermediario", idIntermediario);
				
	intermediarioRequest.validate();
	
	PutIntermediarioDTO putIntermediarioDTO = IntermediariConverter.getPutIntermediarioDTO(intermediarioRequest, idIntermediario, user);
	
	IntermediariDAO intermediariDAO = new IntermediariDAO(false);
	
	PutIntermediarioDTOResponse putIntermediarioDTOResponse = intermediariDAO.createOrUpdateIntermediario(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 5
Source File: IncassiController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addRiconciliazione(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idDominio, java.io.InputStream is) {
  	String methodName = "addRiconciliazione"; 
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.RENDICONTAZIONI_E_INCASSI), 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 6
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 7
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 8
Source File: DominiController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addContiAccredito(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idDominio, String ibanAccredito, java.io.InputStream is) {
	String methodName = "addContiAccredito";  
	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();
		ContiAccreditoPost ibanAccreditoRequest= JSONSerializable.parse(jsonRequest, ContiAccreditoPost.class);

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

		ibanAccreditoRequest.validate();

		PutIbanAccreditoDTO putibanAccreditoDTO = DominiConverter.getPutIbanAccreditoDTO(ibanAccreditoRequest, idDominio, ibanAccredito, user);

		DominiDAO dominiDAO = new DominiDAO(false);

		PutIbanAccreditoDTOResponse putIbanAccreditoDTOResponse = dominiDAO.createOrUpdateIbanAccredito(putibanAccreditoDTO);

		Status responseStatus = putIbanAccreditoDTOResponse.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 9
Source File: IntermediariController.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
public Response addStazione(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idIntermediario, String idStazione, java.io.InputStream is) {
  	String methodName = "addStazione";  
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_PAGOPA), Arrays.asList(Diritti.SCRITTURA));
	
	String jsonRequest = baos.toString();
	StazionePost stazioneRequest= JSONSerializable.parse(jsonRequest, StazionePost.class);
	
	
	ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
	validatoreId.validaIdIntermediario("idIntermediario", idIntermediario);
	validatoreId.validaIdStazione("idStazione", idStazione);
	
	stazioneRequest.validate();
	
	PutStazioneDTO putStazioneDTO = StazioniConverter.getPutStazioneDTO(stazioneRequest, idIntermediario, idStazione, user);
	
	IntermediariDAO intermediariDAO = new IntermediariDAO(false);
	
	PutStazioneDTOResponse putIntermediarioDTOResponse = intermediariDAO.createOrUpdateStazione(putStazioneDTO);
	
	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: 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 11
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 12
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 13
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 14
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void givenSomeValidAccessTokenAndSubdomainAndValidRequestWhenCancelingFulfillmentsThenCancelFulfillments()
		throws JsonProcessingException {

	final ShopifyLineItem lineItem = new ShopifyLineItem();
	lineItem.setId("some_line_item_id");
	lineItem.setSku("some_sku");
	lineItem.setQuantity(5L);

	final String expectedPath = new StringBuilder().append(FORWARD_SLASH).append(ShopifySdk.VERSION_2020_01)
			.append(FORWARD_SLASH).append(ShopifySdk.ORDERS).append("/1234/").append(ShopifySdk.FULFILLMENTS)
			.append("/4567/").append(ShopifySdk.CANCEL).toString();
	final ShopifyFulfillment currentFulfillment = buildShopifyFulfillment(lineItem);
	final ShopifyFulfillmentRoot shopifyFulfillmentRoot = new ShopifyFulfillmentRoot();
	shopifyFulfillmentRoot.setFulfillment(currentFulfillment);

	final String expectedResponseBodyString = getJsonString(ShopifyFulfillmentRoot.class, shopifyFulfillmentRoot);

	final Status expectedStatus = Status.CREATED;
	final int expectedStatusCode = expectedStatus.getStatusCode();
	final JsonBodyCapture actualRequestBody = new JsonBodyCapture();
	driver.addExpectation(
			onRequestTo(expectedPath).withHeader(ShopifySdk.ACCESS_TOKEN_HEADER, accessToken)
					.withMethod(Method.POST).capturingBodyIn(actualRequestBody),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));

	final ShopifyFulfillment actualShopifyFulfillment = shopifySdk.cancelFulfillment("1234", "4567");

	assertEquals(false, actualRequestBody.getContent().get("notify_customer").asBoolean());
	assertEquals(0, actualRequestBody.getContent().get("line_items").size());
	assertEquals(0, actualRequestBody.getContent().get("tracking_urls").size());

	assertValidFulfillment(currentFulfillment, actualShopifyFulfillment);
}
 
Example 15
Source File: PendenzeController.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
public Response pendenzeIdA2AIdPendenzaPUT(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idA2A, String idPendenza, java.io.InputStream is, Boolean stampaAvviso, Boolean avvisaturaDigitale, ModalitaAvvisaturaDigitale modalitaAvvisaturaDigitale) {
	String methodName = "pendenzeIdA2AIdPendenzaPUT";  
	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().setIdPendenza(idPendenza);
		((GpContext) (ContextThreadLocal.get()).getApplicationContext()).getEventoCtx().setIdA2A(idA2A);
		
		// salvo il json ricevuto
		IOUtils.copy(is, baos);

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

		ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
		validatoreId.validaIdApplicazione("idA2A", idA2A);
		validatoreId.validaIdPendenza("idPendenza", idPendenza);
		
		// filtro sull'applicazione			
		if(!AutorizzazioneUtils.getAuthenticationDetails(user).getApplicazione().getCodApplicazione().equals(idA2A)) {
			throw new GovPayException(EsitoOperazione.APP_002, AutorizzazioneUtils.getAuthenticationDetails(user).getApplicazione().getCodApplicazione(), idA2A);
		}

		String jsonRequest = baos.toString();
		PendenzaPut pendenzaPost= JSONSerializable.parse(jsonRequest, PendenzaPut.class);
		pendenzaPost.validate();

		Versamento versamento = PendenzeConverter.getVersamentoFromPendenza(pendenzaPost, idA2A, idPendenza);
		
		PutPendenzaDTO putVersamentoDTO = new PutPendenzaDTO(user);
		putVersamentoDTO.setVersamento(versamento);
		putVersamentoDTO.setStampaAvviso(stampaAvviso);
		putVersamentoDTO.setAvvisaturaDigitale(avvisaturaDigitale);
		ModoAvvisatura avvisaturaModalita = null;
		if(modalitaAvvisaturaDigitale != null) {
			avvisaturaModalita = modalitaAvvisaturaDigitale.equals(ModalitaAvvisaturaDigitale.ASINCRONA) ? ModoAvvisatura.ASICNRONA : ModoAvvisatura.SINCRONA;
		}

		putVersamentoDTO.setAvvisaturaModalita(avvisaturaModalita);
		
		String codDominio = versamento.getCodDominio();
		// controllo che il dominio sia autorizzato
		if(!AuthorizationManager.isDominioAuthorized(putVersamentoDTO.getUser(), codDominio)) {
			throw AuthorizationManager.toNotAuthorizedException(putVersamentoDTO.getUser(), codDominio);
		}

		PendenzeDAO pendenzeDAO = new PendenzeDAO(); 

		PutPendenzaDTOResponse createOrUpdate = pendenzeDAO.createOrUpdate(putVersamentoDTO);
		
		PendenzaCreata pc = new PendenzaCreata();
		pc.setIdDominio(createOrUpdate.getDominio().getCodDominio());
		pc.setNumeroAvviso(createOrUpdate.getVersamento().getNumeroAvviso());
		pc.pdf(createOrUpdate.getPdf());
		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 16
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void givenSomeCustomCollectionsCreationRequestCreateAndReturnCustomCollection()
		throws JsonProcessingException {
	final String expectedCreationPath = new StringBuilder().append(FORWARD_SLASH)
			.append(ShopifySdk.CUSTOM_COLLECTIONS).toString();
	final ShopifyCustomCollectionRoot shopifyCustomCollectionRoot = new ShopifyCustomCollectionRoot();
	final ShopifyCustomCollection shopifyCustomCollection = new ShopifyCustomCollection();

	shopifyCustomCollection.setId("123");
	shopifyCustomCollection.setTitle("Some Title");
	shopifyCustomCollection.setHandle("handle");
	shopifyCustomCollection.setPublished(true);
	shopifyCustomCollection.setBodyHtml("Some Description");

	shopifyCustomCollection.setTemplateSuffix("some-title");
	shopifyCustomCollection.setPublishedScope("global");
	shopifyCustomCollection.setSortOrder("alpha-asc");

	shopifyCustomCollectionRoot.setCustomCollection(shopifyCustomCollection);

	final String expectedResponseBodyString = getJsonString(ShopifyCustomCollectionRoot.class,
			shopifyCustomCollectionRoot);

	final Status expectedCreationStatus = Status.CREATED;
	final int expectedCreationStatusCode = expectedCreationStatus.getStatusCode();

	final JsonBodyCapture actualCreateRequestBody = new JsonBodyCapture();
	driver.addExpectation(
			onRequestTo(expectedCreationPath).withHeader(ShopifySdk.ACCESS_TOKEN_HEADER, accessToken)
					.withMethod(Method.POST).capturingBodyIn(actualCreateRequestBody),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON)
					.withStatus(expectedCreationStatusCode));

	final ShopifyCustomCollectionCreationRequest shopifyCustomCollectionCreationRequest = ShopifyCustomCollectionCreationRequest
			.newBuilder().withTitle("Some Title").withBodyHtml("Some Description").withHandle("handle")
			.withTemplateSuffix("some-title").withPublishedScope("global").withSortOrder("alpha-asc")
			.isPublished(true).build();

	final ShopifyCustomCollection actualShopifyCustomCollection = shopifySdk
			.createCustomCollection(shopifyCustomCollectionCreationRequest);

	assertCustomCollection(shopifyCustomCollection, actualShopifyCustomCollection);

	assertEquals(shopifyCustomCollectionCreationRequest.getRequest().getTitle(),
			actualCreateRequestBody.getContent().get("custom_collection").get("title").asText());
	assertEquals(shopifyCustomCollectionCreationRequest.getRequest().getBodyHtml(),
			actualCreateRequestBody.getContent().get("custom_collection").get("body_html").asText());
	assertEquals(shopifyCustomCollectionCreationRequest.getRequest().getHandle(),
			actualCreateRequestBody.getContent().get("custom_collection").get("handle").asText());
	assertEquals(shopifyCustomCollectionCreationRequest.getRequest().getPublishedScope(),
			actualCreateRequestBody.getContent().get("custom_collection").get("published_scope").asText());
	assertEquals(shopifyCustomCollectionCreationRequest.getRequest().getSortOrder(),
			actualCreateRequestBody.getContent().get("custom_collection").get("sort_order").asText());
	assertEquals(shopifyCustomCollectionCreationRequest.getRequest().isPublished(),
			actualCreateRequestBody.getContent().get("custom_collection").get("published").asBoolean());
	assertNotNull(actualShopifyCustomCollection);
}
 
Example 17
Source File: PendenzeController.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
public Response addPendenza(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , String idA2A, String idPendenza, java.io.InputStream is, Boolean stampaAvviso, Boolean avvisaturaDigitale, ModalitaAvvisaturaDigitale modalitaAvvisaturaDigitale) {
	String methodName = "addPendenza";  
	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().setIdPendenza(idPendenza);
		((GpContext) (ContextThreadLocal.get()).getApplicationContext()).getEventoCtx().setIdA2A(idA2A);
		// 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.PENDENZE), Arrays.asList(Diritti.SCRITTURA));

		ValidatoreIdentificativi validatoreId = ValidatoreIdentificativi.newInstance();
		validatoreId.validaIdApplicazione("idA2A", idA2A);
		validatoreId.validaIdPendenza("idPendenza", idPendenza);

		String jsonRequest = baos.toString();
		PendenzaPut pendenzaPost= JSONSerializable.parse(jsonRequest, PendenzaPut.class);
		pendenzaPost.validate();

		Versamento versamento = PendenzeConverter.getVersamentoFromPendenza(pendenzaPost, idA2A, idPendenza);

		// controllo che il dominio, uo e tipo versamento siano autorizzati
		if(!AuthorizationManager.isTipoVersamentoUOAuthorized(user, versamento.getCodDominio(), versamento.getCodUnitaOperativa(), versamento.getCodTipoVersamento())) {
			throw AuthorizationManager.toNotAuthorizedException(user, versamento.getCodDominio(), versamento.getCodUnitaOperativa(), versamento.getCodTipoVersamento());
		}

		PendenzeDAO pendenzeDAO = new PendenzeDAO(); 

		PutPendenzaDTO putVersamentoDTO = new PutPendenzaDTO(user);
		putVersamentoDTO.setVersamento(versamento);
		putVersamentoDTO.setStampaAvviso(stampaAvviso);
		putVersamentoDTO.setAvvisaturaDigitale(avvisaturaDigitale);
		ModoAvvisatura avvisaturaModalita = null;
		if(modalitaAvvisaturaDigitale != null) {
			avvisaturaModalita = modalitaAvvisaturaDigitale.equals(ModalitaAvvisaturaDigitale.ASINCRONA) ? ModoAvvisatura.ASICNRONA : ModoAvvisatura.SINCRONA;
		}

		putVersamentoDTO.setAvvisaturaModalita(avvisaturaModalita);

		PutPendenzaDTOResponse createOrUpdate = pendenzeDAO.createOrUpdate(putVersamentoDTO);

		PendenzaCreata pc = new PendenzaCreata();
		pc.setIdDominio(createOrUpdate.getDominio().getCodDominio());
		if(createOrUpdate.getUo()!= null && !it.govpay.model.Dominio.EC.equals(createOrUpdate.getUo().getCodUo()))
			pc.setIdUnitaOperativa(createOrUpdate.getUo().getCodUo());
		pc.setNumeroAvviso(createOrUpdate.getVersamento().getNumeroAvviso());
		pc.pdf(createOrUpdate.getPdf());
		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 18
Source File: PendenzeController.java    From govpay with GNU General Public License v3.0 4 votes vote down vote up
public Response addPendenza(Authentication user, UriInfo uriInfo, HttpHeaders httpHeaders , java.io.InputStream is, Boolean stampaAvviso, Boolean avvisaturaDigitale, ModalitaAvvisaturaDigitale modalitaAvvisaturaDigitale) {
	String methodName = "addPendenza";  
	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.PENDENZE), Arrays.asList(Diritti.SCRITTURA));

		String jsonRequest = baos.toString();
		PendenzaPost pendenzaPost= JSONSerializable.parse(jsonRequest, PendenzaPost.class);

		((GpContext) (ContextThreadLocal.get()).getApplicationContext()).getEventoCtx().setIdPendenza(pendenzaPost.getIdPendenza());
		((GpContext) (ContextThreadLocal.get()).getApplicationContext()).getEventoCtx().setIdA2A(pendenzaPost.getIdA2A());

		pendenzaPost.validate();

		Versamento versamento = PendenzeConverter.getVersamentoFromPendenza(pendenzaPost);

		// controllo che il dominio, uo e tipo versamento siano autorizzati
		if(!AuthorizationManager.isTipoVersamentoUOAuthorized(user, versamento.getCodDominio(), versamento.getCodUnitaOperativa(), versamento.getCodTipoVersamento())) {
			throw AuthorizationManager.toNotAuthorizedException(user, versamento.getCodDominio(), versamento.getCodUnitaOperativa(), versamento.getCodTipoVersamento());
		}

		PendenzeDAO pendenzeDAO = new PendenzeDAO(); 

		PutPendenzaDTO putVersamentoDTO = new PutPendenzaDTO(user);
		putVersamentoDTO.setVersamento(versamento);
		putVersamentoDTO.setStampaAvviso(stampaAvviso);
		putVersamentoDTO.setAvvisaturaDigitale(avvisaturaDigitale);
		ModoAvvisatura avvisaturaModalita = null;
		if(modalitaAvvisaturaDigitale != null) {
			avvisaturaModalita = modalitaAvvisaturaDigitale.equals(ModalitaAvvisaturaDigitale.ASINCRONA) ? ModoAvvisatura.ASICNRONA : ModoAvvisatura.SINCRONA;
		}

		putVersamentoDTO.setAvvisaturaModalita(avvisaturaModalita);

		PutPendenzaDTOResponse createOrUpdate = pendenzeDAO.createOrUpdate(putVersamentoDTO);

		PendenzaCreata pc = new PendenzaCreata();
		pc.setIdDominio(createOrUpdate.getDominio().getCodDominio());
		if(createOrUpdate.getUo()!= null && !it.govpay.model.Dominio.EC.equals(createOrUpdate.getUo().getCodUo()))
			pc.setIdUnitaOperativa(createOrUpdate.getUo().getCodUo());
		pc.setNumeroAvviso(createOrUpdate.getVersamento().getNumeroAvviso());
		pc.pdf(createOrUpdate.getPdf());
		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 19
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void givenSomeValidAccessTokenAndSubdomainAndSomeProductMetafieldWhenCreatingProductMetafieldThenCreateAndProductMetafield()
		throws Exception {

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

	final Metafield metafield = new Metafield();
	metafield.setCreatedAt(new DateTime());
	metafield.setUpdatedAt(new DateTime());
	metafield.setValueType(MetafieldValueType.STRING);
	metafield.setId("123");
	metafield.setKey("channelape_product_id");
	metafield.setNamespace("channelape");
	metafield.setOwnerId("123");
	metafield.setOwnerResource("product");
	metafield.setValue("38728743");

	final MetafieldRoot metafieldRoot = new MetafieldRoot();
	metafieldRoot.setMetafield(metafield);

	final String expectedResponseBodyString = getJsonString(MetafieldRoot.class, metafieldRoot);

	final Status expectedStatus = Status.CREATED;
	final int expectedStatusCode = expectedStatus.getStatusCode();
	final JsonBodyCapture actualRequestBody = new JsonBodyCapture();
	driver.addExpectation(
			onRequestTo(expectedPath).withHeader("X-Shopify-Access-Token", accessToken).withMethod(Method.POST)
					.capturingBodyIn(actualRequestBody),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));

	final ShopifyProductMetafieldCreationRequest shopifyProductMetafieldCreationRequest = ShopifyProductMetafieldCreationRequest
			.newBuilder().withProductId("123").withNamespace("channelape").withKey("channelape_product_id")
			.withValue("38728743").withValueType(MetafieldValueType.STRING).build();
	final Metafield actualMetafield = shopifySdk.createProductMetafield(shopifyProductMetafieldCreationRequest);

	assertEquals(shopifyProductMetafieldCreationRequest.getRequest().getKey().toString(),
			actualRequestBody.getContent().get("metafield").get("key").asText());
	assertEquals(shopifyProductMetafieldCreationRequest.getRequest().getValue(),
			actualRequestBody.getContent().get("metafield").get("value").asText());

	assertEquals(shopifyProductMetafieldCreationRequest.getRequest().getNamespace(),
			actualRequestBody.getContent().get("metafield").get("namespace").asText());
	assertEquals(shopifyProductMetafieldCreationRequest.getRequest().getValueType().toString(),
			actualRequestBody.getContent().get("metafield").get("value_type").asText());
	assertNotNull(actualMetafield);
	assertEquals(metafield.getId(), actualMetafield.getId());
	assertEquals(0, metafield.getCreatedAt().compareTo(actualMetafield.getCreatedAt()));
	assertEquals(metafield.getKey(), actualMetafield.getKey());
	assertEquals(metafield.getNamespace(), actualMetafield.getNamespace());
	assertEquals(metafield.getOwnerId(), actualMetafield.getOwnerId());
	assertEquals(metafield.getOwnerResource(), actualMetafield.getOwnerResource());
	assertEquals(0, metafield.getUpdatedAt().compareTo(actualMetafield.getUpdatedAt()));
	assertEquals(metafield.getValue(), actualMetafield.getValue());
	assertEquals(metafield.getValueType(), actualMetafield.getValueType());
}
 
Example 20
Source File: ShopifySdkTest.java    From shopify-sdk with Apache License 2.0 4 votes vote down vote up
@Test
public void givenSomeValidAccessTokenAndSubdomainAndValidRequestWhenCreatingGiftCardThenCreateAndReturn()
		throws Exception {

	final String expectedPath = new StringBuilder().append(FORWARD_SLASH).append(ShopifySdk.GIFT_CARDS).toString();
	final ShopifyGiftCardRoot shopifyGiftCardRoot = new ShopifyGiftCardRoot();
	final ShopifyGiftCard shopifyGiftCard = new ShopifyGiftCard();

	shopifyGiftCard.setInitialValue(new BigDecimal(41.21));
	shopifyGiftCard.setCode("ABCDEFGHIJKLMNOP");
	shopifyGiftCard.setBalance(new BigDecimal(41.21));
	final DateTime someDateTime = new DateTime();
	shopifyGiftCard.setExpiresOn(someDateTime);
	shopifyGiftCard.setCreatedAt(someDateTime);
	shopifyGiftCard.setCurrency("USD");
	shopifyGiftCard.setLastCharacters("MNOP");
	shopifyGiftCard.setId("1");
	shopifyGiftCard.setNote("Happy Birthday!");

	shopifyGiftCardRoot.setGiftCard(shopifyGiftCard);

	final String expectedResponseBodyString = getJsonString(ShopifyGiftCardRoot.class, shopifyGiftCardRoot);

	final Status expectedStatus = Status.CREATED;
	final int expectedStatusCode = expectedStatus.getStatusCode();
	final JsonBodyCapture actualRequestBody = new JsonBodyCapture();
	driver.addExpectation(
			onRequestTo(expectedPath).withHeader("X-Shopify-Access-Token", accessToken).withMethod(Method.POST)
					.capturingBodyIn(actualRequestBody),
			giveResponse(expectedResponseBodyString, MediaType.APPLICATION_JSON).withStatus(expectedStatusCode));

	final ShopifyGiftCardCreationRequest shopifyGiftCardCreationRequest = ShopifyGiftCardCreationRequest
			.newBuilder().withInitialValue(new BigDecimal(42.21)).withCode("ABCDEFGHIJKLMNOP").withCurrency("USD")
			.build();
	final ShopifyGiftCard actualShopifyGiftCard = shopifySdk.createGiftCard(shopifyGiftCardCreationRequest);

	assertEquals("ABCDEFGHIJKLMNOP", actualRequestBody.getContent().get("gift_card").get("code").asText());
	assertEquals("USD", actualRequestBody.getContent().get("gift_card").get("currency").asText());
	assertEquals(BigDecimal.valueOf(42.21),
			actualRequestBody.getContent().get("gift_card").get("initial_value").decimalValue());

	assertEquals(shopifyGiftCard.getId(), actualShopifyGiftCard.getId());
	assertEquals(shopifyGiftCard.getApiClientId(), actualShopifyGiftCard.getApiClientId());
	assertEquals(shopifyGiftCard.getInitialValue(), actualShopifyGiftCard.getInitialValue());
	assertEquals(0, shopifyGiftCard.getCreatedAt().compareTo(actualShopifyGiftCard.getCreatedAt()));
	assertEquals(shopifyGiftCard.getBalance(), actualShopifyGiftCard.getBalance());
	assertEquals(shopifyGiftCard.getCode(), actualShopifyGiftCard.getCode());
	assertEquals(0, shopifyGiftCard.getExpiresOn().compareTo(actualShopifyGiftCard.getExpiresOn()));
	assertNull(actualShopifyGiftCard.getDisabledAt());
	assertEquals(shopifyGiftCard.getLineItemId(), actualShopifyGiftCard.getLineItemId());
	assertEquals(shopifyGiftCard.getNote(), actualShopifyGiftCard.getNote());
	assertEquals(shopifyGiftCard.getLastCharacters(), actualShopifyGiftCard.getLastCharacters());
	assertEquals(shopifyGiftCard.getTemplateSuffix(), actualShopifyGiftCard.getTemplateSuffix());
	assertNull(actualShopifyGiftCard.getUpdatedAt());
}