List of usage examples for java.io Writer toString
public String toString()
From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java
@Override public void updateSimulationScore(String modelSetId, String simulationSessionId, String processArtifactId, Long timestamp, String userId, SimulationScoresMap scoreMap) throws LpRestException { HttpClient httpClient = this.getClient(); String uri = String.format("%s/learnpad/or/bridge/%s/simulationscore", DefaultRestResource.REST_URI, modelSetId);/*from www. j a v a 2s. c o m*/ PostMethod postMethod = new PostMethod(uri); postMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML); String contentType = "application/xml"; NameValuePair[] queryString = new NameValuePair[4]; queryString[0] = new NameValuePair("simulationsessionid", simulationSessionId); queryString[1] = new NameValuePair("processartifactid", processArtifactId); queryString[2] = new NameValuePair("timestamp", timestamp.toString()); queryString[3] = new NameValuePair("userid", userId); postMethod.setQueryString(queryString); try { Writer scoreMapWriter = new StringWriter(); JAXBContext jc = JAXBContext.newInstance(SimulationScoresMap.class); jc.createMarshaller().marshal(scoreMap, scoreMapWriter); RequestEntity requestEntity = new StringRequestEntity(scoreMapWriter.toString(), contentType, "UTF-8"); postMethod.setRequestEntity(requestEntity); httpClient.executeMethod(postMethod); } catch (IOException | JAXBException e) { throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause()); } }
From source file:fr.mby.portal.web.controller.PortalController.java
/** * Perform internal rendering.// ww w . j a v a 2 s . c o m * * @param request * @param response * @param view * @param appsToRender * @throws ServletException * @throws IOException */ protected void renderApp(final HttpServletRequest request, final HttpServletResponse response, final ModelAndView view, final List<IApp> appsToRender) throws ServletException, IOException { final Map<IApp, String> appsRendered = new HashMap<IApp, String>(8); if (appsToRender != null) { for (final IApp app : appsToRender) { final ServletContext loginContext = this.servletContext.getContext(app.getWebPath()); if (loginContext != null) { final Writer sout = new StringWriter(1024); final OpaHttpServletRequest opaRequest = new OpaHttpServletRequest(request, app); final SwallowingHttpServletResponse swallowingResponse = new SwallowingHttpServletResponse( response, sout, "UTF-8"); loginContext.getRequestDispatcher("/").forward(opaRequest, swallowingResponse); final String appRendered = sout.toString(); final String appContent = this.stripHeaders(appRendered); appsRendered.put(app, appContent); } } } view.addObject(PortalController.APPS_RENDERED, appsRendered); }
From source file:ddf.security.pdp.realm.xacml.processor.BalanaClientTest.java
@Test public void testEvaluateroleuseractionquerycitizenshipCA() throws Exception { LOGGER.debug("\n\n\n##### testEvaluate_role_user_action_query_citizenship_CA"); final String country = "CA"; testSetup();// ww w . j a va 2 s . com RequestType xacmlRequestType = new RequestType(); xacmlRequestType.setCombinedDecision(false); xacmlRequestType.setReturnPolicyIdList(false); AttributesType actionAttributes = new AttributesType(); actionAttributes.setCategory(ACTION_CATEGORY); AttributeType actionAttribute = new AttributeType(); actionAttribute.setAttributeId(ACTION_ID); actionAttribute.setIncludeInResult(false); AttributeValueType actionValue = new AttributeValueType(); actionValue.setDataType(STRING_DATA_TYPE); actionValue.getContent().add(QUERY_ACTION); actionAttribute.getAttributeValue().add(actionValue); actionAttributes.getAttribute().add(actionAttribute); AttributesType subjectAttributes = new AttributesType(); subjectAttributes.setCategory(SUBJECT_CATEGORY); AttributeType subjectAttribute = new AttributeType(); subjectAttribute.setAttributeId(SUBJECT_ID); subjectAttribute.setIncludeInResult(false); AttributeValueType subjectValue = new AttributeValueType(); subjectValue.setDataType(STRING_DATA_TYPE); subjectValue.getContent().add(TEST_USER_2); subjectAttribute.getAttributeValue().add(subjectValue); subjectAttributes.getAttribute().add(subjectAttribute); AttributeType roleAttribute = new AttributeType(); roleAttribute.setAttributeId(ROLE_CLAIM); roleAttribute.setIncludeInResult(false); AttributeValueType roleValue = new AttributeValueType(); roleValue.setDataType(STRING_DATA_TYPE); roleValue.getContent().add(ROLE); roleAttribute.getAttributeValue().add(roleValue); subjectAttributes.getAttribute().add(roleAttribute); AttributesType categoryAttributes = new AttributesType(); categoryAttributes.setCategory(PERMISSIONS_CATEGORY); AttributeType citizenshipAttribute = new AttributeType(); citizenshipAttribute.setAttributeId(CITIZENSHIP_ATTRIBUTE); citizenshipAttribute.setIncludeInResult(false); AttributeValueType citizenshipValue = new AttributeValueType(); citizenshipValue.setDataType(STRING_DATA_TYPE); citizenshipValue.getContent().add(country); citizenshipAttribute.getAttributeValue().add(citizenshipValue); categoryAttributes.getAttribute().add(citizenshipAttribute); xacmlRequestType.getAttributes().add(actionAttributes); xacmlRequestType.getAttributes().add(subjectAttributes); xacmlRequestType.getAttributes().add(categoryAttributes); BalanaClient pdp = new BalanaClient(tempDir.getCanonicalPath(), new XmlParser()); // Perform Test ResponseType xacmlResponse = pdp.evaluate(xacmlRequestType); // Verify JAXBContext jaxbContext = JAXBContext.newInstance(ResponseType.class); Marshaller marshaller = jaxbContext.createMarshaller(); ObjectFactory objectFactory = new ObjectFactory(); Writer writer = new StringWriter(); marshaller.marshal(objectFactory.createResponse(xacmlResponse), writer); LOGGER.debug("\nXACML 3.0 Response:\n{}", writer.toString()); assertEquals(xacmlResponse.getResult().get(0).getDecision(), DecisionType.DENY); }
From source file:ddf.security.pdp.realm.xacml.processor.XacmlClientTest.java
@Test public void testEvaluateroleuseractionquerycitizenshipCA() throws Exception { LOGGER.debug("\n\n\n##### testEvaluate_role_user_action_query_citizenship_CA"); final String country = "CA"; testSetup();// w w w . j a v a2 s. com RequestType xacmlRequestType = new RequestType(); xacmlRequestType.setCombinedDecision(false); xacmlRequestType.setReturnPolicyIdList(false); AttributesType actionAttributes = new AttributesType(); actionAttributes.setCategory(ACTION_CATEGORY); AttributeType actionAttribute = new AttributeType(); actionAttribute.setAttributeId(ACTION_ID); actionAttribute.setIncludeInResult(false); AttributeValueType actionValue = new AttributeValueType(); actionValue.setDataType(STRING_DATA_TYPE); actionValue.getContent().add(QUERY_ACTION); actionAttribute.getAttributeValue().add(actionValue); actionAttributes.getAttribute().add(actionAttribute); AttributesType subjectAttributes = new AttributesType(); subjectAttributes.setCategory(SUBJECT_CATEGORY); AttributeType subjectAttribute = new AttributeType(); subjectAttribute.setAttributeId(SUBJECT_ID); subjectAttribute.setIncludeInResult(false); AttributeValueType subjectValue = new AttributeValueType(); subjectValue.setDataType(STRING_DATA_TYPE); subjectValue.getContent().add(TEST_USER_2); subjectAttribute.getAttributeValue().add(subjectValue); subjectAttributes.getAttribute().add(subjectAttribute); AttributeType roleAttribute = new AttributeType(); roleAttribute.setAttributeId(ROLE_CLAIM); roleAttribute.setIncludeInResult(false); AttributeValueType roleValue = new AttributeValueType(); roleValue.setDataType(STRING_DATA_TYPE); roleValue.getContent().add(ROLE); roleAttribute.getAttributeValue().add(roleValue); subjectAttributes.getAttribute().add(roleAttribute); AttributesType categoryAttributes = new AttributesType(); categoryAttributes.setCategory(PERMISSIONS_CATEGORY); AttributeType citizenshipAttribute = new AttributeType(); citizenshipAttribute.setAttributeId(CITIZENSHIP_ATTRIBUTE); citizenshipAttribute.setIncludeInResult(false); AttributeValueType citizenshipValue = new AttributeValueType(); citizenshipValue.setDataType(STRING_DATA_TYPE); citizenshipValue.getContent().add(country); citizenshipAttribute.getAttributeValue().add(citizenshipValue); categoryAttributes.getAttribute().add(citizenshipAttribute); xacmlRequestType.getAttributes().add(actionAttributes); xacmlRequestType.getAttributes().add(subjectAttributes); xacmlRequestType.getAttributes().add(categoryAttributes); XacmlClient pdp = new XacmlClient(tempDir.getCanonicalPath(), new XmlParser()); // Perform Test ResponseType xacmlResponse = pdp.evaluate(xacmlRequestType); // Verify JAXBContext jaxbContext = JAXBContext.newInstance(ResponseType.class); Marshaller marshaller = jaxbContext.createMarshaller(); ObjectFactory objectFactory = new ObjectFactory(); Writer writer = new StringWriter(); marshaller.marshal(objectFactory.createResponse(xacmlResponse), writer); LOGGER.debug("\nXACML 3.0 Response:\n{}", writer.toString()); assertEquals(xacmlResponse.getResult().get(0).getDecision(), DecisionType.DENY); }
From source file:org.ambraproject.service.xml.XMLServiceImpl.java
@Override public InputStream getTransformedInputStream(InputStream xml) throws ApplicationException { try {//from www . j a v a2 s . c o m final Writer writer = new StringWriter(1000); Document doc = createDocBuilder().parse(xml); Transformer transformer = this.getTranslet(doc); DOMSource domSource = new DOMSource(doc); transformer.transform(domSource, new StreamResult(writer)); return new ByteArrayInputStream(writer.toString().getBytes("UTF-8")); } catch (Exception e) { throw new ApplicationException(e); } }
From source file:org.cloudifysource.restDoclet.generation.Generator.java
/** * Creates the REST API documentation in HTML form, using the controllers' * data and the velocity template.//w ww .ja va 2 s.c om * * @param controllers . * @return string that contains the documentation in HTML form. * @throws Exception . */ public String generateHtmlDocumentation(final List<DocController> controllers) throws Exception { logger.log(Level.INFO, "Generate velocity using template: " + velocityTemplatePath + (isUserDefineTemplatePath ? File.separator + velocityTemplateFileName + " (got template path from user)" : "(default template path)")); Properties p = new Properties(); p.setProperty("directive.set.null.allowed", "true"); if (isUserDefineTemplatePath) { p.setProperty("file.resource.loader.path", velocityTemplatePath); } else { p.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); p.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); } Velocity.init(p); VelocityContext ctx = new VelocityContext(); ctx.put("controllers", controllers); ctx.put("version", version); ctx.put("docCssPath", docCssPath); Writer writer = new StringWriter(); Template template = Velocity.getTemplate(velocityTemplateFileName); template.merge(ctx, writer); return writer.toString(); }
From source file:com.denimgroup.threadfix.service.channel.SkipfishChannelImporter.java
private String getStringFromInputStream(InputStream stream) { Writer writer = new StringWriter(); String returnValue = null;//from w ww .j a v a 2 s. c o m try { IOUtils.copy(stream, writer, "UTF-8"); returnValue = writer.toString(); writer.close(); } catch (IOException e) { e.printStackTrace(); } finally { closeInputStream(stream); } return returnValue; }
From source file:io.neba.core.rendering.BeanRendererImpl.java
public String renderInternal(Object object, String templatePath, Map<String, Object> additionalContextElements) { final Writer writer = new FastStringWriter(); final VelocityBindings bindings = prepareBindings(object); merge(additionalContextElements, bindings); final VelocityContext context = new VelocityContext(bindings); String renderedObject;/*from w w w . ja v a 2 s . c o m*/ try { this.engine.getTemplate(templatePath).merge(context, writer); } catch (Exception e) { throw new RuntimeException("Unable to render " + object + " with template " + templatePath + ".", e); } renderedObject = writer.toString(); return renderedObject; }
From source file:org.geosdi.geoplatform.gui.server.service.impl.PublisherService.java
@Override public String publishLayerPreview(HttpServletRequest httpServletRequest, List<String> layerList, boolean reloadCluster) throws GeoPlatformException { try {//from w w w.j ava2 s. c o m sessionUtility.getLoggedAccount(httpServletRequest); } catch (GPSessionTimeout timeout) { throw new GeoPlatformException(timeout); } String result = null; try { geoPlatformPublishClient.publishAll(httpServletRequest.getSession().getId(), "previews", "dataTest", layerList); if (reloadCluster) { HttpResponse response = httpclient.execute(targetHost, httpget, localContext); // HttpResponse response = httpclient.execute(get, localContext); InputStream is = response.getEntity().getContent(); 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(); } result = writer.toString(); } } catch (ResourceNotFoundFault ex) { logger.error("Error on publish shape: " + ex); throw new GeoPlatformException("Error on publish shape."); } catch (FileNotFoundException ex) { logger.error("Error on publish shape: " + ex); throw new GeoPlatformException("Error on publish shape."); } catch (MalformedURLException e) { logger.error("Error on cluster url: " + e); throw new GeoPlatformException(new GPReloadURLException("Error on cluster url.")); } catch (IOException e) { logger.error("Error on reloading cluster: " + e); throw new GeoPlatformException(new GPReloadURLException("Error on reloading cluster.")); } return result; }
From source file:any.servable.LsServable.java
public void process(String cmd, String content, BlockingQueue<Message> outQueue) { logger.info("start LS SERVABLE"); String filename = content.substring(0, content.length()); File file = new File(filename); try {//from w ww.j ava2s .c om File[] list = file.listFiles(new FilenameFilter() { @Override public boolean accept(File arg0, String name) { return !(name.startsWith(".") && !(name.endsWith("~"))); } }); StringBuilder sb = new StringBuilder(); // parent File fp = file.getParentFile(); logger.debug("do file: " + file + " - list: " + list + " fp:" + fp); if (fp != null) { TblUtil tbl = new TblUtil(); // DISPLAYTEXT tbl.set(TblUtil.DISPLAYTEXT, "[..] " + fp.getName()); // DETAILTEXT tbl.set(TblUtil.DETAILTEXT, "UP"); // // ICONRES // try { // JFileChooser ch = new JFileChooser(); // Icon icon = ch.getIcon(fp); // // BufferedImage offscreen = new BufferedImage( // icon.getIconHeight(), icon.getIconWidth(), // BufferedImage.TYPE_4BYTE_ABGR); // icon.paintIcon(null, offscreen.getGraphics(), 0, 0); // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ImageIO.write(offscreen, "png", baos); // baos.flush(); // byte[] imageInByte = baos.toByteArray(); // baos.close(); // // String strrep = new String(imageInByte); // if (!resSet.containsKey(strrep)) { // // System.out.println(fp.getName() + ": " // + icon.toString() + " " + icon.hashCode()); // // outQueue.put(new Message("res", icon.toString(), // "image/png", "NO", imageInByte)); // resSet.put(strrep, icon.toString()); // tbl.set(TblUtil.ICONRES, icon.toString()); // } else { // tbl.set(TblUtil.ICONRES, resSet.get(strrep)); // } // } catch (Error e) { // // TODO // System.err.println("Exception due to icon caught"); // // e.printStackTrace(); // } // TABCMD String tcmd = ((fp.isDirectory() ? "ls://host" : "get://host") + fp.getAbsolutePath()); tbl.set(TblUtil.TABCMD, tcmd); // DETAILCMD tbl.set(TblUtil.DETAILCMD, "tmpl:" + tcmd); // DELETECMD sb.append(tbl.makeCell()); } logger.debug("do list: " + list); if (list != null) { for (File f : list) { logger.debug("do file: " + f); TblUtil tbl = new TblUtil(); // DISPLAYTEXT tbl.set(TblUtil.DISPLAYTEXT, f.getName()); // DETAILTEXT tbl.set(TblUtil.DETAILTEXT, (f.isDirectory() ? " -- " : humanReadableByteCount(f.length(), true)) + " - " + df.format(f.lastModified())); // // ICONRES // try { // JFileChooser ch = new JFileChooser(); // Icon icon = ch.getIcon(f); // // BufferedImage offscreen = new BufferedImage( // icon.getIconHeight(), icon.getIconWidth(), // BufferedImage.TYPE_4BYTE_ABGR); // icon.paintIcon(null, offscreen.getGraphics(), 0, 0); // // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // ImageIO.write(offscreen, "png", baos); // baos.flush(); // byte[] imageInByte = baos.toByteArray(); // baos.close(); // // String strrep = new String(imageInByte); // if (!resSet.containsKey(strrep)) { // // System.out.println(f.getName() + ": " // + icon.toString() + " " + icon.hashCode()); // // outQueue.put(new Message("res", icon.toString(), // "image/png", "NO", imageInByte)); // resSet.put(strrep, icon.toString()); // tbl.set(TblUtil.ICONRES, icon.toString()); // } else { // tbl.set(TblUtil.ICONRES, resSet.get(strrep)); // } // // } catch (Error e) { // // TODO // System.err.println("Exception due to icon caught"); // // e.printStackTrace(); // } String fullpath = f.getAbsolutePath(); if (!fullpath.startsWith("/")) { fullpath = "/" + fullpath; } // TABCMD String tcmd = ((f.isDirectory() ? "ls://host" : "get://host") + fullpath); tbl.set(TblUtil.TABCMD, tcmd); // DETAILCMD tbl.set(TblUtil.DETAILCMD, "tmpl:" + tcmd); // DELETECMD sb.append(tbl.makeCell()); } outQueue.put( new Message("vset", file.getName(), TblUtil.TYPE, "YES", "1", sb.toString().getBytes())); } } catch (InterruptedException e) { e.printStackTrace(); final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); outQueue.add(new Message("vset", "_error", "text/plain", "YES", result.toString().getBytes())); // } catch (IOException e) { // e.printStackTrace(); // final Writer result = new StringWriter(); // final PrintWriter printWriter = new PrintWriter(result); // e.printStackTrace(printWriter); // outQueue.add(new Message("vset", "_error", "text/plain", "YES", // result.toString().getBytes())); } catch (NullPointerException e) { e.printStackTrace(); final Writer result = new StringWriter(); final PrintWriter printWriter = new PrintWriter(result); e.printStackTrace(printWriter); outQueue.add(new Message("vset", "_error", "text/plain", "YES", result.toString().getBytes())); } logger.info("finished LS SERVABLE"); }