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"));
Related
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
i have a GET method to connect to a webservices in xamarin. The method works fine, but when my phone is not connected to internet, the application crash, i would like to know how to avoid this ? Thanks for your answers:
static public string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
HttpWebRequest throws an Exception if there is no internet connection.
You have handled the Exception using the catch block but there, you have also written throw which throws the exception again and if you haven't handled it into the calling method, your app will crash.
Either try removing throw from your catch block, or handle Exception again into a calling method.
Like
try
{
var result = Get("myUrl");
}
Catch(Exception ex)
{
//Handle it here too
}
I have this unit test, it compiles and runs well. How can I represent this in a test case document for my unit test (Id, purpose, preconditions, input and expected output). What would be the input and output since I don't know the actual input of the httpservletrequest and don't know either the response (httpservletresponse). I just mocked these objects so I can perform my unit test. I was planning to do 'AssertEquals' but I don't know what could be the expected output.
#Test
public void testSearchPanelists() throws IOException {
HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
HttpSession hs = Mockito.mock(HttpSession.class);
PowerMockito.mockStatic(SearchPanelist.class);
Controller.searchPanelists(req, res, hs);
PowerMockito.verifyStatic(SearchPanelist.class);
SearchPanelist.searchPanelists(req,res,hs);
}
I have this in Controller class:
public static void searchPanelists(HttpServletRequest req, HttpServletResponse res, HttpSession hs) throws IOException
{
SearchPanelist.searchPanelists(req, res, hs);
}
and this in SearchPanelist class:
public static void searchPanelists(HttpServletRequest req, HttpServletResponse res, HttpSession hs) throws IOException
{
HashMap<String, String> searchCriteria = new HashMap<String, String>();
//Let's pull the values from the search form.
searchCriteria.put("FirstName", req.getParameter("pFName"));
searchCriteria.put("LastName", req.getParameter("pLName"));
searchCriteria.put("Institution", req.getParameter("pInstitution"));
searchCriteria.put("Address", req.getParameter("pAddress"));
searchCriteria.put("City", req.getParameter("pCity"));
searchCriteria.put("State", req.getParameter("pState"));
searchCriteria.put("ZipCode", req.getParameter("pZip"));
searchCriteria.put("Telephone", req.getParameter("pTelephone"));
searchCriteria.put("Email", req.getParameter("pEmail"));
searchCriteria.put("Gender", req.getParameter("pGender"));
searchCriteria.put("Ethnicity", req.getParameter("pEthnicity"));
searchCriteria.put("Expertise", req.getParameter("pExpertise"));
searchCriteria.put("ISCID", req.getParameter("pISCID"));
ArrayList<PanelistProfile> userProfile = DBManager.getPanelists(searchCriteria);
if(userProfile == null)
res.sendRedirect("messagePage?messageCode=No Panelists Found.");
else
{
hs.setAttribute("Panelists", userProfile);
res.sendRedirect("displayPanelists.jsp");
}
}
I am having trouble fetching result from my amazon elastic search cluster using the amazon java SDK and an IAm user credential. Now the issue is that when the PATH string is equal to "/" then I am able to fetch the result correctly but when I try with a different path for e.g "/private-search" then I get a 403 forbidden error. Even when for the path that has public access I am getting a 403 forbidden error for this IAm user but it works if I remove "signer.sign(requestToSign, credentials);" line in performSigningSteps method(for public resource only).
My policy in AWS gives this IAM user access to everything in my elastic search service. And also what can I do to avoid hard-coding the access key and secret key in source code?
private static final String SERVICE_NAME = "es";
private static final String REGION = "region-name";
private static final String HOST = "host-name";
private static final String ENDPOINT_ROOT = "http://" + HOST;
private static final String PATH = "/private-search";
private static final String ENDPOINT = ENDPOINT_ROOT + PATH;
private static String accessKey = "IAmUserAccesskey"
private static String secretKey = "IAmUserSecretkey"
public static void main(String[] args) {
// Generate the request
Request<?> request = generateRequest();
// Perform Signature Version 4 signing
performSigningSteps(request);
// Send the request to the server
sendRequest(request);
}
private static Request<?> generateRequest() {
Request<?> request = new DefaultRequest<Void>(SERVICE_NAME);
request.setContent(new ByteArrayInputStream("".getBytes()));
request.setEndpoint(URI.create(ENDPOINT));
request.setHttpMethod(HttpMethodName.GET);
return request;
}
private static void performSigningSteps(Request<?> requestToSign) {
AWS4Signer signer = new AWS4Signer();
signer.setServiceName(requestToSign.getServiceName());
signer.setRegionName(REGION);
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
signer.sign(requestToSign, credentials);
}
private static void sendRequest(Request<?> request) {
ExecutionContext context = new ExecutionContext();
ClientConfiguration clientConfiguration = new ClientConfiguration();
AmazonHttpClient client = new AmazonHttpClient(clientConfiguration);
MyHttpResponseHandler<Void> responseHandler = new MyHttpResponseHandler<Void>();
MyErrorHandler errorHandler = new MyErrorHandler();
Void response = client.execute(request, responseHandler, errorHandler, context);
}
public static class MyHttpResponseHandler<T> implements HttpResponseHandler<AmazonWebServiceResponse<T>> {
#Override
public AmazonWebServiceResponse<T> handle(com.amazonaws.http.HttpResponse response) throws Exception {
InputStream responseStream = response.getContent();
String responseString = convertStreamToString(responseStream);
System.out.println(responseString);
AmazonWebServiceResponse<T> awsResponse = new AmazonWebServiceResponse<T>();
return awsResponse;
}
#Override
public boolean needsConnectionLeftOpen() {
return false;
}
}
public static class MyErrorHandler implements HttpResponseHandler<AmazonServiceException> {
#Override
public AmazonServiceException handle(com.amazonaws.http.HttpResponse response) throws Exception {
System.out.println("In exception handler!");
AmazonServiceException ase = new AmazonServiceException("exception.");
ase.setStatusCode(response.getStatusCode());
ase.setErrorCode(response.getStatusText());
return ase;
}
#Override
public boolean needsConnectionLeftOpen() {
return false;
}
}
public static String convertStreamToString(InputStream is) throws IOException {
// To convert the InputStream to String we use the
// Reader.read(char[] buffer) method. We iterate until the
// Reader return -1 which means there's no more data to
// read. We use the StringWriter class to produce the string.
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
}
finally {
is.close();
}
return writer.toString();
}
return "";
}
I've got this below restful webservice code. But when the webservice is accessed I'm getting "MIME media type application/pdf was not found". The docService.findByVersionId does return a "TestDoc" which holds the pdf content as byte[].
Can you please help me in fixing this problem?
#GET
#Path("/getPdf/{versionId}")
#Produces("application/pdf")
public Response getPdfFile(#PathParam("versionId") final String versionId) {
try {
final TestDoc doc = this.docService.findByVersionId(versionId);
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
final BufferedOutputStream bos = new BufferedOutputStream(byteArrayOutputStream);
final byte[] pdfContent = doc.getPdfDoc();
bos.write(pdfContent);
bos.flush();
bos.close();
return Response.ok(byteArrayOutputStream).build();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
error:
Exception:
2014-01-02 12:42:07,497 ERROR [STDERR] 02-Jan-2014 12:42:07 com.sun.jersey.spi.container.ContainerResponse write
SEVERE: A message body writer for Java class java.io.ByteArrayOutputStream, and Java type class java.io.ByteArrayOutputStream, and MIME media type application/pdf was not found
It seems that you can't use the ByteArrayOutputStream. The solution is to use StreamingOutput.
#GET
public Response generatePDF(String content) {
try {
ByteArrayOutputStream outputStream = service.generatePDF(content);
StreamingOutput streamingOutput = getStreamingOutput(outputStream);
Response.ResponseBuilder responseBuilder = Response.ok(streamingOutput, "application/pdf");
responseBuilder.header("Content-Disposition", "attachment; filename=Filename.pdf");
return responseBuilder.build();
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage(), e);
return Response.serverError().build();
}
}
private StreamingOutput getStreamingOutput(final ByteArrayOutputStream byteArrayOutputStream) {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException, WebApplicationException {
byteArrayOutputStream.writeTo(output);
}
};
}