List of usage examples for java.io StringWriter getBuffer
public StringBuffer getBuffer()
From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = buildUrl(req);/* w ww . j a va 2 s . c om*/ Map<String, ?> params = new HashMap<String, Object>(); Map<String, String> resultMap = new HashMap<String, String>(); try { params = deserializer.deserialize(req.getReader()); if ("/login".equals(path)) { SessionService sessionService = (SessionService) findInstance(SessionServiceImpl.class); User user = sessionService.login((String) params.get("username"), (String) params.get("password")); resultMap.put("outcome", "success"); req.getSession().setAttribute("user", user); if (user != null) { resultMap.put("result", serializer.deepSerialize(user)); } } else if ("/logout".equals(path)) { req.getSession().removeAttribute("user"); req.getSession().invalidate(); resultMap.put("outcome", "success"); } else { Method m = findRestMethod(RESTMethod.POST, path); @SuppressWarnings("unchecked") Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass()); Object args[] = new Object[m.getParameterTypes().length]; int i = 0; for (Annotation[] annotations : m.getParameterAnnotations()) { RESTParam restAnnotation = null; for (Annotation a : annotations) { if (a.annotationType() == RESTParam.class) { restAnnotation = (RESTParam) a; break; } } if (restAnnotation == null) { throw new RuntimeException("REST method has non REST annotated parameter"); } Class<?> targetClass = m.getParameterTypes()[i]; Object value; if (restAnnotation.session()) { value = convert(req.getSession().getAttribute(restAnnotation.value()), targetClass); } else { value = convert(params.get(restAnnotation.value()), targetClass); } if (value == null) { throw new RuntimeException( "Parameter " + restAnnotation.value() + " not found in request for " + path); } args[i++] = value; } Object result = m.invoke(instance, args); resultMap.put("outcome", "success"); if (result != null) { resultMap.put("result", serializer.deepSerialize(result)); } } } catch (Exception e) { Throwable t = e; if (e instanceof InvocationTargetException) { t = e.getCause(); } StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); resultMap.put("outcome", "error"); resultMap.put("message", t.getMessage()); resultMap.put("type", t.getClass().getCanonicalName()); resultMap.put("stacktrace", stringWriter.getBuffer().toString()); } resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); serializer.deepSerialize(resultMap, resp.getWriter()); }
From source file:admin.AuthenticationServletTest.java
@Test public void test() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); HttpSession session = mock(HttpSession.class); RequestDispatcher rd = mock(RequestDispatcher.class); rd.include(request, response);//from w w w . ja v a 2 s . c o m ServletContext sc = mock(ServletContext.class); when(request.getParameter("action")).thenReturn("login"); when(request.getParameter("userName")).thenReturn("pmahend1"); when(request.getParameter("passWord")).thenReturn("pmahend1"); // when("url").thenReturn("/home.jsp"); //when(pool.getConnection()).thenReturn(connection); //when(request.getParameter("rememberMe")).thenReturn("Y"); when(request.getSession()).thenReturn(session); //when(request.getRequestDispatcher("/home.jsp")).thenReturn(rd); //when(request.getServletContext().getRequestDispatcher("/home.jsp")).thenReturn(rd); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); //when(response.getWriter()).thenReturn(pw); System.out.println("Step Test 1"); new AuthenticationServlet().doPost(request, response); System.out.println("Step Test 2"); List<Book> books = BookDB.selectAllBooks(); //Verify the session attribute value //verify(request).setAttribute("books", books); // request.setAttribute("books", books); //verify(rd).forward(request, response); verify(request, atLeast(1)).getParameter("action"); String result = sw.getBuffer().toString().trim(); System.out.println("Result: " + result); assertEquals("", result); }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.MemberGatewayHubServiceTest.java
/** * Tests that service returns json object * *//*from ww w. ja va2 s. c o m*/ @Test public void testResponseNotNull() { System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE BEGIN : NULL RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE --------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_5_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println( "MemberGatewayHubServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println("MemberGatewayHubServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); Assert.assertNotNull( "MemberGatewayHubServiceTest :: Server returned null response for MemberGatewayHub", jsonObj.getJSONObject("MemberGatewayHub")); } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("MemberGatewayHubServiceTest :: No Http connection was established."); } System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE END : NULL RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE ------\n"); }
From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String path = buildUrl(req);/*from w w w.j ava 2 s. c o m*/ resp.setContentType("application/json"); resp.setCharacterEncoding("UTF-8"); if ("/list".equals(path)) { List<String> names = new ArrayList<String>(); try { for (Class<? extends Service> sc : serviceClasses) { Method m; m = sc.getMethod("getName"); @SuppressWarnings("unchecked") Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass()); String result = instance.getName(); names.add(result); } serializer.deepSerialize(names, resp.getWriter()); } catch (Exception e) { Map<String, String> resultMap = new HashMap<String, String>(); Throwable t = e; if (e instanceof InvocationTargetException) { t = e.getCause(); } StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); resultMap.put("outcome", "error"); resultMap.put("message", t.getMessage()); resultMap.put("type", t.getClass().getCanonicalName()); resultMap.put("stacktrace", stringWriter.getBuffer().toString()); serializer.deepSerialize(resultMap, resp.getWriter()); } } else { Method m = findRestMethod(RESTMethod.GET, path); @SuppressWarnings("unchecked") Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass()); try { Object result = m.invoke(instance); serializer.deepSerialize(result, resp.getWriter()); } catch (Exception e) { Map<String, String> resultMap = new HashMap<String, String>(); Throwable t = e; if (e instanceof InvocationTargetException) { t = e.getCause(); } StringWriter stringWriter = new StringWriter(); PrintWriter writer = new PrintWriter(stringWriter); t.printStackTrace(writer); resultMap.put("outcome", "error"); resultMap.put("message", t.getMessage()); resultMap.put("type", t.getClass().getCanonicalName()); resultMap.put("stacktrace", stringWriter.getBuffer().toString()); serializer.deepSerialize(resultMap, resp.getWriter()); } } }
From source file:com.cts.ptms.tracking.UPSTracking.java
@Override public CustomTrackingResponse getTrackingDetails(CustomTrackingRequest customTrackingRequest) throws TrackingException { CustomTrackingResponse customTrackingResponse = null; try {/*from w w w.j av a 2s.c o m*/ com.cts.ptms.model.gls.AccessRequest accessRequest = null; com.cts.ptms.model.ups.generated.trackrequest.TrackRequest trackRequest = null; com.cts.ptms.model.ups.generated.trackresponse.TrackResponse trackResponse = null; //Create JAXBContext and marshaller for AccessRequest object JAXBContext accessRequestJAXBC = JAXBContext.newInstance(AccessRequest.class.getPackage().getName()); Marshaller accessRequestMarshaller = accessRequestJAXBC.createMarshaller(); com.cts.ptms.model.gls.ObjectFactory accessRequestObjectFactory = new com.cts.ptms.model.gls.ObjectFactory(); accessRequest = accessRequestObjectFactory.createAccessRequest(); AccessRequest receivedAccessReq = customTrackingRequest.getAccessRequest(); //Populate the access request accessRequest.setAccessLicenseNumber(receivedAccessReq.getAccessLicenseNumber()); accessRequest.setUserId(receivedAccessReq.getUserId()); accessRequest.setPassword(receivedAccessReq.getPassword()); TrackRequestDetails inputRequestDtls = customTrackingRequest.getTrackRequestDetails(); if (inputRequestDtls == null || inputRequestDtls.getTrackingNumber() == null) { throw new TrackingException("No Tracking Tracking number found in the request."); } //Create JAXBContext and marshaller for TrackRequest object JAXBContext trackRequestJAXBC = JAXBContext.newInstance( com.cts.ptms.model.ups.generated.trackrequest.TrackRequest.class.getPackage().getName()); Marshaller trackRequestMarshaller = trackRequestJAXBC.createMarshaller(); com.cts.ptms.model.ups.generated.trackrequest.ObjectFactory requestObjectFactory = new com.cts.ptms.model.ups.generated.trackrequest.ObjectFactory(); trackRequest = requestObjectFactory.createTrackRequest(); //Populate the Track request com.cts.ptms.model.ups.generated.trackrequest.Request request = new com.cts.ptms.model.ups.generated.trackrequest.Request(); com.cts.ptms.model.ups.generated.trackrequest.TransactionReference transReference = new com.cts.ptms.model.ups.generated.trackrequest.TransactionReference(); transReference.setCustomerContext("Tracking customer shipment Details"); request.setTransactionReference(transReference); request.setRequestAction("Track"); request.getRequestOption().addAll(inputRequestDtls.getRequestOptions()); trackRequest.setRequest(request); trackRequest.setTrackingNumber(inputRequestDtls.getTrackingNumber()); //Get String out of access request and track request objects. StringWriter strWriter = new StringWriter(); accessRequestMarshaller.marshal(accessRequest, strWriter); trackRequestMarshaller.marshal(trackRequest, strWriter); strWriter.flush(); strWriter.close(); System.out.println("Request: " + strWriter.getBuffer().toString()); if (properties == null) { throw new TrackingException("Error while loading the ups properties."); } URLConnection httpUrlConnection = ShipmentCommonUtilities.contactService( strWriter.getBuffer().toString(), new URL(properties.getProperty("INTEGRATION_URL"))); String strResults = null; if (httpUrlConnection != null) { strResults = ShipmentCommonUtilities.readURLConnection(httpUrlConnection); } else throw new TrackingException("Exception occured while contacting the service.."); //Parse response object JAXBContext trackResponseJAXBC = JAXBContext.newInstance(TrackResponse.class.getPackage().getName()); Unmarshaller trackUnmarshaller = trackResponseJAXBC.createUnmarshaller(); ByteArrayInputStream input = new ByteArrayInputStream(strResults.getBytes()); Object objResponse = trackUnmarshaller.unmarshal(input); trackResponse = (com.cts.ptms.model.ups.generated.trackresponse.TrackResponse) objResponse; List<TrackingError> trackingErrors = null; if (trackResponse.getResponse() != null) { String responseCode = trackResponse.getResponse().getResponseStatusCode(); customTrackingResponse = populateResponse(trackResponse); if (responseCode != null && responseCode.equals("1")) { System.out.println("Response Status: " + trackResponse.getResponse().getResponseStatusCode()); System.out.println("Response Status Description: " + trackResponse.getResponse().getResponseStatusDescription()); } else if (responseCode != null && responseCode.equals("0")) { trackingErrors = new ArrayList<TrackingError>(0); List<com.cts.ptms.model.ups.generated.trackresponse.Error> resErrors = trackResponse .getResponse().getError(); if (resErrors != null && !resErrors.isEmpty()) { for (com.cts.ptms.model.ups.generated.trackresponse.Error resError : resErrors) { TrackingError trackingError = new TrackingError(); trackingError.setErrorSeverity(resError.getErrorSeverity()); trackingError.setErrorCode(resError.getErrorCode()); trackingError.setErrorDescription(resError.getErrorDescription()); trackingErrors.add(trackingError); } } customTrackingResponse.setError(trackingErrors); } } } catch (TrackingException e) { System.out.println("Exception occurred at : " + e.getMessage()); } catch (Exception e) { System.out.println("Exception occurred at : " + e.getMessage()); throw new TrackingException(e.getMessage()); } return customTrackingResponse; }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.MemberGatewayHubServiceTest.java
/** * * Tests that response is for same region * * Test method for {@link com.vmware.gemfire.tools.pulse.internal.service.MemberGatewayHubService#execute(javax.servlet.http.HttpServletRequest)}. * */// w ww .j a v a 2 s. c o m @Test public void testResponseIsGatewaySender() { System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE BEGIN : IS GATEWAY SENDER IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_5_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println( "MemberGatewayHubServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println("MemberGatewayHubServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); JSONObject memberGatewayHubObj = jsonObj.getJSONObject("MemberGatewayHub"); Assert.assertNotNull( "MemberGatewayHubServiceTest :: Server returned null response for MemberGatewayHub", memberGatewayHubObj); Assert.assertTrue( "MemberGatewayHubServiceTest :: Server did not return 'isGatewaySender' for member", memberGatewayHubObj.has("isGatewaySender")); Boolean boolIsGatewaySender = memberGatewayHubObj.getBoolean("isGatewaySender"); Assert.assertEquals( "MemberGatewayHubServiceTest :: Server returned wrong value for 'isGatewaySender'. Expected 'isGatewaySender' = true, actual 'isGatewaySender' = " + boolIsGatewaySender, boolIsGatewaySender, true); } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("MemberGatewayHubServiceTest :: No Http connection was established."); } System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE END : IS GATEWAY SENDER IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE ------\n"); }
From source file:org.artifactory.engine.DownloadServiceImpl.java
private String jsonProperties(RepoPath repoPath, Properties properties) throws IOException { ItemProperties itemProperties = new ItemProperties(); for (String propertyName : properties.keySet()) { Set<String> propertySet = properties.get(propertyName); if ((propertySet != null) && !propertySet.isEmpty()) { itemProperties.properties.put(propertyName, Iterables.toArray(propertySet, String.class)); }/*from w ww. ja v a2s. c om*/ } itemProperties.slf = repoPath.getRepoKey() + "/" + repoPath.getPath(); StringWriter out = new StringWriter(); JsonGenerator generator = JacksonFactory.createJsonGenerator(out); generator.writeObject(itemProperties); return out.getBuffer().toString(); }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.MemberGatewayHubServiceTest.java
/** * * Tests that response is for same region * * Test method for {@link com.vmware.gemfire.tools.pulse.internal.service.MemberGatewayHubService#execute(javax.servlet.http.HttpServletRequest)}. * *//*from ww w . j av a 2 s .c om*/ @Test public void testResponseNoAsyncEventQueues() { System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE BEGIN : NO ASYNC EVENT QUEUES IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_6_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println( "MemberGatewayHubServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println("MemberGatewayHubServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); JSONObject memberGatewayHubObj = jsonObj.getJSONObject("MemberGatewayHub"); Assert.assertNotNull( "MemberGatewayHubServiceTest :: Server returned null response for MemberGatewayHub", memberGatewayHubObj); Assert.assertTrue( "MemberGatewayHubServiceTest :: Server did not return 'asyncEventQueues' for member", memberGatewayHubObj.has("asyncEventQueues")); JSONArray arrAsyncEventQueues = memberGatewayHubObj.getJSONArray("asyncEventQueues"); Assert.assertNotNull( "MemberGatewayHubServiceTest :: Server returned null response for 'asyncEventQueues'", arrAsyncEventQueues); Assert.assertTrue( "MemberGatewayHubServiceTest :: Server returned non-empty array for member 'pnq-visitor2' which has no event queues", (arrAsyncEventQueues.length() == 0)); } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("MemberGatewayHubServiceTest :: No Http connection was established."); } System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE END : NO ASYNC EVENT QUEUES PROPERTIES IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE ------\n"); }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.MemberGatewayHubServiceTest.java
/** * * Tests that response is for same region * * Test method for {@link com.vmware.gemfire.tools.pulse.internal.service.MemberGatewayHubService#execute(javax.servlet.http.HttpServletRequest)}. * *///from w ww. ja v a 2 s . c o m @Test public void testResponseGatewaySenderCount() { System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE BEGIN : GATEWAY SENDER COUNT IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_5_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println( "MemberGatewayHubServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println("MemberGatewayHubServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); JSONObject memberGatewayHubObj = jsonObj.getJSONObject("MemberGatewayHub"); Assert.assertNotNull( "MemberGatewayHubServiceTest :: Server returned null response for MemberGatewayHub", memberGatewayHubObj); Assert.assertTrue( "MemberGatewayHubServiceTest :: Server did not return 'isGatewaySender' for member", memberGatewayHubObj.has("isGatewaySender")); Boolean boolIsGatewaySender = memberGatewayHubObj.getBoolean("isGatewaySender"); Assert.assertTrue( "MemberGatewayHubServiceTest :: Server did not return 'gatewaySenders' for member", memberGatewayHubObj.has("gatewaySenders")); JSONArray arrGatewaySender = memberGatewayHubObj.getJSONArray("gatewaySenders"); Assert.assertNotNull( "MemberGatewayHubServiceTest :: Server returned null response for 'gatewaySenders'", arrGatewaySender); Assert.assertTrue( "MemberGatewayHubServiceTest :: Server returned mis-matched values for 'isGatewaySender' and gateway senders array count", ((boolIsGatewaySender && (arrGatewaySender.length() > 0)) || ((!boolIsGatewaySender) && (arrGatewaySender.length() == 0)))); } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("MemberGatewayHubServiceTest :: No Http connection was established."); } System.out.println( "MemberGatewayHubServiceTest :: ------TESTCASE END : GATEWAY SENDER COUNT IN RESPONSE CHECK FOR MEMBER GATEWAY HUB SERVICE ------\n"); }
From source file:net.sf.jabref.gui.entryeditor.EntryEditor.java
public static String getSourceString(BibEntry entry, BibDatabaseMode type) throws IOException { StringWriter stringWriter = new StringWriter(200); LatexFieldFormatter formatter = LatexFieldFormatter .buildIgnoreHashes(LatexFieldFormatterPreferences.fromPreferences(Globals.prefs)); new BibEntryWriter(formatter, false).writeWithoutPrependedNewlines(entry, stringWriter, type); return stringWriter.getBuffer().toString(); }