display pdf / download pdf from Oracle databse using spring and hibernate - web-services

I have an object with field
#Column(name = "PDF")
#Lob #Basic(fetch=javax.persistence.FetchType.LAZY)
private byte[] pdf;
My dao retrieves this object succesfully using the enitity manager findbyid() method.
I want to display this pdf on browser or download the pdf when the request comes to my controller.
This is what i did.
#Autowired
DocDownloadService docService;
HttpServletResponse response;
#RequestMapping("/document/view/{docID}")
public String getAlert(#PathVariable("docID") String docId){
docService.downloadDoc(docId, response);
return null;
}
And my service
#Override
#Transactional
public String downloadDoc(String docId, HttpServletResponse response){
MyDoc doc = this.getDocById(docId); //brings document object from my DAO
try {
response.addHeader("Content-Disposition", "attachment;filename=report.pdf");
response.setContentType("application/pdf");
response.getOutputStream().write(doc.getPdf(), 0, doc.getPdf().length);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
I get a null pointer exception at the "response.addheaders line.. I am not sure why. I have looked through other posts and tried all those methods but it didnt help.
Any pointers will be appreciated.

Try this
#RequestMapping("/document/view/{docID}")
public String getAlert(#PathVariable("docID") String docId, HttpServletResponse response){
Also, it is better if you handle the response.outputstream within the controller rather than handling it at the service.

Related

wso2 identity server custom handler reading from properties file

public class UserRegistrationCustomEventHandler extends AbstractEventHandler {
JSONObject jsonObject = null;
private static final Log log = LogFactory.getLog(UserRegistrationCustomEventHandler.class);
#Override
public String getName() {
return "customClaimUpdate";
}
if (IdentityEventConstants.Event.POST_SET_USER_CLAIMS.equals(event.getEventName())) {
String tenantDomain = (String) event.getEventProperties()
.get(IdentityEventConstants.EventProperty.TENANT_DOMAIN);
String userName = (String) event.getEventProperties().get(IdentityEventConstants.EventProperty.USER_NAME);
Map<String, Object> eventProperties = event.getEventProperties();
String eventName = event.getEventName();
UserStoreManager userStoreManager = (UserStoreManager) eventProperties.get(IdentityEventConstants.EventProperty.USER_STORE_MANAGER);
// String userStoreDomain = UserCoreUtil.getDomainName(userStoreManager.getRealmConfiguration());
#SuppressWarnings("unchecked")
Map<String, String> claimValues = (Map<String, String>) eventProperties.get(IdentityEventConstants.EventProperty
.USER_CLAIMS);
String emailId = claimValues.get("http://wso2.org/claims/emailaddress");
userName = "USERS/"+userName;
JSONObject json = new JSONObject();
json.put("userName",userName );
json.put("emailId",emailId );
log.info("JSON:::::::"+json);
// Sample API
//String apiValue = "http://192.168.1.X:8080/SomeService/user/updateUserEmail?email=sujith#gmail.com&userName=USERS/sujith";
try {
URL url = new URL(cityAppUrl) ;
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(5000);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
log.info("CONN:::::::::::::"+con);
OutputStream os = con.getOutputStream();
os.write(cityAppUrl.toString().getBytes("UTF-8"));
os.close();
InputStream in = new BufferedInputStream(con.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
jsonObject = new JSONObject(result);
log.info("JSON OBJECT:::::::::"+jsonObject);
}
catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void init(InitConfig configuration) throws IdentityRuntimeException {
super.init(configuration);
}
#Override
public int getPriority(MessageContext messageContext) {
return 250;
}
}
I'm using wso2 identity server 5.10.0 and have to push the updated claim value to an API so I'm using a custom handler and have subscribed to POST_SET_USER_CLAIMS, i have to read the API value from deployment.toml file in jave code of the custom handler. So can any one please help here to read the value from deployment file
I can fetch the updated claim value in logs but im not able to get the API value. So can anyone help me here to read the value from deployment file.
Since the API path is required inside your custom event handler, let's define the API path value as one of the properties of the event handler.
Add the deployment.toml config as follows.
[[event_handler]]
name= "UserRegistrationCustomEventHandler"
subscriptions =["POST_SET_USER_CLAIMS"]
properties.apiPath = "http://192.168.1.X:8080/SomeService/user/updateUserEmail"
Once you restart the server identity-event.properties file populates the given configs.
In your custom event handler java code needs to read the config from identity-event.properties file. The file reading is done at the server startup and every config is loaded to the memory.
By adding this to your java code, you can load to configured value in the property.
configs.getModuleProperties().getProperty("UserRegistrationCustomEventHandler.apiPath")
NOTE: property name needs to be defined as <event_handler_name>.<property_name>
Here is a reference to such event hanlder's property loading code snippet https://github.com/wso2-extensions/identity-governance/blob/68e3f2d5e246b6a75f48e314ee1019230c662b55/components/org.wso2.carbon.identity.password.policy/src/main/java/org/wso2/carbon/identity/password/policy/handler/PasswordPolicyValidationHandler.java#L128-L133

Spring boot testing REST controller with JPA

I am having issues trying to test
THe following REST method
#GetMapping
#RequestMapping("/create")
ResponseEntity<Order> createOrders(#RequestBody String body) {
ObjectMapper mapper = new ObjectMapper();
try{
Map<String,Object> mapBody = mapper.readValue(body,Map.class);
Long cusId = Long.valueOf((int)mapBody.get("customer_id"));
Customer customer = customerRepository.findOne(cusId);
Product product = productRepository.findByProductName((String)mapBody.get("product_name"));
Order order = new Order(customer,product,(int)mapBody.get("quantity"));
orderRepository.saveAndFlush(order);
return new ResponseEntity(order, HttpStatus.OK);
}
catch(Exception e){
e.printStackTrace();
return new ResponseEntity("error with original port", HttpStatus.EXPECTATION_FAILED);
}
}
I have tried numrous things so for and nothing seems to work.
Doing a call to the REST method works fine but it seems I can use either
#AutoConfigureMockMvc or #DataJpaTest in my testing
My code is currently as follows
#SpringBootTest
#AutoConfigureMockMvc
#DataJpaTest
public class OrderTest {
#Autowired
private MockMvc mockMvc;
#Autowired
private ProductRepository productRepositoryTest;
#Autowired
private CustomerRepository customerRepositoryTest;
#Test
public void submitNewOrdersForBricks() {
try {
Customer cus1 = new Customer("cus1");
customerRepositoryTest.saveAndFlush(cus1);
Product pro1 = new Product("brick1","red brick",0.96);
productRepositoryTest.saveAndFlush(pro1);
this.mockMvc.perform(post("/create")
.content("{\"customer_id\":"+cus1.getCustomerId()+",\"product_name\":\"brick1\",\"quantity\":150}")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print()).andExpect(status().isCreated())
.andExpect(jsonPath("$.order_id").value(1));
}
catch(Exception e){
e.printStackTrace();
}
}
}
I have also tried using
when(customerRepository.findOne(cusId)).thenReturn(cus1);
This did not have any effect in my controller.
Please note that the controller method createOrders is only called when I remove #DataJpaTest, but then IDs are not created for customer and product.
Any help would be great.
#DataJpaTest is for repository test. In this case, #DataJpaTest is useless.
And, in test class, you missed
#Autowired
private OrderRepository orderRepository;

Spring boot How to access Appconfig properties in test case

I am new to web services and spring boot. I have written a service for which I am now writing a test case.
My application gets Soap request, parses the body and saves contents into database.
My test case tests this service.
When I run the application and send a request from Postman, it runs alright. But when I call my service method from test case, I get nullpointer for JaxBcontext.
I have declared Jaxbcontext in my AppConfig.java (which is annotated with #Configuration and my jaxb is a bean with #Bean annotation) in my service, I have #autowire to use jaxbcontext.
I have pasted code snippets for clarity. Please advise me what I am doing wrongly here.
My test case
public class ReferralExchangeEndpointTest {
ReferralExchangeEndpoint referralExchangeEndpoint = new ReferralExchangeEndpoint();
JAXBContext jbcTest;
Marshaller marshaller;
Unmarshaller unmarshaller;
public ReferralExchangeEndpointTest() throws JAXBException {
}
#Before
public void setUp() throws Exception {
jbcTest = JAXBContext.newInstance(
"our app schema"); // this is working fine, I have replaced schema with this text for posting it in stack.
ObjectFactory factory = new ObjectFactory();
marshaller = jbcTest.createMarshaller();
unmarshaller = jbcTest.createUnmarshaller();
}
#Test
public void send() throws Exception {
File payload = new File("payload.xml");
Object x = unmarshaller.unmarshal(payload);
JAXBElement jbe = (JAXBElement) x;
System.out.println(jbe.getName());
Object test = jbe.getValue();
SendRequestMessage sendRequestMessage = (SendRequestMessage) jbe.getValue();
// Method in test.
referralExchangeEndpoint.send(sendRequestMessage);
}
}
My service class
#Endpoint
public class ReferralExchangeEndpoint {
public static final Logger logger = LoggerFactory.getLogger(ReferralExchangeEndpoint.class);
#Autowired
private JAXBContext jaxbContext;
#Autowired
.
.
.
private Form parseBody(String payLoadBody) {
try {
Unmarshaller um = jaxbContext.createUnmarshaller();
return (Form) um.unmarshal(new StringReader(payLoadBody));
} catch (Exception e) {
throw new RuntimeException("Failed to extract the form from the payload body", e);
}
}
My appconfig file
#Configuration
public class AppConfig {
#Bean
public JAXBContext jaxbContext() throws JAXBException {
return
JAXBContext.newInstance("packagename");
}
#Bean public MessagingService messagingService() {
return new MessagingService();
}
}
Thanks.
Kavitha.
** Solved **
My test case now looks like this.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {AppConfig.class})`
public class ReferralExchangeEndpointTest {
#Autowired
ReferralExchangeEndpoint referralExchangeEndpoint;
#Autowired
private JAXBContext jaxbContext;
private Marshaller marshaller;
private Unmarshaller unmarshaller;
#Before
public void setUp() throws Exception {
marshaller = jaxbContext.createMarshaller();
unmarshaller = jaxbContext.createUnmarshaller();
}
#Test
public void send() throws Exception {
File payload = new File("src/test/resources/payload.xml");
JAXBElement jbe = (JAXBElement) unmarshaller.unmarshal(payload);
SendRequestMessage sendRequestMessage = (SendRequestMessage) jbe.getValue();
JAXBElement<SendResponseMessage> response = referralExchangeEndpoint.send(sendRequestMessage);
//TODO add remaining assertions on response after confirming what should the service return for these attributes.
assertEquals("SiteId wrong in response: ", "siteId", response.getValue().getSiteId());
}
}`

Unit Testing StreamingOuput as Response entity Jersey

I am doing something similar to mentioned in
Example of using StreamingOutput as Response entity in Jersey
#GET
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response streamExample(#Context UriInfo uriInfo) {
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream os) throws IOException,WebApplicationException {
try{
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
//Read resource from jar
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("public/" + uriInfo.getPath());
...//manipulate the inputstream and build string with StringBuilder here//.......
String inputData = builder.toString();
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
writer.write(inputData);
writer.flush();
} catch (ExceptionE1) {
throw new WebApplicationException();
}
}
};
return Response.ok(stream,MediaType.APPLICATION_OCTET_STREAM).build();
}
I am trying to unit test this by mocking URIInfo like mentioned in How to get instance of javax.ws.rs.core.UriInfo
public void testStreamExample() throws IOException, URISyntaxException {
UriInfo mockUriInfo = mock(UriInfo.class);
Mockito.when(mockUriInfo.getPath()).thenReturn("unusal-path");
Response response = myresource.streamExample(mockUriInfo);}
I want to be able to check that I get an Exception when I switch the path to jar to something else.But, when I run/debug the test, I never enter the
public void write(OutputStream os) throws IOException,
WebApplicationException {...}
part and I only always hit the return Response.ok(stream,MediaType.APPLICATION_OCTET_STREAM).build();
Am I missing something very obvious here??
Because the stream is not written to until it hits the MessageBodyWriter (which is the component that ends up calling the StreamingOutput#write).
What you can do, is just get the Response from the return and call Response#getEntity() (which returns an Object) and cast it to StreamingOutput. Then call the write method yourself, passing an OutputStream, maybe a ByteArrayOutputStream so you can get the contents as a byte[] to check it. It all would look something like
UriInfo mockInfo = mockUriInfo();
Response response = resource.streamExample(mockInfo);
StreamingOutput output = (StreamingOutput) response.getEntity();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
output.write(baos);
byte[] data = baos.toByteArray();
String s = new String(data, StandardCharsets.UTF_8);
assertThat(s, is("SomeCharacterData"));

How to get header value in UploadStringCompletedEventHandler method ASP.NET (Web API Service using HttpClient)

In My Windows Phone 8 App, I create WebClient object and initiate the with UploadStringAsync. and Create webClientLogin.UploadStringCompleted using UploadStringCompletedEventHandler.
WebClient webClientLogin = new WebClient();
webClientLogin.Headers["content-type"] = "application/json";
webClientLogin.UploadStringCompleted += new UploadStringCompletedEventHandler(webClientUploadStringCompleted);
webClientLogin.UploadStringAsync(new Uri(URL + "LogIn"), "POST", stockiestData);
Here stockiestData is Encoded Using Encoding.UTF8
I Get response as well.
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
var logindetails = JsonConvert.DeserializeObject<LogResponse>(e.Result);
}
But I need to get the Header in this above method (webClientUploadStringCompleted).
I send the header like follows HttpContext.Current.Response.AppendHeader("Msg","Checked");
This response created in WebApi
How to get this?
Able to get header values using sender Object in the following method.
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
}
We have to cast this object as WebClient.
Following method shows how to send in WebApi
[HttpPost]
[ActionName("LogIn")]
public dynamic LogIn(List<Student> Student, HttpRequestMessage request)
{
if (Student!= null)
{
HttpContext.Current.Response.AppendHeader("Msg", "Resived");
}
Following code shows you how to get header value from Windows phone 8
private void webClientUploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
WebClient web = (WebClient)sender;
WebHeaderCollection myWebHeaderCollection = (WebHeaderCollection)web.ResponseHeaders;
var v = web.ResponseHeaders["Msg"];
}